Why does this prepared statement throw an error? - php

Having learnt the basics of PHP and MySQL, I am now learning how to protect against SQL injection attacks by using prepared statements. I have the following code:
for ($i = 0; $i < $delegateno ;$i++){
$q = "INSERT INTO delegates (delegate_id,booker_name, booker_email, booker_tel, booker_company, delegate_name, delegate_email, delegate_tel) VALUES (NULL, ?, ?, ?, ?, ?, ?, ? )";//Insert delegate information into delegate tables
$stmt = mysqli_query($dbc, $q);
mysqli_stmt_bind_param($stmt,'sssssss', $fullname, $email, $tel, $company,$delegatename[$i],$delegateemail[$i],$delegatetel[$i]);
mysqli_stmt_execute($stmt);
}
However, this throws:
Notice: Query: INSERT INTO delegates (delegate_id,booker_name, booker_email, booker_tel, booker_company, delegate_name, delegate_email, delegate_tel) VALUES (NULL, ?, ?, ?, ?, ?, ?, ? )
MySQL Error: 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 '?, ?, ?, ?, ?, ?, ? )'
What am I doing wrong?

Because you're executing the raw query containing the placeholders. You need to prepare() the query first.
This is how it goes (usually): prepare -> bind_param -> execute -> fetch.
Change:
$stmt = mysqli_query($dbc, $q);
to:
$stmt = mysqli_prepare($dbc, $q);

Related

SQL Prepared statement not inserting my values

I have this prepared statement and it isn't inserting into the table at all. The connection to my database is working. I am still new to this so I am unsure on what is wrong. The spelling of my table is correct also. My network tab on inspect element doesn't show any errors as if it did insert the data but the table doesn't update with said data.
$stmt = $conn->prepare("INSERT INTO usersreports (DateOfReport,Username,ReportedPostId,ReportedUser,ReportedUserId,ReportedReason,ReportedTopic,Resolved,Response,ActionTaken) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssssssss", $DateOfReport,$YourUsername,$UsersPostId,$ReportedUsername,$ReportedUserId,$ReportReason,$ReportTopic,$Resolved,$Response,$ActionTaken);
if ( $stmt === false ) {
echo $conn->error;
exit;
}
$stmt->execute();
$stmt->close();
$conn->close();

Getting multiple errors when trying to use Prepared statements in PHP/MySQL

I am trying to use prepared statements as a best practice but I keep getting these errors.
1) 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 ') VALUES (?, ?, ?, ?, ?,?, ?, ?, ?, ?)'
2) Undefined index: finalExamGrade in C:\wamp64 (this goes for all the superglobal variables)
3) Fatal error: Call to a member function bind_param() on boolean in C:\wamp64\
Any fixes? Ideas?
PHP/MySQL
require_once("DBCONNECT.php");
$id = $_REQUEST['studentID'];
$last = $_REQUEST['lastName'];
$first = $_REQUEST['firstName'];
$grade1 = $_REQUEST['test1Grade'];
$grade2 = $_REQUEST['test2Grade'];
$grade3 = $_REQUEST['test3Grade'];
$grade4 = $_REQUEST['test4Grade'];
$final = $_REQUEST['finalExamGrade'];
$stmt = $connect->prepare("SELECT * FROM students) VALUES (?, ?, ?, ?, ?,?, ?)");
$stmt->bind_param("issiiiii", $id, $last, $first, $grade1, $grade2, $grade3, $grade4, $final);
$stmt->execute();
var_dump($id, $last, $first, $grade1, $grade2, $grade3, $grade4, $final);
$stmt->close();
$connect->close();
$stmt = $connect->prepare("SELECT * FROM students) VALUES (?, ?, ?, ?, ?,?, ?)");
The above code is the root of all of your problem.
You use SELECT to insert data. It should be INSERT.
There is an extra bracket after students table.
The total parameters doesn't match with the bind_param one. There are 7 ?
in your code when you want to store 8 variables.
Change into this code
$stmt = $connect->prepare("INSERT INTO students(col1, col2, col3, col4, col5, col6, col7, col8) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("issiiiii", $id, $last, $first, $grade1, $grade2, $grade3, $grade4, $final);
I don't explain this code any further because it has been discussed on comments.

Uncaught exception 'mysqli_sql_exception' with message 'No data supplied for parameters in prepared statement'

I am trying to write a query using a prepared statement.
mysqli_report(MYSQLI_REPORT_ALL);
$query = $conn->prepare("INSERT INTO notification(MessageId,TopicArn,Subject,Message,Timestamp,SignatureVersion,Signature,SigningCertURL,UnsubscribeURL,topicid)
VALUES (?, ?, ?, ?, ?,?, ?, ?, ?, ?)");
This throws the following exception
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'No data supplied for parameters in prepared statement'
Where as the following query works
$query = $conn->prepare("INSERT INTO notification(MessageId,TopicArn,Subject,Message,Timestamp,SignatureVersion,Signature,SigningCertURL,UnsubscribeURL,topicid)
VALUES (".$message['MessageId'].", '".$message['TopicArn']."', '".$message['Subject']."', '".$message['Message']."', '".$message['Timestamp']."',".$message['SignatureVersion'].", '".$message['Signature']."', '".$message['SigningCertURL']."', '".$message['UnsubscribeURL']."', ".$topic.")");
I want to use prepared statement with bind_param() function. What is wrong with first query? Please help.
As I suggested - you need to bind parameters to values before you can execute the sql ~ like this perhaps:
mysqli_report(MYSQLI_REPORT_ALL);
$sql='insert into notification
(messageid,topicarn,subject,message,timestamp,signatureversion,signature,signingcerturl,unsubscribeurl,topicid)
values
(?, ?, ?, ?, ?,?, ?, ?, ?, ?)';
$stmt = $conn->prepare( sql );
if( $stmt ){
/* assumed mainly strings other than those with `id` in column name */
$stmt->bind_param('issssssssi',
$message['MessageId'],
$message['TopicArn'],
$message['Subject'],
$message['Message'],
$message['Timestamp'],
$message['SignatureVersion'],
$message['Signature'],
$message['SigningCertURL'],
$message['UnsubscribeURL'],
$topic
);
$result=$stmt->execute();
/* Other code */
} else {
/* investigate why "prepare" method failed */
echo "Error:";
}
You can bind the data like below.
$stmt = $conn->prepare( $sql );
if( $stmt ){
$stmt->bind_param('issssssssi', $message['MessageId'], $message['TopicArn'],
$message['Subject'], $message['Message'], $message['Timestamp'],
$message['SignatureVersion'], $message['Signature'], $message['SigningCertURL'],
$message['UnsubscribeURL'] ,$message['UnsubscribeURL'] );
}
You just forgot to add $ infront of the sql please add that and try again.

php mysql bind param parameters

I'm trying out using prepared statements for the first time and running into the following issue with the below code
Error :
Warning: mysqli_stmt_bind_param() expects parameter 1 to be
mysqli_stmt, boolean given
Code :
$stmt = mysqli_prepare($db, "INSERT INTO fragrances(name, description, essentialoils, topnotes, middlenotes, basenotes, reference, year, type, price, fragrancehouse, triangle, extractname, extractreference, extractprice, extractfragrancehouse, disccolour, collarcolour, actuatorcolour)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssssssssssssssssss', $name, $description, $essentialoils, $topnotes, $middlenotes, $basenotes, $reference, $year, $type, $price, $fragrancehouse, $triangle, $extractname, $extractreference, $extractprice, $extractfragrancehouse, $disccolour, $collarcolour, $actuatorcolour);
mysqli_stmt_execute($stmt);
I've looked at many different questions on here and none of their solutions seem to apply for my problem, does anyone know what the issue is?
$stmt becomes a boolean only when mysqli_prepare returns false.
When this happens it means it failed to prepare the query therefore you need to check for errors:
$stmt = mysqli_stmt_init($db);
if (mysqli_stmt_prepare($stmt, 'INSERT INTO fragrances VALUES...')) {
//it's all good bind and execute here
}else{
//we have a problem
printf("Errormessage: %s\n", mysqli_error($db));
}
The error message means your mysqli_prepare returned a boolean (and for your case, it returned false).
You need to replace all your field name by the character ? to make your prepared statement. This is how it works.
See example in the official documentation
EDIT See also mysqli_error , which will detail your error. In fact, you should always check a variable before using it:
$stmt = mysqli_prepare($db, "....");
if(!$stmt)
echo mysqli_error($db); // display error only for debug. Avoid this in production
It means your SQL was invalid because the prepare is returning false;
Your SQL should be;
$stmt = mysqli_prepare($db, "INSERT INTO fragrances VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )");
Each ? is to show where each parameter needs to be bound respectively.
Your INSERT statement is invalid: VALUES clause must be with ? in parantheses (and after field names in parentheses). Also good practice is to check $stmt after assigning:
$stmt = mysqli_prepare($db,
"INSERT INTO fragrances (name, description, essentialoils, topnotes, middlenotes, basenotes, reference, year, type, price, fragrancehouse, triangle, extractname, extractreference, extractprice, extractfragrancehouse, disccolour, collarcolour, actuatorcolour)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
if ($stmt) {
mysqli_stmt_bind_param($stmt, 'sssssssssssssssssss', $name, $description, $essentialoils, $topnotes, $middlenotes, $basenotes, $reference, $year, $type, $price, $fragrancehouse, $triangle, $extractname, $extractreference, $extractprice, $extractfragrancehouse, $disccolour, $collarcolour, $actuatorcolour);
mysqli_stmt_execute($stmt);
// ...
} else
printf("Error: %s\n", mysqli_error($db));

SQL syntax error: can't be found

I'm new to SQL so i'm probably missing something. Apparently I have a syntax error on this line:
$mysql = 'INSERT INTO Orders (Name, Recipient, Destination, Room, Message, Anonymous, OffCampus, OffCampusAddress) VALUES (?, ?, ?, ?, ?, ?, ?, ?)';
Could anyone help me identify what I am doing wrong? Thanks in advance
Error: 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
Here is my parameter binding:
mysqli_stmt_bind_param($stmt, 'ssssssss', $name, $recipient, $destination, $room, $message, $anonymous, $offcampus, $offcampusaddress);
It should look like this:
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
$mysql = "INSERT INTO Orders\n" +
"(Name, Recipient, Destination, Room, Message, Anonymous, OffCampus, OffCampusAddress)\n" +
"VALUES\n" +
"(?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($link, $mysql);
mysqli_stmt_bind_param($stmt, 'ssssssss', $name, $recipient, $destination, $room, $message, $anonymous, $offcampus, $offcampusaddress);
mysqli_stmt_execute($stmt);
Try to add ` for column names and ' for values. it may work

Categories