mysqli_stmt_execute() expects exactly 1 parameter, 0 given - php

I am trying to save data from an HTML form into database wordpress table: wp_testdb using Prepared Statements method, But I am getting error against line mysqli_stmt_execute();
Warning: mysqli_stmt_execute() expects exactly 1 parameter, 0 given in
Here is my code:
if(isset($_POST['BtnSubmit'])){
include_once 'dbConnection.php';
if($conn -> connect_error) {
die("connection failed:".$conn-> connect_error);
}
$date = $_POST['date'];
$select_bank = $_POST['select_bank'];
$entry_type = $_POST['entry_type'];
$income_cat = $_POST['income_cat'];
$amount = $_POST['amount'];
$sql = "INSERT INTO wp_testdb (data_one, data_two, data_three, data_four, data_five) VALUES (?, ?, ?, ?, ?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt,$sql)) {
echo "SQL Error !!";
} else {
mysqli_stmt_bind_param($stmt, "sssss", $date, $select_bank, $entry_type, $income_cat, $amount);
mysqli_stmt_execute();
}
}
dbConnection.php has below data:
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "wordpress";
$conn= mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
Any suggestions to resolve this?

I will recommend using the object oriented interface instead of the procedural. Both will work - however, all the procedural functions require the connection or statement object to be the first parameter.
As per the documentation, you need to pass the statement-object, in your case $stmt, as a parameter.
mysqli_stmt_execute($stmt);
This function returns a boolean, which you can check if the query was successful or not.
if (!mysqli_stmt_prepare($stmt,$sql)) {
echo "SQL Error !!";
error_log(mysqli_error($conn));
} else {
mysqli_stmt_bind_param($stmt, "sssss", $date, $select_bank, $entry_type, $income_cat, $amount);
if (mysqli_stmt_execute($stmt)) {
// Query succeeded!
// Do something
} else {
// Query failed. Log it, and do something?
error_log(mysqli_stmt_error($stmt));
}
}

Related

No data supplied for parameters in prepared statement - error php MySQLi [duplicate]

This question already has an answer here:
"No data supplied for parameters in prepared statement"
(1 answer)
Closed 1 year ago.
i'm very new to php. So, I tried to make a simple form to order sandwiches, but when I click the submit button i get this error "No data supplied for parameters in prepared statement".
Btw, I copied most of the code from a YouTube video, and I don't know what some parts of the code actually do.
that's my code:
<?php
if (isset($_POST['submit'])) {
if (isset($_POST['nombre']) && isset($_POST['apellido']) &&
isset($_POST['bocadillo']) && isset($_POST['extra']) &&
isset($_POST['comentario']) && isset($_POST['comentario'])) {
$nombre = $_POST['nombre'];
$apellido = $_POST['apellido'];
$bocadillo = $_POST['bocadillo'];
$extra = $_POST['extra'];
$comentario = $_POST['comentario'];
$host = "localhost";
$dbUsername = "------";
$dbpassword = "------";
$dbName = "------";
$conn = new mysqli($host, $dbUsername, $dbpassword, $dbName);
if ($conn->connect_error) {
die('Could not connect to the database.');
}
else {
$Select = "SELECT extra FROM pedidos WHERE extra = ? LIMIT 1";
$Insert = "INSERT INTO pedidos(nombre, apellido, bocadillo, extra, comentario) values(?, ?, ?, ?, ?)";
$stmt = $conn->prepare($Select);
$stmt->execute();
$stmt->bind_result($resultemail);
$stmt->store_result();
$stmt->fetch();
$rnum = $stmt->num_rows;
if ($rnum == 0) {
$stmt->close();
$stmt = $conn->prepare($Insert);
if ($stmt->execute()) {
echo "New record inserted sucessfully.";
}
else {
echo $stmt->error;
}
}
else {
echo "Someone already registers using this email.";
}
$stmt->close();
$conn->close();
}
}
else {
echo "All field are required.";
die();
}
}
else {
echo "Submit button is not set";
}
?>
You're missing the bind_param statements for both queries
$Select = "SELECT extra FROM pedidos WHERE extra = ? LIMIT 1";
$stmt = $conn->prepare($Select);
$stmt->bind_param("s", $extra);
$stmt->execute();
and then in the insert
$Insert = "INSERT INTO pedidos(nombre, apellido, bocadillo, extra, comentario) values(?, ?, ?, ?, ?)";
$stmt = $conn->prepare($Select);
$stmt->bind_param("sssss", $nombre, $apellido, $bocadillo, $extra, $comentario);
$stmt->execute();
https://www.w3schools.com/php/php_mysql_prepared_statements.asp

