Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
Below is a my code write up in which i am trying to insert data into two different tables with help of transactions but code is not executing. Trying very hard to find out issue but unable to resolve it.
I am getting this error: 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 ''u_id_fk','device_type','ip_num','package','pkg_id_fk') VALUES('79','abc','128.1' at line 1[]
$cust_name = 'multi';
$u_name = 'multi2';
$cnic_num = '421';
$address = 'sadaddd';
$password = md5('423423');
$cellnum='43243';
$p_id_fk=(int)'3';
try {
// First of all, let's begin a transaction
$conn->beginTransaction();
// If we arrive here, it means that no exception was thrown
// i.e. no query has failed, and we can commit the transaction
// Forgot to close the VALUES bracket and couldn't find your $email
$users_stmt=$conn->prepare("INSERT INTO users (`cust_name`, `u_name`, `cnic`, `address`, `password`, `email`) VALUES (:cust_name, :u_name, :cnic, :address, :password, :email)");
// PDO::execute() can accept an array of parameter bound to your query so you may avoid selecting data type when using bindParam()
$users_stmt->execute(["cust_name"=>$cust_name, "u_name"=>$u_name, "cnic"=>$cnic_num, "address"=>$address, "password"=>$password, "email"=>$email]);
// Not sure if $db is a PDO object...
$connections_stmt=$conn->prepare("INSERT INTO connections('u_id_fk','device_type','ip_num','package','pkg_id_fk') VALUES(:u_id_fk,:device_type,:ip_num,:package,:pkg_id_fk)");
$connections_stmt->execute(["u_id_fk"=>$u_id,"device_type"=>$device_type,"ip_num"=>$ip_num,"package"=>$package,"pkg_id_fk"=>$p_id_fk]);
$conn->commit();
} catch (Exception $e)
{
// An exception has been thrown
// We must rollback the transaction
$conn->rollback();
echo $e;
}
Please help to resolve it! Thanks
It is very important to set PDO error mode to EXCEPTION during connection.
Avoid using simple hashing algorithms for password as it can be extracted using Rainbow Attack.
$cust_name = 'multi';
$u_name = 'multi2';
$cnic_num = '421';
$address = 'sadaddd';
$password = md5('423423');
$cellnum='43243';
$p_id_fk=(int)'3';
try {
// DB vars
$db_host="";
$db_name="";
$db_username="";
$db_password="";
// Create a new PDO connection and set error mode to EXCEPTION
$conn=new PDO("mysql:host=".$db_host.";dbname=".$db_name,$db_username,$db_password,array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$conn->beginTransaction();
// Forgot to close the VALUES bracket and couldn't find your $email
$users_stmt=$conn->prepare("INSERT INTO users (`cust_name`, `u_name`, `cnic`, `address`, `password`, `email`) VALUES (:cust_name, :u_name, :cnic, :address, :password, :email)");
// PDO::execute() can accept an array of parameter bound to your query so you may avoid selecting data type when using bindParam()
$users_stmt->execute(["cust_name"=>$cust_name, "u_name"=>$u_name, "cnic"=>$cnic_num, "address"=>$address, "password"=>$password, "email"=>$email]);
$connections_stmt=$conn->prepare("INSERT INTO connections(`u_id_fk`,`device_type`,`ip_num`,`package`,`pkg_id_fk`) VALUES(:u_id_fk, :device_type, :ip_num, :package, :pkg_id_fk)");
$connections_stmt->execute(["u_id_fk"=>$u_id, "device_type"=>$device_type, "ip_num"=>$ip_num, "package"=>$package, "pkg_id_fk"=>$p_id_fk]);
$conn->commit();
} catch (Exception $e){
$conn->rollback();
echo $e->getMessage();
}
The closing double quotation in your first statement is not correct, it must be at the end of it and also you missed the end bracket of prepare function
$stmt=$conn->prepare("INSERT INTO users (cust_name, u_name,cnic,address,password,email) VALUES (?, ?, ?, ?, ?, ?)");
Try to correct that typo.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Linked question is here.
I have upgraded the code in the linked question to use a prepared statement.
I now have:
$stmt = $conn->prepare("INSERT INTO `workbook-data` (`workbook-language`, `gui-language`, `foreign-language-group-mode`, `version`) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssis', $mwblang, $guilang, $flgmode, $version);
$mwblang = mysqli_real_escape_string($conn, $_GET['mwblang']);
$guilang = mysqli_real_escape_string($conn, $_GET['guilang']);
$flgmode = mysqli_real_escape_string($conn, $_GET['flg']);
$version = mysqli_real_escape_string($conn, $_GET['version'] ?? '210061');
if ($stmt->execute()) {
echo "<br>" . "New record created successfully";
} else {
echo "Error: " . mysqli_error($conn);
}
$stmt->close();
According to the documentation for bind_param it states this about the return value:
Returns true on success or false on failure.
In these official examples they don't seem to do any error checking for failure. Should be we testing the return value? I have done so for execute() but I am not sure how much checking is needed.
You should not be checking for the return value of any of mysqli functions. This is just pointless. When you enable proper mysqli error reporting you will be automatically informed of all the errors.
If you decide to keep the error reporting silenced for some strange reason, then you must check every single mysqli function call including bind_param(). If you do check for the return value, make sure to never display the error message on the screen. Log the errors to a file in a safe place.
So, your code should look like this:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli('localhost', 'user', 'password', 'test');
$conn->set_charset('utf8mb4'); // always set the charset
// ...
$stmt = $conn->prepare("INSERT INTO `workbook-data` (`workbook-language`, `gui-language`, `foreign-language-group-mode`, `version`) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssis', $mwblang, $guilang, $flgmode, $version);
$stmt->execute();
or like this:
mysqli_report(MYSQLI_REPORT_OFF);
$conn = new mysqli('localhost', 'user', 'password', 'test');
if ($conn->connect_errno) {
error_log($conn->connect_error);
}
if (false === $conn->set_charset('utf8mb4')) {
error_log($conn->error);
}
// ...
if (false === ($stmt = $conn->prepare("INSERT INTO `workbook-data` (`workbook-language`, `gui-language`, `foreign-language-group-mode`, `version`) VALUES (?, ?, ?, ?)"))) {
error_log($conn->error);
}
if (false === $stmt->bind_param('ssis', $mwblang, $guilang, $flgmode, $version)) {
error_log($stmt->error);
}
if (false === $stmt->execute()) {
error_log($stmt->error);
}
Note how there are 3 different ways of reading the error message depending on which function you called. Manual error checking is much more verbose.
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
PHP's white screen of death [duplicate]
Closed 5 years ago.
I am new to using PDO and I am getting an http 500 server error when the form is submitted.
The php page with the processing code is in the correct folder so I don't know why its throwing up a 500 error.
There is NO url rewrite going on neither .
Here is my code:
try {
$dbh = new PDO("mysql:host=$hostname;dbname=crm",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$stmt = $db->prepare("INSERT INTO testdrives (forename, surname,phone,email,add1,add2,add3,city,county,postcode,car,date) VALUES (:forename, :surname,:phone,:email,:add1,:add2,:add3,:city,:county,:postcode,:car,:date)");
$stmt->bindParam(':forename', $_POST['forename']);
$stmt->bindParam(':surname', $_POST['surname']);
$stmt->bindParam(':phone', $_POST['phone']);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':add1', $_POST['add1']);
$stmt->bindParam(':add2', $_POST['add2']);
$stmt->bindParam(':add3', $_POST['add3']);
$stmt->bindParam(':city', $_POST['city']);
$stmt->bindParam(':county', $_POST['county']);
$stmt->bindParam(':postcode', $_POST['postcode']);
$stmt->bindParam(':car', $_POST['car']);
$stmt->bindParam(':date', $_POST['date']);
$stmt->execute();
if ($dbh->query($sql)) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
Edit:
I missed the incorrect variable used for the connection being $dbh and $db in the prepare; my bad.
Original answer.
This line:
if ($dbh->query($sql)) {...}
is failing for two reasons:
Calling query() on what is already being prepared/executed.
Using a non-existant variable, $sql.
Get rid of that statement with the related brace and replace it with simply and replacing the $stmt->execute(); with:
if($stmt->execute()){
// success
} else{
// error
}
and using PDO's error handling (as you are doing now) and PHP's error reporting:
http://php.net/manual/en/pdo.error-handling.php
http://php.net/manual/en/function.error-reporting.php
Check your logs also.
Found the problem
The above code shows
$stmt = $db->prepare
Needed to be changed to
$stmt = $dbh->prepare
Thanks for help with the other issue
Quick question how to i insert into a table that has an auto increment column ?
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
My html :
<form action="rent.php" method="post"><pre>
Email : <input type="text" name="email">
Message : <input type="text" name="msg_text">
<input type="submit" value="Rent it">
</pre></form>
My rent.php file :
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) {
die($conn->connect_error);
}
$query = "SET NAMES utf8";
$result = $conn->query($query);
if (!$result) {
die($conn->error);
}
$req = $conn->prepare('INSET INTO renter (email, msg_text) VALUES(?, ?)');
$req->execute(array($_POST['email'], $_POST['msg_text']));
header('Location: menu.php');
My error when I try to submit, is : Fatal error: Call to a member function execute() on boolean in C:...\rent.php on line 18
email, msg_text are in varchar type
mysqli->prepare can also return FALSE (check http://php.net/manual/en/mysqli.prepare.php) if an error occurred. Your problem is that you have INSET instead of INSERT.
This may help someone:
I was facing same issue.
In my case, i have missed to close first prepared statement before executing second prepared statement.
When i have added $select_stmt_type->close(); before executing second prepare statement, it fixed the issue.
Just to add. Similar error comes when the mysql column name is incorrect in php. I found below error for my condition when i printed the $conn->error.
errno: 1054, error: Unknown column 'xyz' in 'field list'
To catch errors do something like this
$req = $conn->prepare('INSERT INTO renter (email, msg_text) VALUES(?, ?)');
if(!$req){
echo "Prepare failed: (". $conn->errno.") ".$conn->error."<br>";
}
since prepare returns a boolean. Please use when debugging you code and refer to error reporting as stated in the comment.
Your SQL prepared statement needs to be corrected as shudent said, but I think you also have to set the values with ->bind_param() before calling ->execute() (which does not take any parameters).
$stmt = $conn->prepare('INSERT INTO renter (email, msg_text) VALUES(?, ?)');
$stmt->bind_param("ss", $_POST['email'], $_POST['msg_text']);
$stmt->execute();
See documentation and example on the PHP official site : http://php.net/manual/fr/mysqli.prepare.php
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've been trying to get a form to insert records to a MySQL database using a form, but for some reason it errors out on me and I can't figure out why.
Here is the code that processes the request:
if ($_SERVER['REQUEST_METHOD']=='POST'){
// database connection
try {
$dbh = new PDO('mysql:host='.$host.';dbname='.$dbName, $dbUser, $dbPass);
$dbh -> setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$dbh -> exec("SET NAMES 'utf8'");
} catch (Exception $e) {
echo "Error!: " . $e->getMessage() . "<br/>";
die();
}
// new data
$title = $_POST["txtTitle"];
$description = $_POST["txtDesc"];
$content = $_POST["txtContent"];
$sql = "INSERT INTO tblPageContent
SET (PageTitle, Description, PageContent)
VALUES (:title, :desc, :content)";
try {
$update = $dbh->prepare($sql);
$update->bindParam(":title",$title, PDO::PARAM_STR);
$update->bindParam(":desc",$description, PDO::PARAM_STR);
$update->bindParam(":content",$content, PDO::PARAM_STR);
$update->execute();
$id = $update->dbh->lastInsertId();
$update->dbh->commit();
echo $id;
} catch (Exception $e) {
echo "Data could not be updated in the database.";
echo $e;
exit;
}
}
Whenever I try to use it, I end up with this:
exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error
or access violation: 1064 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 '(PageTitle, Description, PageContent) VALUES
('Awards', 'This is a test', '' at line 2'
I've tried tweaking the SQL syntax, but I still can't get it to work. Is there something I'm missing here?
Your insert syntax is WRONG.
The correct syntax is:
insert into tblPageContent (pageTitle, Description, PageContent)
values (:title, :desc, :content)
I recommend you have MySQL reference manual at hand
In your SQL, take out the SET before the first (. You use SET in updates, not inserts.
This question already has answers here:
Reference — frequently asked questions about PDO
(3 answers)
Closed 9 years ago.
I'm trying to insert values to mysql database, but for some reason this is not working. I can get it to work with normal PHP but I have been told that PDO would be safer to use. This is the code I use, the values are posted to the php file, but not updated to mysql. What could be the reason for that?
<?php
include 'config.php';
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$value1 = $_POST["value1"];
$value2 = $_POST["value2"];
$value3 = $_POST["value3"];
$value4 = $_POST["value4"];
// query
$sql = "INSERT INTO `database`.`table`
(`id`, `value1`, `value2`, `value3`, `value4`, `timeStamp`)
VALUES (NULL, ?, ?, ?, ?, CURRENT_TIMESTAMP)";
$q = $conn->prepare($sql);
$q->execute(array($value1, $value2, $value3, $value4));
?>
Change this line
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
to this
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
and use try catch on
try
{
$q->execute(array($value1, $value2, $value3, $value4));
}
catch(Exception $e)
{
echo $e->getMessage();
//other code to handle exception for example logging, rollback transaction if exists etc.
}
When you make these changes then PDO Exceptions will be thrown and you will see what problem is. With PDO exception you can do more to handle error, for example if you use transactions then you can in catch block rollback it.
You can use error_reporting(E_ALL); and display_errors with ini_set().
You can also use PDO::errorInfo
From manual:
PDO::errorInfo — Fetch extended error information associated with the last operation on the database handle
To see examples check this link
Check these links:
how to set display errors
info about exceptions
pdo exception