PHP inserting into MYSQL

I have a some PHP and it appears to be working, to insert a message based on if the first and last name and email match. The database has two tables.
The code appears to run smoothly but nothing is entered in the database.
I am using xampp mysql.

here is my code:

$servername = "localhost";
$username = "******";
$password = "******";
$dbname = "adrian";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
};

$f = $_POST['fname'];
$l = $_POST['lname'];
$e = $_POST['email'];
$t =$_POST['telephone'];
$m =$_POST['message'];

$sql = "SELECT firstName, lastName, email from clienttb where firstName = $f AND lastName = $l AND email = $e";
$result = $conn->query($sql);
$rows = $result->num_rows;
echo $rows;
if($rows == 0){

$conn->query("INSERT INTO clienttb(firstName, lastName, email, dateCreated)values($f, $l, $e, CURRENT_TIMESTAMP()");
}

$conn->query("insert into messagetb(message, clientid, messageDate) values('".$m."',
(select clientid from clienttb where firstName = ".$f." AND lastName = ".$l." AND email = ".$e."),CURRENT_TIMESTAMP ());");

if ($conn->multi_query($sql) === TRUE) {
    echo "New records created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

Your code is wide open to an SQL Injection Attack. NEVER EVER put variables in a query, You need to use Prepared Statements. I suggest you use PDO. https://phpdelusions.net/pdo

Do not output internal System errors to the user. That info is only good to hackers.

Do not create variables for nothing.

You need to set a unique index on the columns you don’t want duplicated and then attempt the insert, capturing the duplicate error if any. What you have done creates a race condition.

There is no need to manually close the DB connection. Php does it automatically.
There is no need to over-code and check for true, the if statement already does that.

1 Like

Thats useful to know. However its only a sample website for an apprenticeship im going for.

Then isn’t that a good reason to apply this advice to your code? You do want to make a good impression, I would think.

3 Likes

So you’re learning that simple websites can be poorly programmed and open to fairly basic security vulnerabilities that can easily be prevented?

1 Like

Yeah thanks. Its frustrating but im learning which is great.

Im getting issues with num_rows from my select statement

That tells us absolutely nothing. WHAT issues? Did you turn on error reporting?

First remove echo $rows; and put in var_dump($rows); if you want to check if you get any result.

You have a bad logic here, if rows are 0 insert query ? Probably you meant if rows are more that 0.

Why you using this CURRENT_TIMESTAMP ()); you see the error here ?

Where is $sql variable here ? This already runs query here $result = $conn->query($sql); so i don’t see a point to put it here ($conn->multi_query($sql) === TRUE) since you run query already.

Try this

<?php

error_reporting(E_ALL);

$servername = "localhost";
$username = "******";
$password = "******";
$dbname = "adrian";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
};

// escape this post values !
$f = $conn->real_escape_string($_POST['fname']);
$l = $conn->real_escape_string($_POST['lname']);
$e = $conn->real_escape_string($_POST['email']);
$t = $conn->real_escape_string($_POST['telephone']);
$m = $conn->real_escape_string($_POST['message']);

$sql = "SELECT clientid, firstName, lastName, email from clienttb where firstName = '".$f."' AND lastName = '".$l."' AND email = '".$e."'";
$result = $conn->query($sql);
$data = $result->fetch_array(MYSQLI_BOTH); // will get you array for clientid

// if returned rows count more that 0, insert data
// put both querys here
if ($result->num_rows > 0) {
	$query = $conn->query("INSERT INTO clienttb(firstName, lastName, email, dateCreated) VALUES ('".$f."', '".$l."', '".$e."', CURRENT_TIMESTAMP()");
	$query .= $conn->query("INSERT INTO messagetb(message, clientid, messageDate) VALUES ('".$m."', '".$data['clientid']."' , CURRENT_TIMESTAMP()");
}

if ($query) {
    echo "New records created successfully";
} else {
    echo "Error: <br>" . $conn->error;
}

$conn->close();

?>

I have tried this and get: Undefined variable: query line 36

Put that piece of code like this, just after queries

