Failed prepare in a prepared statement [duplicate] - php

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 7 years ago.
I am trying to GET a user ID from the previous page and output the information onto another page and in my prepared statement I am getting an error in the prepare part of the statement. What I don't get is I have this almost exact same code on another site I have and it works perfeclty. I am stumped I have looked over all of the names in my db and everything is correct.
This is the error I am getting:
prepare() failed: 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 'group FROM users WHERE id = ?' at line 1
The line that is being mentioned is this one...
$stmt = $con->prepare("SELECT fullname, email, username, group FROM users WHERE id = ?");
This is the full prepared statement.
<?php
$con = mysqli_connect("localhost","root","","db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $con->prepare("SELECT fullname, email, username, group FROM users WHERE id = ?");
if ( false===$stmt ) {
// Check Errors for prepare
die('prepare() failed: ' . htmlspecialchars($con->error));
}
$stmt->bind_param("i", $_GET['id']);
if ( false===$stmt ) {
// Check errors for binding parameters
die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->execute();
if ( false===$stmt ) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
//Check errors for execute
//if(!$stmt->execute()){trigger_error("there was an error....".$con->error, E_USER_WARNING);}
$stmt->bind_result($fullname, $email, $username, $group);
$stmt->store_result();
if ($stmt->fetch()) { ?>
Am I missing something very obvious or what could be causing this?

Put a backtick (grave accents `) or quotation marks (or apostrophes) around group so it looks like this `group`. It's a MySQL keyword so that's what is messing up your query. It's good practice to always do that with your column names.

Related

Subject Update Failed Mysql

Subject Update Failed!!You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1
I am stuck here can anyone help me what I am missing in this code.The error is in Update Query.
Everything is ok, and I don't get any syntax error when I write the code (I am using a Dreamviwer code editor software. However, when I run it, I get this error:
//Process the form
$id= $current_subject["Id"];
$name=mysql_prep($_POST["Name"]);
$position=(int)$_POST["Position"];
$visible=(int)$_POST["Visible"];
$query="UPDATE subjects SET Name='{$name}',Position=$position,Visible=$visible WHERE Id={$id}";
$result= mysqli_query($conn, $query);
if($result && mysqli_affected_rows($conn)==1){
//success
$_SESSION["message"]="Subject updated.";
redirect_to("manage_content.php");
}else{
//Failure
$message="Subject Update Failed" . $conn->error;
}
Most likely you mistyped the parameter name. Đ•cho your parameters first.
And use prepared statements to prevent SQL injections:
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$query="UPDATE subjects SET Name = ? ,Position = ?,Visible = ? WHERE Id = ?";
$stmt = $dbh->prepare($query);
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $position);
$stmt->bindParam(3, $visible);
$stmt->bindParam(4, $id);
$stmt->execute();
$stmt->fetchAll();
Further reading: PDO.

Attempt to get a php prepare to work with two different tables

I am attempting to do my first query where I send to two different db tables. I am trying to update the 'group' in the users and user_request table. I am getting an id from an AJAX call, I am using that id to find the record I am trying to update.
In the users table the id will need to find the id field.
In the user_requests table the id will need to associate with the user_id.
This is the line I am trying to change to make this send to two different db tables..
$stmt = $con->prepare("UPDATE users,user_reuqests SET `group`=? WHERE id, user_id=?");
I'm getting an error responce saying the error is by the user_id part.
$approved_id = $_POST['id'];
$change_group = $_POST['update_group'];
$con = mysqli_connect("localhost","root","","db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $con->prepare("UPDATE users,user_reuqests SET `group`=? WHERE id, user_id=?");
if ( !$stmt || $con->error ) {
// Check Errors for prepare
die('User Group update prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt->bind_param('ii', $change_group, $approved_id)) {
// Check errors for binding parameters
die('User Group update bind_param() failed: ' . htmlspecialchars($stmt->error));
}
if(!$stmt->execute()) {
die('User Group update execute() failed: ' . htmlspecialchars($stmt->error));
}
What am I doing wrong to not get this to work and conjoin?
UPDATE: After I changed the prepare part of this, I'm now getting errors in my bind_param part of my prepared statement. How can I change this?
$stmt = $con->prepare("UPDATE users,user_requests SET users.group=?, user_requests.group=? WHERE users.id=? AND user_requests.user_id=?");
First, The WHERE clause in your query doesn't specify an id for the first constraint.
Second, group is ambiguous and will cause errors when you try to update it.
Your query should read:UPDATE users,user_reuqests SET users.group=?, user_request.group=? WHERE users.id=? AND user_request.user_id=?
Now, since we've updated the query with more place holders, we need to bind these additional placeholders to PHP variables. The new query uses both $change_group and $approved_id twice - so we need to bind each of them twice.
if(!$stmt->bind_param('iiii', $change_group, $change_group, $approved_id, $approved_id)) {
// Check errors for binding parameters
die('User Group update bind_param() failed: ' . htmlspecialchars($stmt->error));
}
When all is said and done, the final code should look like this:
$approved_id = $_POST['id'];
$change_group = $_POST['update_group'];
$con = mysqli_connect("localhost","root","","db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $con->prepare("UPDATE users,user_reuqests SET users.group=?, user_request.group=? WHERE users.id=? AND user_request.user_id=?");
if ( !$stmt || $con->error ) {
// Check Errors for prepare
die('User Group update prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt->bind_param('iiii', $change_group, $change_group, $approved_id, $approved_id)) {
// Check errors for binding parameters
die('User Group update bind_param() failed: ' . htmlspecialchars($stmt->error));
}
if(!$stmt->execute()) {
die('User Group update execute() failed: ' . htmlspecialchars($stmt->error));
}
More info on binding parameters to a mysqli_stmt here: http://php.net/manual/en/mysqli-stmt.bind-param.php
There's a problem with your syntax:
WHERE id, user_id=?
It should be something like this:
WHERE id = ? AND user_id = ?

PHP Warning: mysqli_stmt_bind_result() [duplicate]

This question already has an answer here:
INSERT - Number of bind variables doesn't match number of fields in prepared statement
(1 answer)
Closed 1 year ago.
I am new to programing not only with PHP but at all. Currently I am doing a siple project of mine to improve myself. I did it onec but now I want to make all my queries to work with prepared statements which is something new for me...
$create_stmt = mysqli_prepare($connection, "INSERT INTO `users`(`user_name`, `password`) VALUES (?,?)");
if(!$create_stmt){
echo 'error';
exit;
}
mysqli_stmt_bind_param($create_stmt, 'ss',$username,$password);
mysqli_stmt_execute($create_stmt);
mysqli_stmt_bind_result($create_stmt, $new_uname, $new_unamepass);
mysqli_stmt_fetch($create_stmt);
So here is the deal. I am having this kind of an error:
Warning: mysqli_stmt_bind_result(): Number of bind variables doesn't match number of fields in prepared statement.
Since I want to add 2 values to my 'users' table I am declaring 2 new variables $new_uname, $new_unamepass, but somehow this is not correct...
Also mysqli_stmt_fetch($create_stmt); is not TRUE but it should be if everything is OK (obviously its not ok..) So please if anyone can help me or give me some advice, it will be great!
TRY This:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO `users`(`user_name`, `password`) VALUES (?,?)");
$stmt->bind_param('ss', $user, $pass);
$user='username';
$pass = 'Password1234';
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();

php prepared statement

It does not print the result. Dont know why. Everything is neatly commented
I get no error displays, no syntax blasphemes, it just does not print any result. However, I do know that the values are passed by the form to this processing php page, so the error is not in there. In the DB I have encrypted all fields except 'company'- Thus, I want to see if this will work by trying to fetch the results back.
// 1. Creating a new server connection
$db = new mysqli('localhost', 'root', '', 'developers');
if ($db->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
// 2, Creating statement object
$stmt = $db->stmt_init();
// 3, Creating a prepared statement
if($stmt->prepare("SELECT company FROM accesoweb WHERE username = AES_DECRYPT(?, 'salt')")) {
//4. Binding the variable to replace the ?
$stmt->bind_param('s', $username);
printf("Error: %d.\n", $stmt->errno);
// 5. Executing query
$stmt->execute();
// 6. Binding the result columns to variables
$stmt->bind_result($company);
// 7. Fetching the result of the query
while($stmt->fetch()) {
echo $company;
}
// 8. Closing the statement object
$stmt->close();
// 9. Closing the connection
$mysqli->close();
}
The inserting code that I just included in the MySQL was:
INSERT INTO accesoweb (company, username,email,password)
VALUES
('hola',
AES_ENCRYPT('maria','salt'),
AES_ENCRYPT('sumail','salt'),
AES_ENCRYPT('password',' salt')
);
So, that row above(actually, the "company" is what I am trying to recover through the PHP code
SELECT company FROM accesoweb WHERE username = AES_DECRYPT(?, 'salt')
Should be
SELECT company FROM accesoweb WHERE username = AES_ENCRYPT(?, 'salt')
OR
SELECT company FROM accesoweb WHERE AES_DECRYPT(username, 'salt') = ?

PHP MySQL prepared-statement prepare() fails

the following returns false and i don't know how to find out what exactly is wrong.
$stmt = $dbo->stmt_init();
if($stmt->prepare("INSERT INTO transactions ('id', 'time') VALUES ('',?)")) // returns false
{
}
i have another statement which does an select open at that time. is it a problem to have more than one statements?
Have you verified that you are connecting to the database successfully?
/* check connection */
if ( mysqli_connect_errno() ) {
printf("Connect failed: %s\n", mysqli_connect_error());
}
As far as figuring out what's wrong with your prepared statement, you should be able to display $stmt->error, which will return a string description of the latest statement error, and $dbo->error, which will return the latest mysqli error.
printf("Error: %s.\n", $stmt->error);
You don't want single quotes around your table names. It should look like this:
$stmt = $dbo->stmt_init();
if($stmt->prepare("INSERT INTO transactions (id, time) VALUES ('', ?)")) {
}
just check whether those columns are properly entered... as i was getting same error coz i mentioned non existing column name in the query..

Categories