简体   繁体   中英

SQL syntax error when value is entered for parameter

I have this line of code to enter data into a database using binding:

$mysql = "INSERT INTO Orders (`Name`, `Recipient`, `Destination`, `Room`, `Message`, `Anonymous`, `OffCampus`, `OffCampusAddress`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

$stmt = mysqli_prepare($con,$mysql);

Oddly enough, this error only occurs when a value for the column Recipient is entered in the html form. When nothing is entered in the field it works. The error is:

mysqli 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 '0' at line 1

Could anyone tell me why entering a value for the parameter would cause a MySQL syntax error? Thanks in advance, and sorry if it's obvious, I'm new to web development.

Here is my binding:

  mysqli_stmt_bind_param($stmt, 'ssssssss', $name, $recipient, $destination, $room, $message, $anonymous, $offcampus, $offcampusaddress);    

I think you should do like this as in my below code.

$mysqli = new mysqli('localhost', 'root', '', 'DBNAME');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = $mysqli->prepare("INSERT INTO Orders (`Name`, `Recipient`, `Destination`, `Room`, `Message`, `Anonymous`, `OffCampus`, `OffCampusAddress`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");

$stmt->bind_param("sssdssss", $Name, $Recipient, $Destination, $Room, $Message, $Anonymous, $OffCampus, $OffCampusAddress);

$Name= 'DEU';
$Recipient= 'Bavarian';
$Destination= "XYZ";
$Room= 15;
$Message= 'May I help you';
$Anonymous= 'i do not know';
$OffCampus= "YY";
$OffCampusAddress= "Known Street";

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

In bind parameters (sssdssss) means the the type of parameter as you given as input. s for string value, and d for decimal value. I keep sssdssss because, d is decimal ie no: of rooms and this type comes first, if in your db, you keep it varchar so you may convert d to s. you have write wrong syntax in you question ie

mysqli_stmt_bind_param($stmt, 'ssssssss', $name, $recipient, $destination, $room, $message, $anonymous, $offcampus, $offcampusaddress); 

Hope it will help you.

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM