I'm trying to implement my first prepared statement using mysqli.
At the moment I have this:
<?php
$con = new mysqli('example.com', 'user', 'password', 'database');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();}
$first = $_GET['firstname'];
$last = $_GET['surname'];
$dob = $_GET['dob'];
$address = $_GET['homeaddress'];
$college = $_GET['college'];
$emergname = $_GET['emergencyname'];
$emergnumber = $_GET['emergencynumber'];
$condition = $_GET['condition'];
$conditiondetails = $_GET['conditiondetails'];
$medication = $_GET['medication'];
$medicationdetails = $_GET['medicationdetails'];
if($stmt = $con->prepare("INSERT INTO medical ('forename', 'surname', 'dob', 'address', 'college', 'emergency_name', 'emergency_number', 'condition', 'condition_details', 'medication', 'medication_details') VALUES (:forename, :surname, :dob, :address, :college, :emergencyname, :emergencynumber, :condition, :conditiondetails, :medication, :medicationdetails)")){
$stmt->bind_param(':forename', $first);
$stmt->bind_param(':surname', $last);
$stmt->bind_param(':dob', $dob);
$stmt->bind_param(':address', $address);
$stmt->bind_param(':college', $college);
$stmt->bind_param(':emergencyname', $emergname);
$stmt->bind_param(':emergencynumber', $emergnumber);
$stmt->bind_param(':condition', $condition);
$stmt->bind_param(':conditiondetails', $conditiondetails);
$stmt->bind_param(':medication', $medication);
$stmt->bind_param(':medicationdetails', $medicationdetails);
$stmt->execute();
$stmt->close();} ?>
I have previously tried a variance using:
<?php
$stmt = $con->prepare("INSERT INTO medical ('forename', 'surname', 'dob', 'address', 'college', 'emergency_name', 'emergency_number', 'condition', 'condition_details', 'medication', 'medication_details') VALUES (?,?,?,?,?,?,?,?,?,?,?)")
$stmt->bind_param('sssssssssss', $first...);
?>
In both instances I get an error message that the $stmt variable doesn't exist.
Any suggestions as to where I'm going wrong?
Column names should be escaped with backticks, not single-quotes. Also, you can't use named parameter bindings.
Try
$stmt = $con->prepare("INSERT INTO medical (`forename`, `surname`, `dob`, `address`, `college`, `emergency_name`, `emergency_number`, `condition`, `condition_details`, `medication`, `medication_details`) VALUES (?,?,?,?,?,?,?,?,?,?,?)")
if (!$stmt)
{
echo $con->error;
}
Maybe you should try using this SQL syntax instead:
$stmt = $con->prepare("INSERT INTO medical VALUES (:forename, :surname, :dob, :address, :college, :emergencyname, :emergencynumber, :condition, :conditiondetails, :medication, :medicationdetails)");
$stmt->bind_param(':forename', $first);
$stmt->bind_param(':surname', $last);
$stmt->bind_param(':dob', $dob);
$stmt->bind_param(':address', $address);
$stmt->bind_param(':college', $college);
$stmt->bind_param(':emergencyname', $emergname);
$stmt->bind_param(':emergencynumber', $emergnumber);
$stmt->bind_param(':condition', $condition);
$stmt->bind_param(':conditiondetails', $conditiondetails);
$stmt->bind_param(':medication', $medication);
$stmt->bind_param(':medicationdetails', $medicationdetails);
$stmt->execute();
Or try:
$stmt = $con->prepare("INSERT INTO medical VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param('sssssssssss', $first, $second, $third, $fourth, $fifth, $sixth, $seventh, $eighth, $ninth, $tenth, $eleventh);
Meaning, without no Use-Fields declaration in your INSERT statement.
Related
I'm trying to use prepared statements to enter data in a database. The unprepared statement works but this prepared statement does not. I can't find out why.
Prepared version:
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path)
VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $newstring, $id, $date->format('Y-m-d'), $location);
$stmt->execute();
Unprepared version:
$sql = "INSERT INTO videos (file_name, upload_by, date, path) VALUES ('$newstring', '$id', '
$date', 'Nominator/$location$newstring')";
mysqli_query($mysqli, $sql);
Replace $stmt-execute(); with $stmt->execute();
Also, don't use date and path in query. Rename them with some other name like date1 and path1.
Update your Query like below that will surely work (Tested Offline):
<?php
$mysqli = new mysqli('localhost', 'root', '', 'test2');
if ($mysqli->errno) {
printf("Connect failed: %s\n", $mysqli->error);
exit();
}
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date1, path1) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $file_name, $upload_by, $date1, $path1);
$date1 = date("Y-m-d");
$file_name = "test.jpg";
$upload_by = "amit";
$path1 = "test";
if ($result = $stmt->execute()){
echo "success";
$stmt->free_result();
} else {
echo "error";
}
$stmt->close();
?>
You are binding your parameter twice, if you are using only ?, don't bind parameter again just execute directly.
//Prepare your query first
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path)
VALUES (?, ?, ?, ?)");
//Just pass your argument and execute directly without binding the parameter (The parameter is binded already)
$stmt->execute('ssss', $newstring, $id, $date->format('Y-m-d'), $location);
I encountered a problem while making a prepared statement using php and mysql. For some reason my variables aren't right.
Note: - $mysqli = $conn
$stmt = $mysqli->prepare("INSERT INTO `inschrijving` (`id`, `bezoeker_naam`, `bezoeker_voornaam`, `bezoeker_email`, `bezoeker_straat`, `bezoeker_huisnummer`, `bezoeker_postnummer`, `bezoeker_plaats`) VALUES (NULL, '{$mysqli->real_escape_string('?')}', '{$mysqli->real_escape_string('?')}', '{$mysqli->real_escape_string('?')}', '{$mysqli->real_escape_string('?')}', '{$mysqli->real_escape_string('?')}', '{$mysqli->real_escape_string('?')}', '{$mysqli->real_escape_string('?')}');");}
$stmt->bind_param("sssssss", $naam, $voornaam, $email, $straat, $huisnummer, $postcode, $plaats);
$naam = $_POST['naam'];
$voornaam = $_POST['voornaam'];
$email = $_POST['email'];
$straat = $_POST['straat'];
$huisnummer = $_POST['nummer'];
$postcode = $_POST['postcode'];
$plaats = $_POST['plaats'];
$stmt->execute();
The error I got was this:
mysqli_stmt::bind_param(): Number of variables doesn't match number of
parameters in prepared statement
I am new doing prepared statements and I need someone to point my faults out on this. It will really help me get to know more about prepared statements. :)
When working with prepared statements you shouldn't escape the bound variables:
$stmt = $mysqli->prepare("INSERT INTO `inschrijving` (`id`, `bezoeker_naam`, `bezoeker_voornaam`, `bezoeker_email`, `bezoeker_straat`, `bezoeker_huisnummer`, `bezoeker_postnummer`, `bezoeker_plaats`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?)");
I would declare your POST variables above the prepare portion like so and remove the $mysqli->real_escape_string() from the statement:
$naam = $_POST['naam'];
$voornaam = $_POST['voornaam'];
$email = $_POST['email'];
$straat = $_POST['straat'];
$huisnummer = $_POST['nummer'];
$postcode = $_POST['postcode'];
$plaats = $_POST['plaats'];
$stmt = $mysqli->prepare("INSERT INTO `inschrijving` (`id`, `bezoeker_naam`, `bezoeker_voornaam`, `bezoeker_email`, `bezoeker_straat`, `bezoeker_huisnummer`, `bezoeker_postnummer`, `bezoeker_plaats`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssss", $naam, $voornaam, $email, $straat, $huisnummer, $postcode, $plaats)";
$stmt->execute();
You can put the $mysqli->real_escape_string() around the POST variables instead. For example:
$naam = $mysqli->real_escape_string($_POST['naam']);
Lastly, make sure that all the variables are strings and don't forget to close the $stmt.
$stmt->close();
I have this code:
<link rel="stylesheet"href="includes/css/bootstrap.min.css"><?php
require_once "class.php";
$conn = new db_class();
if(ISSET($_POST['signup'])){
$username = $_POST['username'];
$password = sha1($_POST['password']);
$confpassword = sha1($_POST['confpassword']);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$conn->save($username, $password,$confpassword, $firstname, $lastname);
} ?>
and this is the function :
public function save($username, $password,$confpassword, $firstname, $lastname){
$stmt = $this->conn->prepare("SELECT * FROM `user` WHERE `username` = '$username'") or die($this->conn->error);
if($stmt->execute()){
$result = $stmt->get_result();
if($password!=$confpassword){
echo "<div class=\"alert alert-danger\"><strong>password does not match</strong></div>";
}else
if( $result->num_rows == 0){
$stmt1 = $this->conn->prepare("INSERT INTO `user` (username, password, confirmPass, firstname, lastname) VALUES('$username', '$password','$confpassword', '$firstname', '$lastname')") or die($this->conn->error);
$stmt1->bind_param("s", $username, $password, $confpassword, $firstname, $lastname);
$stmt1->execute();
everything work great except this warning:
Warning: mysqli_stmt::bind_param(): Number of elements in type
definition string doesn't match number of bind variables in C:\Program
Files
(x86)\EasyPHP-DevServer-14.1VC11\data\localweb\segments\class.php on
line 214
any idea? I tried to add more "s" in here:
$stmt1->bind_param("s", $username, $password, $confpassword, $firstname, $lastname);
And still have the same warning. Any ideas?
When using prepared statements, you must use placeholders. Without them, not only would you get unecessary fatal erros, but you are defeating the use of prepared statements.
You are binding 5 variables, therefore you need 5 placeholders to bind them.
$stmt1 = $this->conn->prepare("INSERT INTO `user` (username, password, confirmPass, firstname, lastname) VALUES(?, ?,?, ?, ?)") or die($this->conn->error);
$stmt1->bind_param("sssss", $username, $password, $confpassword, $firstname, $lastname);
$stmt1->execute();
This is wrong
$stmt1 = $this->conn->prepare("INSERT INTO `user` (username, password, confirmPass, firstname, lastname) VALUES('$username', '$password','$confpassword', '$firstname', '$lastname')") or die($this->conn->error);
You need to have placeholders that you will bind not variables above
this is what you need:
$stmt1 = $this->conn->prepare("INSERT INTO `user` (username, password, confirmPass, firstname, lastname) VALUES(?,?,?,?,?)") or die($this->conn->error);
$stmt1->bind_param("sssss", $username, $password, $confpassword, $firstname, $lastname);
$stmt1->execute();
Update :
this or die($this->conn->error); is somehow useless where you have put it as the query does not get executed, in that line you are just preparing, you need to check success/fail after execute()
therefore should be like :
<?php
$stmt1 = $this->conn->prepare("INSERT INTO `user` (username, password, confirmPass, firstname, lastname) VALUES(?,?,?,?,?)");
$stmt1->bind_param("sssss", $username, $password, $confpassword, $firstname, $lastname);
$stmt1->execute();
if(!$stmt1){
die($this->conn->error);
}
?>
My php files that submits an entry to a database table isn't working and I can't figure out why. It takes in an Ajax submit and I know that the problem isn't with the data, or the Ajax request as it processes as a success. The only issue is that no data is ever submitted to my database. I had this working before I changed to code to concatenate the address string where it was one variable before. Any advice would be great!
Here is the php files
UPDATE:::THIS IS THE UPDATED PHP FILE
<?php
require("dbinfo.php");
// Create connection
$conn = new mysqli('localhost', $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = $_POST['user_name'];
$street = $_POST['user_street'];
$city = $_POST['user_city'];
$state = $_POST['user_state'];
$country = $_POST['user_country'];
$zip = $_POST['user_zip'];
$address = $street.', '.$city.', '.$state.', '.$country.', '.$zip;
$shortAdd = $city.', '.$state.', '.$country;
$type = $_POST['user_color'];
$desc = $_POST['user_message'];
$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$address."&sensor=true";
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->status;
if ($status=="OK") {
$lat = $xml->result->geometry->location->lat;
$lon = $xml->result->geometry->location->lng;
}
$sql = "INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`, `desc`)
VALUES (?, ?, ?, ?, ?, ?);";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssssss', $name, $shortAdd, $lat, $lon, $type, $desc);
$stmt->execute();
$conn->close();
?>
While docliving's answer is correct, please take the extra step and use prepared statements. Your code is vulnerable to SQL injection attacks without it. It just takes a very minor change to convert it to use prepared statements. Here is how to do it with mysqli:
$sql = "INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`, `desc`)
VALUES (?, ?, ?, ?, ?, ?);";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssssss', $name, $shortAdd, $lat, $lon, $type, $desc);
$stmt->execute();
When #MySelfBoy wrote:
After the assignment, you have to execute SQL statements
He means that you have to execute your query
$sql = "INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`, `desc`)
VALUES ('$name', '$shortAdd', '$lat', '$lon', '$type', '$desc');";
with the following instruction:
$conn->query($sql);
NOTE: I Still canĀ“t make comments, so I'm posting it here.
All I want to know is if you can use mysqli's prepare, execute, and rollback together?
$m = new mysqli($dbhost,$dbuser,$dbpassword,$dbname);
$m->autocommit(FALSE);
$stmt = $m->prepare("INSERT `table` (`name`,`gender`,`age`) VALUES (?,?,?)");
$stmt->bind_param("ssi", $name, $gender, $age);
$query_ok = $stmt->execute();
$stmt = $m->prepare("INSERT `table` (`name`,`gender`,`age`) VALUES (?,?,?)");
$stmt->bind_param("ssi", $name, $gender, $age);
if ($query_ok) {$query_ok = $stmt->execute();}
if (!$query_ok) {$m->rollback();} else {$m->commit();}
Can you do this? Let's assume that the above code has a loop and or the variables get new data in them.
Best way to handle this is with exceptions (as always, darn PHP error/warning stuff). Simply because our commit() call may fail too. Note that finally is only available in newer PHP versions.
<?php
// Transform all errors to exceptions!
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$connection = new \mysqli($dbhost, $dbuser, $dbpassword, $dbname);
$connection->autocommit(false);
$stmt = $connection->prepare("INSERT `table` (`name`, `gender`, `age`) VALUES (?, ?, ?)");
$stmt->bind_param("ssi", $name, $gender, $age);
$stmt->execute();
// We can simply reuse the prepared statement if it's the same query.
//$stmt = $connection->prepare("INSERT `table` (`name`, `gender`, `age`) VALUES (?, ?, ?)");
// We can even reuse the bound parameters.
//$stmt->bind_param("ssi", $name, $gender, $age);
// Yet it would be better to write it like this:
/*
$stmt = $connection->prepare("INSERT `table` (`name`, `gender`, `age`) VALUES (?, ?, ?), (?, ?, ?)");
$stmt->bind_param("ssissi", $name, $gender, $age, $name, $gender, $age);
*/
$stmt->execute();
$connection->commit();
}
catch (\mysqli_sql_exception $exception) {
$connection->rollback();
throw $exception;
}
finally {
isset($stmt) && $stmt->close();
$connection->autocommit(true);
}