Why is this mysql statement not working?

I have two back-to-back mysql statements in my php code. The first works fine but the second one fails for some unknown reason.

The first statement, which works, is:


	$sql="SELECT * FROM qs WHERE ID='$quoteID'";
	$result = mysqli_query($link, $sql);

The second statement, which does NOT work, is:

 $sql="INSERT INTO qs (sourceName) VALUES ('$sourceName')";
	 $result = mysqli_query($link, $sql);

Note: sourceName in the above code is simply an article title, like “The Call of the Wild.” I have verified that the variable $sourceName exists and yet the insert operation fails to work. After I run the insert operation attempt, I actually can request and receive an ID that has supposedly been created – but when I look in the qs table, no new record has actually been created.

I am on a recent version of PHP at my new web host, php version 8-something.

Here is the entire script. The point of the script is to create a new record in the table qs. The script that follows will run. However, it does not insert a record into the qs table.

<?php
include 'allow_access.php';

if ($accessYN=="Y") {
	
	$quoteID=$_REQUEST['quoteID'];

include 'connection.php';


	$sql="SELECT * FROM qs WHERE ID='$quoteID'";
	$result = mysqli_query($link, $sql);
	while($row = mysqli_fetch_assoc($result)) {
    $sourceName=$row['sourceName']; 
	}
 
echo "for quoteID=".$quoteID.", sourceName=".$sourceName."<BR><BR>";
 
 
$sourceName = mysqli_real_escape_string($link, $sourceName);



 
 $sql="INSERT INTO qs (sourceName) VALUES ('$sourceName')";
 
	 $result = mysqli_query($link, $sql);
	 
	 
	 

 
?>
<a href="quotes_get.php">Back</a>
<?php 
}

 ?>

Do you have php’s error_reporting set to E_ALL (it should always be this value) and display_errors set to ON, preferably in the php.ini on your system, so that php will help you by reporting and displaying all the errors it detects?

Is there any code after the posted code that could be deleting or updating the just INSERTed record?

I hope you are planning to switching to use prepared queries, instead of putting dynamic values directly into sql query statements, where any sql special characters in a value can break the sql query syntax. This is where the much simpler and better designed PDO extension comes in.

Thanks. I will try to rewrite the code using PDO.

I am not sure how to change error reporting. I am on a shared hosting platform so I am not sure that I am even allowed to make such changes. Any suggestions on how to do so would be appreciated. I am currently “flying blind” because I have no error reporting whatsoever from my mysql statements. I received error messages in php 5.6 but since I moved to php 8-something last week, I never get error messages.

You should be able to set those two settings in your code, unless the web host has disabled the ability to do so.

You should be learning, developing, and debugging code/queries on a localhost development system. Constantly uploading code to web hosting to see the result of each change is a huge waste of time and if an error occurs during the upload, you can end up running the previous code, not the latest.

Here is typical PDO connection code -

$DB_HOST = ''; // database host name or ip address
$DB_USER = ''; // database username
$DB_PASS = ''; // database password
$DB_NAME = ''; // database name
$DB_ENCODING = 'utf8mb4'; // db character encoding. set to match your database table's character set. note: utf8 is an alias of utf8mb3/utf8mb4

$options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // set the error mode to exceptions. this is the default now in php8+
			PDO::ATTR_EMULATE_PREPARES => false, // run real prepared queries
			PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC // set default fetch mode to assoc
			];

$pdo = new pdo("mysql:host=$DB_HOST;dbname=$DB_NAME;charset=$DB_ENCODING",$DB_USER,$DB_PASS,$options);

Converting an old query that has variables being put directly into it into a prepared query is fairly straightforward -

  1. Remove, and keep for later, any php variables that are inside the sql query statement. note: any wild-card characters in a LIKE comparison are supplied as part of the data value not as part of the sql query statement.
  2. Remove any quotes or {} that were around the php variable and any concatenation dots/extra quotes that were used to get the php variable into the sql query statement.
  3. Put a simple ? prepared query place-holder into the sql query statement for each value.
  4. Call the PDO prepare() method for the sql query statement. This returns a PDOStatement object.
  5. Call the PDOStatement execute([…]) method with an array of the variables you removed in step #1.

