PHP Warning: mysqli_stmt_bind_result() [duplicate] - php

This question already has an answer here:
INSERT - Number of bind variables doesn't match number of fields in prepared statement
(1 answer)
Closed 1 year ago.
I am new to programing not only with PHP but at all. Currently I am doing a siple project of mine to improve myself. I did it onec but now I want to make all my queries to work with prepared statements which is something new for me...
$create_stmt = mysqli_prepare($connection, "INSERT INTO `users`(`user_name`, `password`) VALUES (?,?)");
if(!$create_stmt){
echo 'error';
exit;
}
mysqli_stmt_bind_param($create_stmt, 'ss',$username,$password);
mysqli_stmt_execute($create_stmt);
mysqli_stmt_bind_result($create_stmt, $new_uname, $new_unamepass);
mysqli_stmt_fetch($create_stmt);
So here is the deal. I am having this kind of an error:
Warning: mysqli_stmt_bind_result(): Number of bind variables doesn't match number of fields in prepared statement.
Since I want to add 2 values to my 'users' table I am declaring 2 new variables $new_uname, $new_unamepass, but somehow this is not correct...
Also mysqli_stmt_fetch($create_stmt); is not TRUE but it should be if everything is OK (obviously its not ok..) So please if anyone can help me or give me some advice, it will be great!

TRY This:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO `users`(`user_name`, `password`) VALUES (?,?)");
$stmt->bind_param('ss', $user, $pass);
$user='username';
$pass = 'Password1234';
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();

Related

SELECT * FROM and mysqli_fetch_array using Prepared Statements

