Something with variables and parameters (Prepared statement) - php

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();

Related

mysqli prepared statements - doyou still need to escape data?

I am a bit confused about MYSQLI prepared statements. If you use prepared statements is the data automatically escaped or do you still have to do that.
I have attached some code below - based on this example is the data automatically escaped or do I have to do that also ?
include("configi.php");
$stmt = $conn->prepare("INSERT INTO phx_userid (comp_name, email, password, user_sec_level, user_status, username, contact_name, comp_type, comp_system_option) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssiissss", $comp_name, $email_address, $password, $user_sec_level, $user_status, $email_address, $contact_name, $comp_type, $comp_system_option);
// set parameters and execute
$comp_name = $comp_name;
$email_address = $email_address;
$password = password_hash($password, PASSWORD_DEFAULT);
$user_sec_level = 600;
$user_status = 0;
$contact_name = $first_name . " " . $last_name;
$comp_type = "fintrack";
$comp_system_option = "standard";
$stmt->execute();
No errors - I just want to check if I am doing this right.

sql error when submitting with php

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.

How incorporate On Duplicate Key with bind_param

Hi How can i incorporate On Duplicate Key with mysqli_stmt_bind_param
$stmt = mysqli_prepare($con, "INSERT INTO assy (ItemID,partid,qty,rev,bomEntry) VALUES (?, ?, ?, 'A',?) ON DUPLICATE KEY UPDATE partid=$bom");
mysqli_stmt_bind_param($stmt, "ssii", $itemid, $bom, $qty, $bomEntry) or die(mysqli_error($con));
$recordd = $tv->search(454545400000, 's=2');
//print_r($recordd);echo"1<br/>";
foreach($recordd as $data2) {
$itemid = $data2['fields']['CALC STOCK NO'];
$bomEntry = 1;
if ($data2['fields']['BOM WHEEL PN']) {
$bom = $data2['fields']['BOM WHEEL PN'];
$qty=1;
mysqli_stmt_execute($stmt) or die(mysqli_stmt_error($stmt));
$bomEntry++;
}
}
I tried something like
$stmt = mysqli_prepare($con, "INSERT INTO table_name (ItemID,partid,qty,rev,bomEntry) VALUES (?, ?, ?, 'A',?) ON DUPLICATE KEY UPDATE patid=$bom;");
.
.
.
but it set to blank
Your $bom is a string so it need to be quoted, or preferably swapped out of the query and bound via a placeholder. Here is the placeholder and binding approach:
$stmt = mysqli_prepare($con, "INSERT INTO assy (ItemID,partid,qty,rev,bomEntry) VALUES (?, ?, ?, 'A',?) ON DUPLICATE KEY UPDATE partid=?");
mysqli_stmt_bind_param($stmt, "ssiis", $itemid, $bom, $qty, $bomEntry, $bom);
With prepared statements you rarely will want variables in your query.

PHP SQL insert prepared statements doesn't insert properly

When executing the following code, no Errors occur but the data isn't put into the database!
$zero = 0;
$connection = new mysqli("localhost", "andrewle_me", "*****", "andrewle_velocity");
$stmt = $connection->prepare("INSERT INTO accounts Values(?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("issssssi", $zero, $_POST["username"], password_hash($_POST["password"], PASSWORD_DEFAULT), $_POST["Email"], $_POST["firstname"], $_POST["lastname"], $_POST["nationality"], $zero);
$stmt->execute();
$stmt->close();
$connection->close();
echo "Success";
Define your posts and password hash outside of the param binding. Set the fields in the table that your values are going to be entered into.

mysqli prepared statement woes

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.

Categories