For a query that returns a result set, fetch the data from the query. See the PDOStatement fetch() method when fetching a single row of data, the PDOStatement fetchAll() method when fetching all the rows of data at once, and occasionally the PDOStatement fetchColum() method when fetching a single column from a single row of data. Forget about any num rows function/method/property. Just fetch then test if/how many rows of data there are.

For a query that doesn’t return a result set, you can use the PDO lastInsertId() method and the PDOStatement rowCount() method with an insert/update/delete query to get the last insert id and the number of affected rows.

Php8+ uses exceptions for database statement errors by default. For an insert/update query that could result in duplicate data (the appropriate column(s) need to be defined as unique indexes in the database table), you will need to catch and handle database exceptions from the query, test if the error number is for a duplicate index error, and setup a message for the user letting them know what was wrong with the data that they submitted. For all other query errors, simply rethrow the exception and let php handle it, and for all other type of queries, simply do nothing in your code, and let php catch and handle any database exception, where php will use its error related settings to control what happens with the actual error information via an uncaught exception error (database errors will ‘automatically’ get displayed/logged the same as php errors.)

For the two queries you have shown, they would look like -

$sql="SELECT * FROM qs WHERE ID=?";
$stmt = $pdo-prepare($sql);
$stmt->execute([ $quoteID ]);

$sql="INSERT INTO qs (sourceName) VALUES (?)";
$stmt->prepare($sql);
$stmt->execute([ $sourceName ]);

I am trying to use the Insert statement that you provided.

The first line works:

$sql="INSERT INTO qs (sourceName) VALUES (?)";

`
However, when I include the second line…

$stmt->prepare($sql);

…the code stops working.

Unfortunately, there’s a typo in the line. It should have been the same as the SELECT query -

$stmt = $pdo-prepare($sql);

You would have been getting a runtime error. The sooner you get the error_reporting/display_errors setting set, the easier it will be to do this.

I tried that too but that didn’t work either. Looks like I’m missing something basic here. I guess I have to define $pdo. I’ve tried doing that, based on examples I’ve seen online, but that does not seem to help either.

I’ll continue to research the subject, so that I can at least figure out the right questions to ask.

I’m used to forgetting about the connection routines once I’m connected to a dbase – but it looks like with modern PHP and PDO, one has to do more than just connect; one has to connect in such a way as to create the right string variables for subsequent use in queries. Maybe that’s what I’m having trouble doing.

The typical PDO connection code I posted creates a connection and assigns it to the variable $pdo.

The old mysql_ extension was able to ‘automatically’ use the last created connection, without you needing to specify it in each statement that used a connection. This was a bad design decision that is thankfully now removed.

I’ve tried the connection data that you used and so far no luck. I’ll keep trying to figure out what I’m doing wrong.

Meanwhile when I use other methods to execute mysql, I sometimes get a “success” message, and yet the table is never actually updated.

The following code, for instance, returns “new record created” – and yet no record was actually created for the table.

$sql2 = "INSERT INTO qs (sourceName) VALUES ('$sourceName')";
if (mysqli_query($link, $sql2)) {
    echo "New record created successfully*******************************************************";
} else {
    echo "Error: " . $sql2 . "<br>" . mysqli_error($link);
}

I think I might have to hire someone to work with me on Google Meet for a half-hour or so to look at my code and see what I’m missing.

Thanks for the help. I think I have an error in my code elsewhere, something that is deleting records after they’re created. I think I’m on the verge of straightening this out, and will report back, hopefully later today.

Thanks again. The statements are now working!

Sponsor our Newsletter | Privacy Policy | Terms of Service