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
Related
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.
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 5 years ago.
My code is as follows:
include('config.php');
$mysqli = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
$statement = $mysqli->prepare("INSERT INTO brickTable (url, description) VALUES(?,?)");
$statement->bind_param("ss", $_POST["url"], $_POST["description"]);
I keep getting the error "Call to a member function bind_param() on boolean". I've looked all over S.O., and found several examples, but none that solved my issue. I don't see any syntax or typo errors in my code. Using a var_dump, I know that the $_POST["url"] and $_POST["description"] exist and are being received properly.
Thoughts or help?
First turn on error reporting by adding the below two lines at the top of your page. Then try printing out the exact error by doing echo $mysli->error;
error_reporting(E_ALL);
ini_set('display_errors', 1);
$mysqli = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
$statement = $mysqli->prepare("INSERT INTO brickTable (url, description) VALUES(?,?)");
echo $mysqli->error;
$statement->bind_param("ss", $_POST["url"], $_POST["description"]);
$statement->execute();
It will tell you the error.
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
Im a bit confused on this subject, I have seen variances in answers I have found and looking for a bit more direction for my application. What I am trying to do is use a PDO method to take data from a form with multiple entries and insert the data into my table I created.
I think I have an understanding of the overall concept but what I would like to do or rather not do is have to create a variable ( $player1 = $_POST['player1'] or similar...) for every input field I have.
Is there a way in my sql statement I can use something like $_POST['player1'] to use the input from the form? I tried doing it as such below, but Im getting this error:
Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) on line 19
line 19 being the values line of the sql statment...
html
<form method='post' action='phpfiles/Sqldata2.php'>
Enter data in for team 1. <br>
Enter Id: <input type='text' name='id1' maxlength='6'><br>
Enter Teamname: <input type='text' name='team1' maxlength='30'><br>
Enter city: <input type='text' name='city1' maxlength='30'><br>
Enter Bestplayer: <input type='text' name='best1' maxlength='30'><br>
Enter Year formed: <input type='number' name='year1' maxlength='4'><br>
Enter website: <input type='text' name='website1' maxlength='40'><br>
<br><br><br>
<input type='submit' name='SQLdata' value='Submit Data'>
</form>
php
<?php
// server and database information
$servername = " n/a ";
$username = " n/a ";
$password = " n/a ";
$dbname = " n/a ";
if ($_SERVER["REQUEST_METHOD"] == "POST"){
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// begin the transaction
$conn->beginTransaction();
// our SQL statememtns
$conn->exec("INSERT INTO teams (id, teamname, city, bestplayer, yearformed, website)
VALUES ($_POST['id1'], $_POST['teamname1'], $_POST['city1'], $_POST['bestplayer1'], $_POST['yearformed1'], $_POST['website1'])");
// commit the transaction
$conn->commit();
echo "New records created successfully";
}
catch(PDOException $e)
{
// roll back the transaction if something failed
$conn->rollback();
echo "Error: " . $e->getMessage();
}
$conn = null;
}
?>
The error im getting I believe is a syntax error such as that I need some more "" because my sql statment isnt a string? a little lost here and not sure if what Im trying to do is correct...
You had some typos that had to do with quoting. Alos try to use prepared statements to avoid SQL injection. Finally check the html name attributes of your form with your $_POST names you use (team1 or $_POST['teamname1']).
e.g.
$sql = "INSERT INTO teams (id, teamname, city, bestplayer, yearformed, website) VALUES (:id1, :teamname1, :city1, :bestplayer1, :yearformed1, :website1)";
$stmt = $conn->prepare($sql);
//Execute the query
$stmt->execute(array(':id1'=>$_POST['id1'], ':teamname1'=>$_POST['teamname1'], ':city1'=>$_POST['city1'], ':bestplayer1'=>$_POST['bestplayer1'], ':yearformed1'=>$_POST['yearformed1'], ':website1'=>$_POST['website1']));
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