"No data supplied for parameters in prepared statement" - php

So I am reworking a script to include prepared statements. It was working fine before, but now I am getting "No data supplied for parameters in prepared statement" when the script runs. What is the issue here?
<?php
require_once("models/config.php");
$firstname = htmlspecialchars(trim($_POST['firstname']));
$firstname = mysqli_real_escape_string($mysqli, $firstname);
$surname = htmlspecialchars(trim($_POST['surname']));
$surname = mysqli_real_escape_string($mysqli, $surname);
$address = htmlspecialchars(trim($_POST['address']));
$address = mysqli_real_escape_string($mysqli, $address);
$gender = htmlspecialchars(trim($_POST['gender']));
$gender = mysqli_real_escape_string($mysqli, $gender);
$city = htmlspecialchars(trim($_POST['city']));
$city = mysqli_real_escape_string($mysqli, $city);
$province = htmlspecialchars(trim($_POST['province']));
$province = mysqli_real_escape_string($mysqli, $province);
$phone = htmlspecialchars(trim($_POST['phone']));
$phone = mysqli_real_escape_string($mysqli, $phone);
$secondphone = htmlspecialchars(trim($_POST['secondphone']));
$secondphone = mysqli_real_escape_string($mysqli, $secondphone);
$postalcode = htmlspecialchars(trim($_POST['postalcode']));
$postalcode = mysqli_real_escape_string($mysqli, $postalcode);
$email = htmlspecialchars(trim($_POST['email']));
$email = mysqli_real_escape_string($mysqli, $email);
$organization = htmlspecialchars(trim($_POST['organization']));
$organization = mysqli_real_escape_string($mysqli, $organization);
$inriding = htmlspecialchars(trim($_POST['inriding']));
$inriding = mysqli_real_escape_string($mysqli, $inriding);
$ethnicity = htmlspecialchars(trim($_POST['ethnicity']));
$ethnicity = mysqli_real_escape_string($mysqli, $ethnicity);
$senior = htmlspecialchars(trim($_POST['senior']));
$senior = mysqli_real_escape_string($mysqli, $senior);
$student = htmlspecialchars(trim($_POST['student']));
$student = mysqli_real_escape_string($mysqli, $student);
$order= "INSERT INTO persons (firstname, surname, address, gender, city, province, postalcode, phone, secondphone, email, organization, inriding, ethnicity, senior, student_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($mysqli, $order);
mysqli_stmt_bind_param($stmt, "sssd", $firstname, $surname, $address, $gender, $city, $province, $postalcode, $phone, $secondphone, $email, $organization, $inriding, $ethnicity, $senior, $student);
mysqli_stmt_execute($stmt);
echo $stmt->error;
$result = mysqli_query($mysqli,$stmt);
if ($result === false) {
echo "Error entering data! <BR>";
echo mysqli_error($mysqli);
} else {
echo "User $firstname added <BR>";
}
?>
Thanks in advance.