After a long time avoiding Prepared Statements I want to leave my comfort zone and update all my sites to mysqli, but I'm having a really hard time to achieve things that seem simple before...
Connection
$conn = mysqli_connect($host, $user, $password, $database)or die(mysqli_error($conn));
All my query's were built this way:
$id = 1;
$result = mysqli_query($conn, "SELECT * FROM users WHERE id = '$id'");
$row = mysqli_fetch_array($result);
Then I could print all needed fields:
Name: $row['name'];
Email: $row['email'];
Address: $row['address'];
City: $row['city'];
...
I've tried several ways to prepare, execute, bind and fetch the results in a simple way, or similar to what I was used to, but none of them work for me.
My statement is that bad? I mean, if I sanitize all itens before any Query or Insert my statement will remain insecure?
Can anyone show me a example of how can I use prepared statement but still be able to print my results individually, like: $row['name], $row['address'], $row['city']...
JUST TO UPDATE A FEW THINGS
This code works properly, my connection is ok and the $id is declared above my query (I've edited my question). My question is how can I "transform" this code into a mySQLi Prepared Statement and still be able to print results individually like $row['name'], $row['address']...
<?php
$mysqli = new mysqli("localhost", "username", "password", "db_name");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$id =1;
if ($stmt = $mysqli->prepare("SELECT name, email from users where id=?")) {
/* bind parameters for markers */
$stmt->bind_param("d", $id);
/* execute query */
$stmt->execute();
$stmt->bind_result($name, $email);
/* fetch value */
$stmt->fetch();
printf("%s has email %s", $name, $email);
/* close statement */
$stmt->close();
}
?>
May it help

MySQLi insert, successful database connection but not successfully inserted [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I'm attempting to insert some data into a table using mysqli functions.
My connection works fine using the following:
function connectDB(){
// configuration
$dbuser = "root";
$dbpass = "";
// Create connection
$con=mysqli_connect("localhost",$dbuser,$dbpass,"my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return false;
}else{
echo '<br />successfully connected<br />';
return $con;
}
}
But when I attempt to run my insert function I get nothing in the database.
function newUserInsertDB($name,$email,$password){
$con = connectDB();
// Prepare password
$password = hashEncrypt($password);
echo $password . "<br />";
// Perform queries
mysqli_query($con,"SELECT * FROM users");
mysqli_query($con,"INSERT INTO users (name,email,password,isActivated) VALUES ($name,$email,$password,0)");
// insert
mysqli_close($con);
}
I have been looking through the list of mysqli functions for the correct way to give errors but they all seem to be regarding the connection to the DB, not regarding success of an insert (and I can clearly see in my DB that it is not inserting.)
What would be the best way to debug? Which error handling shall I use for my insert?
I've tried using mysqli_sqlstate which gives a response of 42000 but I cannot see any syntax errors in my statement.
As mentioned in my comment, you would be better off using a prepared statement. For example...
$stmt = $con->prepare(
'INSERT INTO users (name, email, password, isActivated) VALUES (?, ?, ?, 0)');
$stmt->bind_param('sss', $name, $email, $password);
$stmt->execute();
Using this, you don't have to worry about escaping values or providing quotes for string types.
All in all, prepared statements are much easier and much safer than attempting to interpolate values into an SQL string.
I'd also advise you to pass the $con variable into your function instead of creating it within. For example...
function newUserInsertDB(mysqli $con, $name, $email, $password) {
// Prepare password
$password = hashEncrypt($password);
// functions that "echo" can cause unwanted side effects
//echo $password . "<br />";
// Perform queries
$stmt = $con->prepare(
'INSERT INTO users (name, email, password, isActivated) VALUES (?, ?, ?, 0)');
$stmt->bind_param('sss', $name, $email, $password);
return $stmt->execute(); // returns TRUE or FALSE based on the success of the query
}
The quotes are missing from the mysql statement from around the values. Also, you should escape the values before inserting them into the query. Do this way:
mysqli_query($con,"INSERT INTO users (name,email,password,isActivated) VALUES ('".
mysqli_real_escape_string($con,$name)."','".
mysqli_real_escape_string($con,$email)."','".
mysqli_real_escape_string($con,$password)."',0)");
Regards

Which is correct way to get last inserted id in mysqli prepared statements procedural style?

i am using mysqli prepared statement to insert record in the table like this
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
/* check connection */
if (!$link) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = mysqli_prepare($link, "INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $code, $language, $official, $percent);
$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;
/* execute prepared statement */
mysqli_stmt_execute($stmt);
if(mysqli_stmt_affected_rows($stmt) > 0){
//if insert is successful then get the insrted id.
}
/* close statement and connection */
mysqli_stmt_close($stmt);
/* close connection */
mysqli_close($link);
and would like to get the last inserted id , as the table has record_num field which is auto increment .
so my question is should i place connection name or the statement name inside the function.
i.e
1)
echo mysqli_insert_id($link);
Source: http://php.net/manual/en/mysqli.insert-id.php
2)
echo mysqli_stmt_insert_id($stmt);
Source: http://php.net/manual/en/mysqli-stmt.insert-id.php
which one is correct ?
which one will give me last insrted id by the $stmt ?
there are no other inserts are being done using the same stmt one the same page..*
Update:
according to the note from http://php.net/manual/en/mysqli-stmt.insert-id.php
I am doing only single insert so i guess i can use
mysqli_stmt_insert_id($stmt)
but while doing multiple inserts using prepared statements using
echo mysqli_insert_id($link);
is best practice.
You should use
mysqli_insert_id($link);
Because of this note on the PHP manual you referred us to
mysqli_stmt_insert_id
It should be noted that using mysqli_stmt->insert_id will not result in a unique ID being returned for each execution of a prepared insert statement. In practice, it appears that the first insertion ID is returned. If you are performing multiple inserts with the same prepared statement (one invocation of mysqli_stmt::prepare and multiple invocations of mysqli_stmt::execute() for a given statement), and need to keep the unique ID for each insert, use mysqli_connection->insert_id.
for procedural language you need to use below code,
mysqli_insert_id($link));
yes as you mention in 1 point.
Correct is 1) - link, as stated in documentation:
http://php.net/manual/en/mysqli.insert-id.php