// if returned rows count more that 0, insert data
	// put both querys here
	if ($result->num_rows > 0) {
		$query = $conn->query("INSERT INTO clienttb(firstName, lastName, email, dateCreated) VALUES ('".$f."', '".$l."', '".$e."', CURRENT_TIMESTAMP()");
		$query .= $conn->query("INSERT INTO messagetb(message, clientid, messageDate) VALUES ('".$m."', '".$data['clientid']."', CURRENT_TIMESTAMP()");

		if ($query) {
	    	echo "New records created successfully";
		} else {
		    echo "Error: <br>" . $conn->error;
		}

	}

Just getting
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘’ at line 1

Sorry im a newbie with php

Can you show me database tables, and what is line 1 in your code block ?

Hi,
I found an error relating to a missing parenthesis in the first insert query where client exists.
This goes onto enter in data into ‘messagetb’ hoever when a new client is added it now produces an error:

Undefined variable: query

Sorted it my code that works before using PDO is below. Many thanks

<?php

error_reporting(E_ALL);

$servername = "localhost";
$username = "*****";
$password = "*****";
$dbname = "adrian";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
else{ 
	echo "Connected successfully";
}


// escape this post values !
$f = $conn->real_escape_string($_POST['fname']);
$l = $conn->real_escape_string($_POST['lname']);
$e = $conn->real_escape_string($_POST['email']);
$t = $conn->real_escape_string($_POST['telephone']);
$m = $conn->real_escape_string($_POST['message']);

$sql = "SELECT clientid, firstName, lastName, email from clienttb where firstName = '".$f."' AND lastName = '".$l."' AND email = '".$e."'";
$result = $conn->query($sql);
$data = $result->fetch_array(MYSQLI_BOTH); // will get you array for clientid


// if returned rows count more that 0, insert data
// put both querys here
	if ($result->num_rows > 0) {
	$query = $conn->query("INSERT INTO messagetb(message, clientid, messageDate) VALUES ('".$m."', '".$data['clientid']."', CURRENT_TIMESTAMP())");
	}
	else{
		$query = $conn->query("INSERT INTO messagetb(message, clientid, messageDate) VALUES ('".$m."', '".$data['clientid']."', CURRENT_TIMESTAMP())");

		$query = $conn->query("INSERT INTO clienttb(firstName, lastName, email, telephone, dateCreated) VALUES ('".$f."', '".$l."', '".$e."', '".$t."', CURRENT_TIMESTAMP())");
	}
		
	if ($query) {
	  	echo "New records created successfully";
	} else {
		echo "Error: <br>" . $conn->error;
		}
$conn->close();

?>

Uh, excuse me, but your code is not using PDO. And you are still putting variables in your query and your still outputting internal system errors to hackers and YOU do not need to insert the current timestamp.The database can do it automatically AND you have a redundant query that runs in the IF and the ELSE.

Hi, completely get the security aspec5. But wanted to get the code working first.
I have added the pdo but was having issues with $data[‘clientid’]

No, you have not added one bit of PDO whatsoever.

Got it. Please tell me how i can improve it.

<?php error_reporting(E_ALL); $servername = "localhost"; $username = "root"; $password = "admin"; $dbname = "adrian"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } else{ echo "Connected successfully"; } // escape this post values ! $f = $_POST['fname']; $l = $_POST['lname']; $e = $_POST['email']; $t = $_POST['telephone']; $m = $_POST['message']; $sql = "SELECT clientid, firstName, lastName, email from clienttb where firstName = '".$f."' AND lastName = '".$l."' AND email = '".$e."'"; $result = $conn->query($sql); $data = $result->fetch_array(MYSQLI_BOTH); // will get you array for clientid $sqlm = "INSERT INTO messagetb(message, clientid, messageDate) VALUES (? , ? , CURRENT_TIMESTAMP())"; $stmtm = $conn->prepare($sqlm); $stmtm->bind_param("si", $m, $data['clientid']); $sqlc = "INSERT INTO clienttb(firstName, lastName, email, telephone, dateCreated) VALUES (? , ?, ?, ?, CURRENT_TIMESTAMP())"; $stmtc = $conn->prepare($sqlc); $stmtc->bind_param("ssss",$f,$l,$e,$t); // if returned rows count more that 0, insert data // put both querys here if ($result->num_rows > 0) { $query = $stmtm->execute(); } else{ $query = $stmtc->execute(); $query = $stmtm->execute(); } if ($query) { echo "New records created successfully"; } else { echo "Error:
" . $conn->error; } $conn->close(); ?>

Still not PDO, but at least you’re trying to use prepared statements.

Also, you should be using prepared statements for your SELECT query.