I need help with this query. If I use this query in MySQL that works fine but is not being executed when used in PHP.
$sql = "INSERT INTO dtable (name, mobile, email) VALUES ('".$MP_Name."', '".$MP_Mobil."','".$MP_Email."');";
$conn->query($sql);
Use prepared statements to avoid sql injection.
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("INSERT INTO dtable (name, mobile, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $MP_Name, $MP_Mobil, $MP_Email);
$stmt->execute();
$stmt->close();
Try to echo the query string before executing it and copy/paste that echoed query in phpmyadmin and check for errors in the query
$result= $sql->query(sprintf("INSERT INTO dtable(name,mobile,email) VALUES ('%s','%s','%s')", ($_POST['MP_Name']), ($_POST['MP_Mobil']), ($_POST['MP_Email'])));
echo $sql;
With more study, I came to know that I was actually getting an error; commands out of sync; you can't run this command now.
I added $conn->next_result() before running the query which solved the issue.
Related
I am pretty new to SQL Transactions and tried to execute following statement which did unfortunately not work...
$stmt = $mysqli->prepare("
BEGIN;
INSERT INTO groups (group_name, group_desc, user_id_fk) VALUES ("'.$groupName.'","'.$groupDesc.'","'.$user_id.'");
INSERT INTO group_users (group_id_fk, user_id_fk) VALUES (LAST_INSERT_ID(), "'.$username.'");
COMMIT;
") or trigger_error($mysqli->error, E_USER_ERROR);
$stmt->execute();
$stmt->close();
Is this even possible what I am trying here or is it completely wrong?
I appreciate every response, thank you!
You are using prepare() wrong way. There is absolutely no point in using prepare() if you are adding variables directly in the query.
This is how your queries have to be executed:
$mysqli->query("BEGIN");
$sql = "INSERT INTO groups (group_name, group_desc, user_id_fk) VALUES (?,?,?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("ssi",$groupName,$groupDesc,$user_id);
$stmt->execute();
$sql = "INSERT INTO group_users (group_id_fk, user_id_fk) VALUES (LAST_INSERT_ID(), ?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s",$username);
$stmt->execute();
$mysqli->query("COMMIT");
There are so many questions on SO for failed prepared statements, but I cannot find one which solves my exact problem (or explains it, atleast).
I'm trying to give my users a login-token which is valid for 5 minutes.
When I execute the query through PHPMyAdmin it works just fine:
WORKING QUERY
INSERT INTO LOGGEDIN (userID, loggedInToken, loggedInRefresh) VALUES
(1, "HJKFSJKFDSKLJFLS", ADDTIME(CURTIME(), '00:05:00'));
However, when trying to execute the query through PHP using a prepared statement it fails.
$stmt = $this->conn->prepare("INSERT INTO LOGGEDIN VALUES (userID, loggedInToken, loggedInRefresh) VALUES (?, ?, ADDTIME(CURTIME(), '00:05:00'))");
$stmt->bind_param("is", $userID, $token);
I get the 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 'VALUES (?, ?, ADDTIME(CURTIME(), '00:05:00'))' at line 1
It is the exact same query so I think it's due to how the prepare handles the query.
I've also tried entering the '00:05:00' as a variable because I thought the ' was causing the error but it fails as well.
$five_minutes = '00:05:00';
$stmt->bind_param("iss", $userID, $token, $five_minutes);
When I remove the prepare and use the following query:
$query = "INSERT INTO LOGGEDIN VALUES (userID, loggedInToken, loggedInRefresh) VALUES (" . $userID . ", '" . $token . "', ADDTIME(CURTIME(), '00:05:00'))";
if ($result = $mysqli->query($query)) {
...
It works fine but I would like to keep my code consistent and use a prepared statement everywhere I can.
How can I let this query execute properly using a prepared statement? If all else fails I think I could create the timestamp in PHP and pass it through to the database thus bypassing the whole ADDTIME calculation, but I would like to know what is causing the problem in the first place.
Problems need to be understood, not dodged.
You have a superfluous VALUES on your query:
$stmt = $this->conn->prepare("INSERT INTO LOGGEDIN VALUES (userID, loggedInToken, loggedInRefresh) VALUES (?, ?, ADDTIME(CURTIME(), '00:05:00'))");
^^
Remove that:
$stmt = $this->conn->prepare("INSERT INTO LOGGEDIN (userID, loggedInToken, loggedInRefresh) VALUES (?, ?, ADDTIME(CURTIME(), '00:05:00'))");
I am trying to INSERT data into a table from a form using MySQLi. I have my database connection on a separate include file before including the form that will INSERT the data. my connection looks like so:
#$DB = new mysqli($mysqlHost,$mysqlUser,$mysqlPass,$mysqlDB);
if($DB ->connect_errno >0){
echo 'Could not connect to the server at this time. Please try again later.';
exit;
}
Now i want to execute a query that will store the users information into a table called users. When i run the query in phpMyAdmin it works fine, so i'm guessing its something to do with the syntax or my logic. Here is my insert code:
if($stmt = $DB->prepare("INSERT INTO `users`(`email`, `password`) VALUES ('value1', 'value2')")){
$stmt->execute();
$stmt->close();
}
echo 'Data INSERTED INTO table.';
Here is the error i am receiving:
Warning: mysqli::prepare(): Couldn't fetch mysqli in C:\xampp\htdocs\Phpclass\Website\includes\register.php
If you need additional information please let me know, i have been working on this for sometime now and it is very frustrated.
Change
$stmt = $DB->prepare("INSERT INTO `users`(`email`, `password`) VALUES ('value1', 'value2')");
To
if ($stmt = $DB->prepare("INSERT INTO `users`(`email`, `password`) VALUES (?, ?)"))
{
$stmt->bind_param("ss", 'value1', 'value2');
$stmt->execute();
$stmt->close();
}
You have you bind the parameters if you use prepared statements. Prepared statements can be used to re-use an SQL query repetitively, to import large chunks of data.
If you're not requiring to import large chunks of data I would recommend using the following instead:
$q = $DB->query("INSERT INTO `users`(`email`, `password`) VALUES ('value1', 'value2')");
You need to remove # before $DB, also check error like below ;
$DB = #new mysqli($mysqlHost,$mysqlUser,$mysqlPass,$mysqlDB);
if($DB->connect_errno){
echo 'Could not connect to the server at this time. Please try again later.';
exit;
}
$stmt = $DB->prepare("INSERT INTO `users`(`email`, `password`) VALUES ('value1', 'value2')")
if ($stmt === FALSE) {
die($DB->error);
}
$stmt->execute();
$stmt->close();
$DB->close();
echo 'Data INSERTED INTO table.';
Im trying to create my own register form but im having issues with prepared statements.
the idea is to create a prepared statement to insert info into the user table, then from that get the insert_id from the generated content to use in another insert statement
here is a version of my register script
<?php
$returnedId = '';
include "includes/dbconnect.php";
$stmt = $db->prepare("INSERT INTO `users`(`Username`, `Email`, `Password`) VALUES (?, ?, ?)");
$stmt->bind_param('sss', $_POST['username'], $_POST['email'], $_POST['password']);
$stmt->execute();
$returnedId = $stmt->insert_id;
$stmt->close();
echo $returnedId;
$allergystmt = $db->prepare("INSERT INTO 'user_allergy' ('user_id', 'allergy_id') VALUES (?, ?)");
$allergystmt->bind_param('ss', $returnedId, $_POST['check_list']);
$allergystmt->execute();
$allergystmt->close();
header('Location: index.php');
?>
the first prepared statement runs correctly and inserts information into the table, after that the $returnId variable is successfully echoed. next in the script is my second prepared statement, when it tries to run im getting the error that says:
Fatal error: Call to a member function bind_param() on a non-object in D:\filepath\register.php on line 17
it seems that my variable isnt being carried into the second prepared statement.
Your second query has syntax errors and failed to prepare. Since you have no error handling for database failures like this, your later code just blunders onwards:
$allergystmt = $db->prepare("INSERT INTO 'user_allergy' ('user_id', 'allergy_id') VALUES (?, ?)");
^--- ^--^--- ^-- etc...
You cannot use ' quotes on table and field names. ' indicate strings. None of those field/table names are reserved words, so there is NO need to quote them at at all:
$allergystmt = $db->prepare("INSERT INTO user_allergy (user_id, allergy_id) VALUES (?, ?)");
if (!$allergystmt) { die($dbh->errorInfo()); }
Note the addition of the errorInfo() output. Never assume a DB operation was successful. Always assume failure, and treat success as a pleasant surprise.
As the title says Im trying to do a simple insert, but nothing actually is inserted into the table. I try to print out errors, but nothing is reported.
My users table has many more fields than these 4, but they should all default.
$query = 'INSERT INTO users (username, password, level, name) VALUES (?, ?, ?, ?)';
if($stmt = $db -> prepare($query))
{
$stmt -> bind_param('ssis', $username, $password, $newlevel, $realname);
$stmt -> execute();
$stmt -> close();
echo 'Any Errors: '.$db->error.PHP_EOL;
}
There are no errors given, but when I go to look at the table in phpmyadmin there is not a new row added. I know for sure that the types are correct (strings and integers). Is there something really wrong here or does it have something to do with the fact that I'm ignoring other columns. I have about 8 columns in the user table.
If you have turned auto commit off, you will have to explicitly call the commit method after you execute the query.
$stmt->execute();
$db->commit();
$stmt->close();
You have to check for errors at each stage of the process: When you connect, when you prepare the statement, when you bind, when you execute, and when you close. In your code, assuming the $db handle was properly created, the error check happens after the ->close() call, which should succeed, so there won't be any error at that point.
Something along these lines will show where things blew up:
$query = 'INSERT INTO users (username, password, level, name) VALUES (?, ?, ?, ?)';
$stmt = $db->prepare($query);
echo 'prepare error: ', $db->error, PHP_EOL;
$stmt->execute();
echo 'execute error: ', $db->error
etc....
Check if the string "Any Errors" is being printed. If not, then the statement:
if ($stmt = $db->prepare($query))
is returning false. You should move echo 'Any Errors: '.$db->error.PHP_EOL; outside of the conditional block.
Do u initialize the values of $username, $password, $newlevel, $realname before the
$stmt -> execute(); statement. Otherwise you have to initialize and try
$query = 'INSERT INTO users (username, password, level, name) VALUES (?, ?, ?, ?)';
if($stmt = $db -> prepare($query)){
$stmt -> bind_param('ssis', $username, $password, $newlevel, $realname);
$username='testname';$password='testpwd';$level=5;$realname='testrealname';
$stmt -> execute(); echo "inserted SuccessFully"; $stmt -> close(); }
else { printf("Prepared Statement Error: %s\n", $mysqli->error);}
try this code. If the query is executed successfully it show the "Inserted Successfully" otherwise it shows the error.