How to prevent mysql injection 1=1 using msqli? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to prevent SQL Injection in PHP
In my website users can submit posts and delete their posts.
To delete a post, they follow the link /posts.php?deletid=X where X is the id of the post in database (for example: 1).
When clicked, it will run the following:
if(isset($_GET['deleteid'])) {
$deleteid = $_GET['deleteid'];
$sql = "DELETE from `posts` WHERE `id`=".mysql_real_escape_string($deleteid).";";
$query = mysql_query($sql);
header('Location: posts.php');
exit();
}
The problem is that it's vulnerable to the 1=1 SQL injection. If they type into the address bar /posts.php?deletid=1 OR 1=1;
it will delete all posts on database.
In this question: How can I prevent SQL injection in PHP?, I realized I need to use mysqli statements, and I tried to make it work but with no success..
Can someone please tell me exactly how I can prevent this with mysqli?
You need to have the value in quotes for mysql_real_escape_string to have any useful effect.
$sql = "DELETE from `posts` WHERE `id`='".mysql_real_escape_string($deleteid)."'";
Alternatively, instead of mysql_real_escape_string, which is intended for strings, try intval.
With MySQLi and prepared statements you do not need to worry about this, as a parameter cannot be replaced by 1 OR 1=1 (or if it is provided as the parameter value, then it’s interpreted as a string).
By using prepared statements, the mysql_* functions are on there way out and soon tobe deprecated, one should not be writing new code with these functions, refactor your code.
PDO
<?php
$db = new PDO("mysql:host=localhost;dbname=yourDB", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/*** prepare the SQL statement ***/
$query = $db->prepare("DELETE from `posts` WHERE `id`=:id;");
/*** bind the paramaters ***/
$query->bindParam(':id', $deleteid, PDO::PARAM_INT);
/*** execute ***/
$query->execute();
header('Location: posts.php');
exit();
?>
mysqli
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* create a prepared statement */
if ($stmt = $mysqli->prepare("DELETE from `posts` WHERE `id`=?")) {
/* bind parameters for markers */
$stmt->bind_param("i", $deleteid);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
header('Location: posts.php');
exit();
?>
One thing first: if you can, it would be wise not to use mysql_* but e.g. mysqli_* functions or PDO, since the first are outdated. There you can use placeholders (?) instead of string concats. You don't have to care for quoting yourself there.
The easiest option in your example code would be to run all numbers through integer parsing (use intval).
if(isset($_GET['deleteid'])) {
$deleteid = $_GET['deleteid'];
$sql = "DELETE from `posts` WHERE `id`=".intval($deleteid).";";
$query = mysql_query($sql);
header('Location: posts.php');
exit();
}

php prepared statement

It does not print the result. Dont know why. Everything is neatly commented
I get no error displays, no syntax blasphemes, it just does not print any result. However, I do know that the values are passed by the form to this processing php page, so the error is not in there. In the DB I have encrypted all fields except 'company'- Thus, I want to see if this will work by trying to fetch the results back.
// 1. Creating a new server connection
$db = new mysqli('localhost', 'root', '', 'developers');
if ($db->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
// 2, Creating statement object
$stmt = $db->stmt_init();
// 3, Creating a prepared statement
if($stmt->prepare("SELECT company FROM accesoweb WHERE username = AES_DECRYPT(?, 'salt')")) {
//4. Binding the variable to replace the ?
$stmt->bind_param('s', $username);
printf("Error: %d.\n", $stmt->errno);
// 5. Executing query
$stmt->execute();
// 6. Binding the result columns to variables
$stmt->bind_result($company);
// 7. Fetching the result of the query
while($stmt->fetch()) {
echo $company;
}
// 8. Closing the statement object
$stmt->close();
// 9. Closing the connection
$mysqli->close();
}
The inserting code that I just included in the MySQL was:
INSERT INTO accesoweb (company, username,email,password)
VALUES
('hola',
AES_ENCRYPT('maria','salt'),
AES_ENCRYPT('sumail','salt'),
AES_ENCRYPT('password',' salt')
);
So, that row above(actually, the "company" is what I am trying to recover through the PHP code
SELECT company FROM accesoweb WHERE username = AES_DECRYPT(?, 'salt')
Should be
SELECT company FROM accesoweb WHERE username = AES_ENCRYPT(?, 'salt')
OR
SELECT company FROM accesoweb WHERE AES_DECRYPT(username, 'salt') = ?

Categories