Mysqli fetch array not working - php

I am in the process of making my mysql querys prepared in an attempt to increase security, however I have a problem when I attempt to fetch the results of a prepared statement. I have researched for the cause of the error, however many of the examples use complex code and I do not know how to apply the solution to my code.
The error
mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in
My code
$query = "SELECT cid, user1, user2 FROM convotable
WHERE user1 = ? OR user2 = ? ORDER BY createtime ASC";
$stmt = mysqli_prepare($dbc, $query);
if ($stmt) {
mysqli_stmt_bind_param($stmt, "ii", $user1, $user2);
mysqli_stmt_execute($stmt);
while($row = mysqli_fetch_array($stmt)){
$cid = $row['cid'];
$user1 = $row['user1'];
$user2 = $row['user2'];
}
}

Try this way and set variable that you bind in mysqli_stmt_bind_param()
$query = "SELECT cid, user1, user2 FROM convotable
WHERE user1 = ? OR user2 = ? ORDER BY createtime ASC";
$stmt = mysqli_prepare($dbc, $query);
if ($stmt)
{
mysqli_stmt_bind_param($stmt, "ii", $user1, $user2);
$user1=1; //set variable
$user2=2; //set variable
mysqli_stmt_execute($stmt);
while($row = mysqli_fetch_array($stmt))
{
$cid = $row['cid'];
$user1 = $row['user1'];
$user2 = $row['user2'];
}
}
See for more :http://php.net/manual/en/mysqli-stmt.execute.php

It may not be what you need, but I find using PDO (alternative to mysqli) alot more easy and clear:
<?php
$dsn = 'mysql:host=localhost;dbname=DBNAME;charset=utf8';
$user = 'user';
$pass = 'pass';
$db = new PDO($dsn, $user, $pass);
$user1 = '123';
$user2 = '234';
$query = "SELECT cid, user1, user2 FROM convotable
WHERE user1 = ? OR user2 = ? ORDER BY createtime ASC";
$stmt = $db->prepare($query);
$stmt->bindParam(1, $user1, PDO::PARAM_INT);
$stmt->bindParam(2, $user2, PDO::PARAM_INT);
if (!$stmt->execute()) {
echo 'something went wrong';
die;
}
print_r($stmt->fetchAll());

Related

Is it possible to parametarize query that has a concatenation variable?

As learning php and sql injections, I would like to parametize my queries for safe and secure website app. however, mine does not work I try to parametize my update and select my query but I didn't achieved the goal to make the program working.
The current output is throwing an error the ? is not found
As of now here is my code, am I missing something that does not work?
<?php
//connection
$connection = mysqli_connect("hostserver","username","");
$db = mysqli_select_db($connection, 'dbname');
if (isset($_POST['qrname'])) {
$qrid = $_POST['qrid'];
//Query No. 1
$qrQuery = "SELECT * FROM scratch_cards WHERE code='$qrid' ";
$qrQuery_run = mysqli_query($connection,$qrQuery);
//Query No. 2
$qrQuery2 = "UPDATE scratch_cards SET status = 'U' WHERE code='$qrid' ";
$qrQuery_run2 = mysqli_query($connection,$qrQuery2);
$qrQuery2->bind_param("s", $qrid);
$qrQuery2->execute();
while ($qrRow = mysqli_fetch_array($qrQuery_run)) {
$txtQrvalue = $qrRow['amount'];
$txtQrstatus = $qrRow['status'];
// QUERY TO UPDATE THE VALUE
// BIND AND PARAMETIZE MY QUERY
$qrQuery3 = $db->parepare("UPDATE shopusers SET ewallet = ewallet + " . (0+?) . " WHERE id = '?' ");
$qrQuery3->bind_param("ii", $txtQrvalue, $id);
$qrQuery3->execute();
//END
}
If I'm reading your question and code right, you can reduce this down to two queries using a JOIN instead, that way you can get rid of the SELECT statement. Use prepared statements for both.
I also specified your connection's charset to UTF-8 (which you should set for your PHP and HTML headers, and your database-tables too).
<?php
$connection = mysqli_connect("hostserver","username","");
$db = mysqli_select_db($connection, 'dbname');
$connection->set_charset("utf8");
if (isset($_POST['qrname'])) {
$qrid = $_POST['qrid'];
$sql = "UPDATE scratch_cards SET status = 'U' WHERE code=?";
$stmt = $connection->prepare($sql);
$stmt->bind_param("s", $qrid);
$stmt->execute();
$stmt->close();
$sql = "UPDATE shopusers su
INNER JOIN scratch_cards sc
ON sc.qrid = su.code
SET su.ewallet = su.ewallet + sc.amount,
sc.status = 'U'
WHERE sc.code = ?";
$stmt = $connection->prepare($sql);
$stmt->bind_param("s", $qrid);
$stmt->execute();
$stmt->close();
}
we have the foll syntax in PDO bind param, where i have put your update query as an example and it works perfectly fine. Try searching for named parameter binding
<?php
$user = 'root';
$pass = 'xxxx';
$DB = 'test';
$host = 'localhost';
$mysqlConnection = new \PDO('mysql:host='.$host.';dbname='.$DB, $user, $pass);
$mysqlConnection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$sql = 'update info set fname = fname + :fn where id = 1';
$stmt = $mysqlConnection->prepare($sql);
$stmt->bindValue(':fn', '100');
$stmt->execute();
echo $stmt->rowCount();
?>
Is this the query you wanted to run using mysqli bind params???
<?php
ini_set('display_errors', 1);
$user = 'root';
$pass = 'xxxx';
$DB = 'test';
$host = 'localhost';
$sql = 'update info set fname = fname + ? where id = 1';
$conn = new mysqli($host, $user, $pass, $DB);
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $val);
$val = 100;
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
exit;