You have only bound four arguments, by the control string "sssd", but you have many parameters. When binding variables with mysqli, you need one character for each parameter, for example:
mysqli_stmt_bind_param($stmt, "sssdsssssssssdd", $firstname, $surname, $address,
$gender, $city, $province, $postalcode, $phone, $secondphone, $email,
$organization, $inriding, $ethnicity, $senior, $student);
(I'm assuming senior and student are integers, and need the "d" code.)
You don't need to treat any of your variables with mysqli_real_escape_string() -- that's the point of using parameters. If you do escaping as well, you'll get literal backslash characters in your data in the database.
And you never need to use htmlspecialchars() in any case - you would use that when outputting to HTML, not when inserting to the database. You're going to get literal sequences like & in your data in the database.
Re your next error:
"Catchable fatal error: Object of class mysqli_stmt could not be converted to string in..."
This is caused by the following:
$result = mysqli_query($mysqli,$stmt);
That function expects the second argument to be a string, a new SQL query. But you've already prepared that query, so you need the following:
$result = mysqli_stmt_execute($stmt);

Related

PHP Prepared Statement not executing correctly

I have been staring at a problem for far to long now.
I have a PHP file that is preparing an insert query, binding the params, and executing the query (Simple).
QUERY
$stmt = $db->prepare("SELECT insert_user(?, ?, ?, ?, ?, ?)");
For some reason the $stmt object returned by execute returns -1 for the affected rows. If I alter the code to do just an insert query with the values I wanted to bind, hard coded instead, the query works just fine.
HARD CODED QUERY
$db->query("SELECT insert_user('Test', 'Account', 'testAccount#testApp.io', 'testAccount9', '1980-01-01', 1)");
Something is going wrong in the bind_param section. I have errors turned on and am checking for mysqli errors too, but both are returning no errors.
PHP FILE
...
$postdata = file_get_contents("php://input");
if (isset($postdata) && !empty($postdata)) {
$request = json_decode($postdata);
}
if (
validate_string($request->fname)
&& validate_string($request->lname)
&& validate_integer(intval($request->gender))) {
$stmt = $db->prepare("SELECT insert_user(?, ?, ?, ?, ?, ?)");
if ($stmt) {
$stmt->bind_param("ssssis", $first_name, $last_name, $email, $password, $gender, $dob);
$first_name = $request->fname;
$last_name = request->lname;
$email = $request->email;
$password = password_hash($request->password, PASSWORD_BCRYPT);
$gender = intval($request->gender);
$dob = $request->dob;
$stmt->execute();
if ($stmt->affected_rows > 0) {
echo toJson('success');
} else {
echo toJson('fail');
}
} else {
echo toJson("Prepare failed: (" . $db->errno . ") " . $db->error);
}
} else {
echo toJson('fail - passed data not valid');
}
...
I feel the error must be simple at this point, but I have tried at least 23,432 different things to no success.
My guess the problem is here "ssssis" .
The fifth should be string, the last integer. Maybe this should work?

Brand new to coding: Fatal error: Call to a member function execute() on boolean

I am assuming by "Boolean" that it is coming out as "false"...
Can anyone explain what could be wrong here?
My code may be flawed altogether, but I would like some constructive criticism.
<?php
if ($_SERVER['REQUEST_METHOD'] = "POST") {
include("mytableconn.php");
$firstName = mysqli_real_escape_string($conn, trim($_POST['firstn']));
$lastName = mysqli_real_escape_string($conn, trim($_POST['lastn']));
$email = mysqli_real_escape_string($conn, trim($_POST['uemail']));
$password = mysqli_real_escape_string($conn, trim($_POST ['userpasscode']));
$cryption = "$2y$10$";
$chars = "thisisseriouslyfucked1";
$crypchar = $cryption . $chars;
$crypass = crypt($password, $crypchar);
$user = $conn->prepare("
INSERT INTO mytable(first_name, last_name, e_mail, pass_word)
VALUES(?, ?, ?, ?)
");
$user = $user->bind_param("ssss", $firstName, $lastName, $email, $crypass);
$user->execute();
$user->close();
$conn->close();
}else {
echo("Sorry, an unexpected error occurred");
}
?>
When you prepare the sql you assign it as a variable - you should then test that variable before proceeding to check that the sql is valid.
mysqli_prepare() returns a statement object or FALSE if an error
occurred
<?php
if ( $_SERVER['REQUEST_METHOD'] = "POST" ) {
include("mytableconn.php");
$firstName = mysqli_real_escape_string($conn, trim($_POST['firstn']));
$lastName = mysqli_real_escape_string($conn, trim($_POST['lastn']));
$email = mysqli_real_escape_string($conn, trim($_POST['uemail']));
$password = mysqli_real_escape_string($conn, trim($_POST['userpasscode']));
$cryption = "$2y$10$";
$chars = "thisisseriouslyfucked1";
$crypchar = $cryption . $chars;
$crypass = crypt( $password, $crypchar );
$stmt = $conn->prepare("insert into `mytable` ( `first_name`, `last_name`, `e_mail`, `pass_word` ) values (?, ?, ?, ?)");
if( $stmt ){
$stmt->bind_param("ssss", $firstName, $lastName, $email, $crypass);
$stmt->execute();
$stmt->close();
}
$conn->close();
}else {
echo("Sorry, an unexpected error occurred");
}
?>

Is this code vulnerable to sql injection?

Is this code prone to SQL Injection? Can you suggest something to improve the security? Is it right to use mysqli_real_escape_string? And do you think it's alright to use this for project?
<?php
require 'db.php';
if(isset($_POST['pawnshopName'])&&isset($_POST['street'])&&isset($_POST['barangay'])&&isset($_POST['city'])&&isset($_POST['dtiPermitNo'])&&isset($_POST['mayorPermitNo'])&&isset($_POST['firstName'])&&isset($_POST['lastName'])&&isset($_POST['middleName'])&&isset($_POST['contactNumber'])&&isset($_POST['email'])&&isset($_POST['password'])&&isset($_POST['confirmPassword']))
{
$options = ['cost' => 11, 'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),];
$pawnshopName = mysqli_real_escape_string($connection, $_POST['pawnshopName']);
$street = mysqli_real_escape_string($connection, $_POST['street']);
$barangay = mysqli_real_escape_string($connection, $_POST['barangay']);
$city = mysqli_real_escape_string($connection, $_POST['city']);
$dtiPermitNo = mysqli_real_escape_string($connection, $_POST['dtiPermitNo']);
$mayorPermitNo = mysqli_real_escape_string($connection, $_POST['mayorPermitNo']);
$firstName = mysqli_real_escape_string($connection, $_POST['firstName']);
$lastName = mysqli_real_escape_string($connection, $_POST['lastName']);
$middleName = mysqli_real_escape_string($connection, $_POST['middleName']);
$contactNumber = mysqli_real_escape_string($connection, $_POST['contactNumber']);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password = mysqli_real_escape_string($connection, password_hash($_POST['password'], PASSWORD_BCRYPT, $options));
$confirmPassword = mysqli_real_escape_string($connection, $_POST['confirmPassword']);
if(password_verify($confirmPassword,$password))
{
echo 'Password Match';
}else
{
echo 'Password mismatch';
}
$sql = "INSERT INTO pawnshop ".
"(Pawnshop_ID, Pawnshop_Name, Street, Barangay, City, DTI_Permit_No, Mayor_Permit_No, Firstname, Middlename, Lastname, Contact_Number, Email_Address, Password) ".
"VALUES ".
"('','".$pawnshopName."', '".$street."', '".$barangay."', '".$city."', '".$dtiPermitNo."', '".$mayorPermitNo."', '".$firstName."', '".$lastName."', '".$middleName."', '".$contactNumber."', '".$email."', '".$password."' )";
mysqli_query($connection, $sql);
mysqli_close($connection);
}
?>
No, you must use prepare method. Then on every place where you want to add a value place a ?. Than you must use the bind_param method. Finally, you can execute it and get the results whit get_results. An example:
$stmt = $connection->prepare("INSERT INTO Customers (CustomerName, Address, CityID) VALUES (?, ?, ?)");
$stmt->bindParam('ssi', $name, $address, $cityId);
$stmt->execute();
$results = $stmt->get_results();
The 'ssi' are corresponding variable the types of the attributes.
i are integers
d are doubles
s are strings
b is a blob and will be sent in packets
My resources are: w3schools and php.net

Can't get PHP rest server post method to update database

I am creating an android app with a php Rest server with firebird database. I can get information from the database via json with php server but I can't update anything. Here is my code.
public function update_user_info (){
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$home = $_POST['home'];
$cell = $_POST['cell'];
$birthdate = $_POST['birthdate'];
$weekly = $_POST['weekly'];
$email = $_POST['email'];
$users_id = $_POST[users_id];
$last_active = date("m/d/Y", time());
$last_act_time = date("h:i:s", time());
$acct_email = strtolower($email);
//make email all lowercase
horse_connect();
$query = ibase_prepare("UPDATE USERS SET FIRST_NAME = ?,
LAST_NAME = ?, ADDRESS = ?, CITY = ?,
STATE = ?, ZIP = ?, HOME_PHONE = ?, CELL_PHONE = ?,
BIRTHDATE = ?, HTML_EMAIL = ?,
LAST_ACTIVE = ?,
LAST_ACT_TIME = ?, EMAIL_NEWS = ?, EMAIL_LIVE_SCORES = ?
WHERE USERS_ID = ?");
$result = ibase_execute($query, $fname, $lname,
$address, $city, $state, $zip,
$home, $cell, $birthdate,
$acct_email, $last_active, $last_act_time,
$weekly, $live, $users_id);
//$final_array = array('user id' => $fname);
if($Result)
$json = array("status" => 1);
else
$json = array("status" =>0);
echo json_encode($json);
} //end: update_user_info
I am using Advanced rest client for testing.
Try using ibase_commit after execute. If possible try to use PDO when working with database.
Thanks everyone but I found the Problem. HTML_EMAIL should be ACCT_EMAIL. HTML_EMAIL is a bit field, true or false. ACCT_EMAIL is a string

mysqli insert statement problems

am getting the following error from my code:
Binding parameters failed: (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 '? (Name, Address, Location, Phone, Email, Time, Website, Photo1, Rating, Date_Pu' at line 1
Can anyone help me out please? Here is my code:
include("mysqli.php");
$search_tbl = mysql_query("SELECT * from listing_title where listing_title_ID = '$main_id'");
$tbl_name = $search_tbl['tbl_name'];
$stmt = $db->stmt_init();
global $tbl_name;
if($stmt->prepare("INSERT INTO ? (Name, Address, Location, Phone, Email, Time, Website, Photo1, Rating, Date_Published, categories_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"))
{
$stmt->bind_param('sssssssssisi',$tbl_name,$title,$address,$location,$phone,$email,$time,$website,$name,$rating,$date,$sub_cat);
$title = $_POST['name'];
$email = $_POST['email'];
$address = $_POST['address'];
$location = $_POST['location'];
$phone = $_POST['phone'];
$time = $_POST['time'];
$rating = $_POST['rating'];
$main = $_POST['main'];
$website = $_POST['website'];
$date = date('Y-m-d');
$stmt->execute();
$stmt->close();
}
else
{
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
}
else
{
echo 'a';
}
your script appears to be incomplete, but doing the best i could with what you had this is what you need. first of all, ditch whatever mysqli wrapper crap you are using. it is teaching you bad principles.
first file, your db info. call it config.php or whatever the hell you want. use require once instead of include. also, ditch the parenthesis around the requires these are not necessary at all, and use single quotes instead of double quotes. single quotes are treated as strings while double quotes php will search for variables inside, thus spending more resources from the cpu/cache.
config.php
$host = 'localhost';//your db host
$user = 'someuser'; //your db user
$pass = 'somepass'; //your db password
$name = 'somedb'; //the name of your db
$mysqli = new mysqli($host,$user,$pass,$name);
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit;
}else{
global $mysqli;//make your db connection available globally
}
Now for your script
script.php
require_once 'config.php';
//keep your post variables up here. you still need to santize and trim these
$title = $_POST['name'];
$email = $_POST['email'];
$address = $_POST['address'];
$location = $_POST['location'];
$phone = $_POST['phone'];
$time = $_POST['time'];
$rating = $_POST['rating'];
$main = $_POST['main'];
$website = $_POST['website'];
$date = date('Y-m-d');
global $mysqli;//fetch your db connection
$stmt = $mysqli->prepare("SELECT tbl_name from listing_title where listing_title_ID = ? ");
$stmt->bind_param('i',$main_id);
if($stmt->execute()) {
$stmt->bind_result($tbl_name);
$stmt->close();
$stmt = $mysqli->prepare("INSERT INTO ".$tbl_name."
(Name, Address, Location, Phone, Email, Time, Website, Photo1, Rating, Date_Published, categories_ID)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");
$stmt->bind_param('ssssssssisi',$title,$address,$location,$phone,$email,$time,$website,$name,$rating,$date,$sub_cat);
if($stmt->execute()) {
$stmt->close();
}else{
$stmt->close();
//catch the error
}
}else{
$stmt->close();
//throw an exception or handle the error here.
}
Please note, this still needs work. you need to sanitize and trim your variables. here's an example function. to include funcs, just add a require_once to the config.php file, and it will be included in any file you include config.php in.
example of this:
require_once 'funcs.php';
example sanitize function:
funcs.php
function security($value) {
if(is_array($value)) {
$value = array_map('security', $value);
} else {
if(!get_magic_quotes_gpc()) {
$value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
} else {
$value = htmlspecialchars(stripslashes($value), ENT_QUOTES, 'UTF-8');
}
$value = str_replace("\\", "\\\\", $value);
}
return $value;
}
to call the function
$title = security(trim($_POST['name']));
I leave the sanitizing to you. its a valuable exercise and you have an example that will sanitize anything, whether it be integers, arrays, objects, or strings.
you should only use trims on strings though. if you want to sanitize an entire array, just use the security function.
good luck.

Categories