Warning: mysqli_stmt_init() expects parameter 1 to be mysqli, null given [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
I'm making a chat feature for a site and am not good with PHP:
<?php
if (isset($_POST['send'])) {
require 'database.php';
$input = $_POST['input'];
} else {
$sql = "INSERT INTO chatsys (chat) VALUES (?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("index.html?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_param($stmt, "sss", $input);
mysqli_stmt_execute($stmt);
header("index.html?request=success");
exit();
}
}
{
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
And database code:
<?php
$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "chatsys";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
?>
This results in:
Notice: Undefined variable: conn in C:\Users\John Doe\Desktop\server\htdocs\php\message\chat.php on line 11
Warning: mysqli_stmt_init() expects parameter 1 to be mysqli, null given in C:\Users\John Doe\Desktop\server\htdocs\php\message\chat.php on line 11
Warning: mysqli_stmt_prepare() expects parameter 1 to be mysqli_stmt, null given in C:\Users\john doe\Desktop\server\htdocs\php\message\chat.php on line 12
What have I done wrong?
First of all, don't blame PHP because it is a powerful and easy to use server side language, try to get close and you will love it.
Second you have unneccessary if else, and also passing extra parameters to bind param, while you just have only one to pass.
<?php
if (isset($_POST['send'])) {
require 'database.php';
$input = $_POST['input'];
$sql = "INSERT INTO chatsys (chat) VALUES (?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("index.html?error=sqlerror");
exit();
}
//No need to else here because if error happens you get back and exit.
mysqli_stmt_bind_param($stmt, "s", $input);
mysqli_stmt_execute($stmt);
header("index.html?request=success");
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
You are overcomplicating your code. You do not need all these braces or if statements. You do not need to check the return value of mysqli calls if you enable error reporting.
<?php
// If value was posted to the server
if (isset($_POST['send'])) {
// include mysqli connection
require 'database.php';
// perform prepared statement. (prepare/bind/execute)
$stmt = $conn->prepare("INSERT INTO chatsys (chat) VALUES (?)");
$stmt->bind_param("sss", $_POST['input']);
$stmt->execute();
// redirect on success
header("index.html?request=success");
exit();
}
and your connection file:
<?php
$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "chatsys";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
$conn->set_charset('utf8mb4'); // always set the charset

PHP query wont insert to database

The below query wont insert to database, I had tried this query on my database so I am quite sure that the query is working. I also added the dbcon.php below.
<?php
require '../api/dbcon.php';
$stmt=$conn->prepare("INSERT INTO joborder (AirCondition,
CarpentryMasonry,
ElectricalWorks,
Plumbing,
Welding,
Campus,
priorityId,
RequestorName,
UserJobDescription,
SerialCode
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" );
$stmt->bind_param('ssssssssss',
$airConditioning,
$masonryCarpentry,
$electrical,
$plumbing,
$welding,
$campus,
$priority,
$requester,
$userJobDescription,
$serialCode);
$airConditioning = "check";
$masonryCarpentry = "check";
$electrical = "check";
$plumbing = "check";
$welding = "check";
$campus = 'NA';
$priority = '1';
$requester = "m";
$userJobDescription ="test";
//create serial code
$serialCode= "na12321";
?>
dbcon.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbtable = "table";
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbtable);
if(!$conn ){
die('Could not connect: ' . mysqli_error());
}
?>
you're using a bad error reporting mode, and thus need to meticulously check for errors everywhere, but you're not.
on not-dbcon.php on line 4 you're not checking that $conn->prepare succeeded, do that, it returns bool(false) if there was an error. on line 16 you're not checking that $stmt->bind_param succeeded, do that, it returns bool(false) if there was an error. or better yet, don't do that, just convert return-value-error-reporting into exception-error-reporting, by running $conn->report_mode = MYSQLI_REPORT_ALL; immediately after creating the object.
... and most importantly, seems you forgot to run $stmt->execute(), which actually executes the query, which obviously explains why you're not inserting anything.
<?php
$servername = "localhost";
$username = "root";
$password = "123456";
$database = "inventory";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
$stat = $conn->prepare("INSERT INTO salary (name, salary, job) values (?, ?, ?)");
$name = 'test';
$salary = '21123';
$job = 'demo';
$stat->bind_param($name,$salary, $job );
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO salary (name, salary, job) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "Johnqqq";
$lastname = "123123";
$email = "sdadsad";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>

Problems with my first prepared MySQLi

Following a question earlier about sanitising a string, I'm now attempting to use the principles seen at How can I prevent SQL injection in PHP?
$connection = mysqli_connect('localhost', 'user', 'xxxxx');
$database = mysqli_select_db($connection, 'xxxxx');
$param1 = $_GET['q'];
//prepared mysqli statement
$stmt = mysqli_stmt_init($connection);
$stmt = $connection->prepare('SELECT * FROM CONTACTS WHERE SURNAME = ?');
$stmt->bind_param('s', $param1); // 's' specifies the variable type => 'string'
$stmt->execute();
$result = $stmt->get_result();
$num_rows = mysqli_num_rows($result);
echo "Records Found:".$num_rows."<br/><br/><hr/>";
while ($row = $result->fetch_assoc()) {
echo $result['COMPANY']." ".$result['FORENAME']." ".$result['SURNAME'];
}
However, although $connection and $database are both processing correctly, I'm getting the following error:
Fatal error: Call to undefined method mysqli_stmt::get_result() in
/my_first_mysqli.php on line xxxx
Am I not getting the syntax correct or does it have more to do with the php version 5.2.0 I'm rocking. (Yes, I'm upgrading code before upgrading server).
If it's the latter, is there a simpler MySQLi method I can use that will work before I upgrade the php version?
EDIT
I've updated this now which is a bit cleaner:
$servername = "localhost"; $username = "xxxx"; $password = "xxxx"; $dbname = "xxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$param1 = $_GET['q'];
$stmt = mysqli_prepare($conn, "SELECT CONTACTID, COMPANY, FORENAME, SURNAME FROM CONTACTS WHERE SURNAME = ?");
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $param1);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $CONTACTID, $COMPANY, $FORENAME, $SURNAME);
/* fetch value */
mysqli_stmt_fetch($stmt);
$num_rows = mysqli_num_rows($stmt);
echo "Records Found:".$num_rows."<br/><br/><hr/>";
/* close statement */
mysqli_stmt_close($stmt);
mysqli_close ($conn);
I'm obviously not getting a recordset result to loop through and don't know how to... The rest appears to work without throwing an error.
Thanks for all the contributions. I now have a working procedural solution that I thought I'd post for reference.
It's a bit cumbersome but it's fine and I believe it follows good modern practice.
$servername = "localhost"; $username = "xxxx"; $password = "xxxx"; $dbname = "xxxx";
$conn = new mysqli($servername, $username, $password, $dbname);// Create connection
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$param1 = $_GET['q'];
$stmt = mysqli_prepare($conn, "SELECT CONTACTID, COMPANY, FORENAME, SURNAME FROM CONTACTS WHERE SURNAME = ?");
mysqli_stmt_bind_param($stmt, "s", $param1);// bind parameters for markers
mysqli_stmt_execute($stmt);// execute query
mysqli_stmt_bind_result($stmt, $CONTACTID, $COMPANY, $FORENAME, $SURNAME);// bind result variables
// fetch values
while (mysqli_stmt_fetch($stmt)) {
echo $CONTACTID."<br>";
echo $COMPANY."<br>";
echo $FORENAME."<br>";
echo $SURNAME."<br>";
echo "<hr/>";
}
mysqli_stmt_close($stmt);// close statement
mysqli_close ($conn);
Feedback welcome if you can see any improvements.