PHP: if statement testing if DB value equals a number - if true execute multiple sql query

Hello, I am trying to make php code that executes multiple sql queries as long as a certain database value equals 1. If that value does not equal one, then redirect the page to oops.php.
Here is my code so far:
<?php
session_start();
$servername = "localhost";
$username = "myUser";
$password = "myPass";
$dbname = "cashball_accounts";
$cash_amount = $_SESSION['cash_amount'];
// Create connection
$userid = $_SESSION['id'];
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch the existing value of the cash_amount against that particular user here. You can use the SELECT cash_amount from users where userid = $userid
$_SESSION['cash_amount'] += $_POST['cashmade'];
$sql = "UPDATE users SET cashincheck = 0 WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $userid);
$result = $stmt->execute();
if($result)
{
echo "cashin complete!";
}
else
{
echo mysqli_error($conn);
session_start();
session_unset();
session_destroy();
}
$conn->close();
?>
So I want everything from the //Fetch comment to the if($result) to execute if the variable "cashincheck" is equal to 1 in the database.
For example:
if(SELECT cashincheck FROM users WHERE id = ? = 1) {
$_SESSION['cash_amount'] += $_POST['cashmade'];
$sql = "UPDATE users SET cashincheck = 0 WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $userid);
$result = $stmt->execute();
} else {
//redirect to oops.php
}
**/\ I know this wont work at all it's just an example /**
I also want to make several other if statements and update the database accordingly, meaning more sql queries and if statements will be needed,so how would I add more?
another example for a separate if statement:
if($_POST['cashmade'] < $_POST['type']) {
$sql = "UPDATE users SET moneymade = moneymade + $_POST['cashmade'] WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $userid);
$result = $stmt->execute();
} else {
$sql = "UPDATE users SET moneylost = moneylost + $_POST['type'] - $_POST['cashmade'] WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $userid);
$result = $stmt->execute();
}

Set a Value from a SQL table select statement to a local variable

I'm trying to take the CustomerID from the SQL select statement and then assign it to a $_SESSION variable i can use later on during the session.
MY CODE:
session_start();
$Username = $request->getParam('Username');
$PassW = $request->getParam('PassW');
$sql = "SELECT CustomerID FROM login WHERE Username= '$Username' AND PassW='$PassW' LIMIT 1";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(count($result) == 1){
$_SESSION['Username'] = $Username;
$_SESSION['CustomerID'] = '****CUSTOMER ID FROM TABLE****';
I'm new to this so any help is appreciated :)
Sovled it.
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
needed to be
$result = $stmt->fetchColumn();

mysqli prepare - only works when not a function?

That one always returns a false bool:
<?php
function check($username, $db_conx) {
$sql = 'SELECT User_ID FROM tbl_user WHERE Username=?';
$stmt = $db_conx->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$ret= $stmt->get_result();
$stmt->close();
$db_conx->close();
$ret = $ret->fetch_row();
return $ret;
}
$usr = "root";
$res = check($u,$db_conx);
echo var_dump($res);
echo $a[0];
?>
I don't get it, they are pretty equal - so what's the error?
That one returns what I expected:
<?php
$usr = 'root';
$sql = "SELECT User_ID FROM tbl_user WHERE Username=?";
$stmt = $db_conx->prepare($sql);
$stmt->bind_param('s', $usr);
$stmt->execute();
$ret = $stmt->get_result();
$stmt->close();
$db_conx->close();
$ret = $ret->fetch_row();
echo var_dump($ret);
echo $ret[0];
?>
I want to recycle it over and over again with the function, but it doesn't seem to work. Is it even possible to set & execute the parameters in a function or have I just made a stupid mistake?

MySQLi Prepared Statement Query Issue

I'm relatively new to MySQLi prepared statements, and running into an error. Take this code:
$user = 'admin';
$pass = 'admin';
if ($stmt = $mysqli->query("SELECT * FROM members WHERE username='$user' AND password='$pass'"))
{
echo $stmt->num_rows;
}
This will display "1", as it should.
This next piece of code though, returns "0":
$user = 'admin';
$pass = 'admin';
if ($stmt = $mysqli->prepare("SELECT * FROM members WHERE username=? AND password=?"))
{
$stmt->bind_param("ss", $user, $pass);
$stmt->execute();
echo $stmt->num_rows;
}
Any ideas why?
you need to call store_result() before you get the number of rows
$user = 'admin';
$pass = 'admin';
if ($stmt = $mysqli->prepare("SELECT * FROM members WHERE username=? AND password=?"))
{
$stmt->bind_param("ss", $user, $pass);
$stmt->execute();
$stmt->store_result(); // add this line
echo $stmt->num_rows;
}

Categories