Prepared statements during connection database

I am trying to make my website protected from sql injections. So I decided to change my code and replace it with prepared statements. I think I made a minor misstake in the code below.
<?php
session_start();
$host= 'localhost';
$user='root';
$pass='';
$db='gameforum';
$conn= mysqli_connect($host, $user, $pass, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$username = $_POST['username'];
$password = $_POST['password'];
$rpassword = $_POST['rpassword'];
$email = $_POST['email'];
if ($password!==$rpassword) {
$_SESSION['err']="Passwords did not match, please try again!";
header("Location: index.php");
$conn->close();
}
else {
$stmt = $conn->prepare("INSERT INTO users (username, password, rpassword, email) VALUES (?, ?, ?, ?)");
if(!$stmt){
echo "false";
}else {
$stmt->bind_param("ssss", $username, $password, $rpassword, $email);
if ($stmt->execute === TRUE) {
$redirectUrl = 'index.php';
$_SESSION['registrationsuccessful']="Your account was successfully created! You may now log in to your account.";
header("Location: index.php");
}else{
$_SESSION['alreadyexists']="Username or email already exists!";
header("Location: index.php");
$stmt->close();
$conn->close();
}
$stmt->close();
$conn->close();
}
}
The problem I am facing now is that I get the message "user already exists" when I try to create an account that do not actually exist. Thanks!
You have already executed the execute statement. Remove one of them. Alternatively check for success on only one of the execute statement
I believe the reason for the problem was the second usage of $stmt->execute() - but a few other modifications could be made to the code.
Create the db connection IF the initial logic if ( $password!==$rpassword ) test succeeds ~ seems pointless otherwise. I would use one session variable for this rather than 3 - it makes it easier to check the values later on other pages perhaps.
Assign the result of the first $stmt->execute() to a variable and use that vaiable in further logic tests if needed.
As for error messages - it is fine ( and indeed preferable ) to display verbose error messages for development but never in production - hence removed $conn->connect_error.
One other thing, mixing of procedural and object orientated code is probably not considered good practise - better to stick to one or other ( OO is easier I think )
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$rpassword = $_POST['rpassword'];
$email = $_POST['email'];
$_SESSION['registration_status']="";
if ( $password!==$rpassword ) {
$_SESSION['registration_status']="Passwords did not match, please try again!";
exit( header( "Location: index.php" ) );
} else {
$host= 'localhost';
$user='root';
$pass='';
$db='gameforum';
$conn= mysqli_connect($host, $user, $pass, $db);
if( $conn->connect_error ) die( "Connection failed" );
$stmt = $conn->prepare("INSERT INTO users (`username`, `password`, `rpassword`, `email`) VALUES (?, ?, ?, ?)");
if( $stmt ){
$stmt->bind_param("ssss", $username, $password, $rpassword, $email);
$result = $stmt->execute();
/* use the return value from stmt->execute() */
$_SESSION['registration_status'] = $result ? "Your account was successfully created! You may now log in to your account." : "Username or email already exists!";
$stmt->close();
}
$conn->close();
exit( header( "Location: index.php" ) );
}
}
?>
You can try this,
<?php
// if session not start, start now
!session_id() ? session_start() : null;
$mysql_server = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_db = "gameforum";
// connect db connection
$conn = new mysqli($mysql_server, $mysql_user, $mysql_password, $mysql_db);
// chck if connection has error
if ($conn->connect_errno) {
printf("Connection failed: %s \n", $conn->connect_error);
exit();
}
// db encoding
$conn->set_charset("utf8");
// when POST happen
if (isset($_POST) && !empty($_POST)) {
// convert POST array key as PHP variable
extract($_POST);
// if password matched with confirm password
if ($password === $rpassword) {
// create insert query with prepare
$stmt = $conn->prepare("INSERT INTO users (username, password, rpassword, email) VALUES (?, ?, ?, ?)");
// if prepare fine, there is no query or mysql error
if ($stmt) {
// bind real values
$stmt->bind_param("ssss", $username, $password, $rpassword, $email);
// if query executed
if ($stmt->execute()) {
// success message & redirect
$_SESSION['registrationsuccessful'] = "Your account was successfully created! You may now log in to your account.";
header("Location: index.php");
exit();
} else {
// query error & redirect
$_SESSION['alreadyexists'] = "There was an error or Username/Email already exists!";
header("Location: index.php");
exit();
}
}
} else {
// password matched failed
$_SESSION['err'] = "Passwords did not match, please try again!";
header("Location: index.php");
exit();
}
}
I am not closing connection because, PHP will close all open files and connections at the end of the script.

Categories