PHP Procedural: error in the syntax using LIKE keyword [duplicate] - php

This question already has answers here:
You have an error in your SQL syntax error?
(2 answers)
Closed 12 days ago.
I'm experimenting with joining databases in php using prepared statements.
I got this error:
Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '? OR users.class LIKE ? OR users.email LIKE ?' at line 3 in C:\xampp\htdocs\Burza\includes\functions.inc.php:335
Stack trace: #0
#0 C:\xampp\htdocs\Burza\includes\functions.inc.php(335): mysqli_query(Object(mysqli), 'SELECT * FROM p...')
#1 C:\xampp\htdocs\Burza\buy.php(20): getProductsBySearch(Object(mysqli), '%summer%')
#2 {main}
thrown in C:\xampp\htdocs\Burza\includes\functions.inc.php
I think it's because of the LIKE keyword, but I don't know what to do about it.
All of the names of the tables and rows are correct
My code looks like this:
function getProductsBySearch($conn, $search){
$sql = "SELECT * FROM products
JOIN users ON products.userid = users.id
WHERE users.name LIKE ? OR users.surname LIKE ? OR users.class LIKE ? OR users.email LIKE ?;";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
header("location: ../index.php?error=stmtfailed");
exit();
}
$search = "%".$search."%";
mysqli_stmt_bind_param($stmt, "ssss", $search, $search, $search, $search);// s = string
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$result = mysqli_query($conn, $sql);
$products = mysqli_fetch_all($result, MYSQLI_ASSOC);
mysqli_stmt_close($stmt);
return $products;
}
Can somebody explain to me why it's happening and how to fix it?
I tried changing the * symbol to more specific part in my database - products.id and it didn't help. And I tried using '%".?."%' and it didn't work as well.

This is the problem:
$result = mysqli_query($conn, $sql);
mysqli_query() is used when your query has no query parameters.
If your query has parameters, then use only mysqli_prepare() and mysqli_stmt_execute().
I suggest the following sequence:
try {
$stmt = $conn->prepare($sql);
$search = "%$search%";
$stmt->bind_param("ssss", $search, $search, $search, $search);
$stmt->execute();
$result = $stmt->get_result();
$products = $result->fetch_all(MYSQLI_ASSOC);
catch (mysqli_sql_exception $e) {
error_log($e);
header("location: ../index.php?error=stmtfailed");
exit();
}

Related

MySQL SELECT query returning false when prepared

My file should get all users with this id (It's only one since id is unique in this table) and prepare a statement to execute later. When I execute it I get this error:
Fatal error: Uncaught Error: Call to a member function execute() on
boolean in C:\xampp\htdocs\Gamanware.ga\Admin\update.php:7 Stack
trace: #0 {main} thrown in
C:\xampp\htdocs\Gamanware.ga\Admin\update.php on line 7.
And I can't see anything wrong with it. The id is alright (I echo it out to be sure), Im not using reserved words and have made sure that it won't matter anyway, but I still get this error. I have been on several forums and many questions have not worked for me. I hope some of you can! My code:
<?php
require '../includes/login_system.dbh.php';
$id = $_GET['id'];
$sql = 'SELECT * FROM `users` WHERE `id`=:id';
$statement = $conn->prepare($sql);
$statement->execute([':id' => $id ]);
Try the code below and see if it helps
require '../includes/login_system.dbh.php';
$sql= "SELECT * FROM users WHERE id = :id";
$statement = $conn->prepare($sql);
$statement->bindParam(':id', $id, PDO::PARAM_INT);
$id = $_GET['id'];
$statement->execute();
You can also do an if else statement with your execute like so to see what it gives you.
require '../includes/login_system.dbh.php';
$sql= "SELECT * FROM users WHERE id = :id";
$statement = $conn->prepare($sql);
$statement->bindParam(':id', $id, PDO::PARAM_INT);
$id = $_GET['id'];
if ($statement->execute()) {
echo "Success";
} else {
echo "Failed";
}

MySQLI mysqli_store_result results with Malformed Packet error

I am in the process of converting some old MySQL code into MySQLI Prepared Statements and hit a snag:
If I run the same SQL code as prepared statement, I get a "Malformed Package" error. This happens even with extremely simple queries like "SELECT * FROM [TableName]".
I have the creation of the connection and setting of the Report level in a Seperate file altogether. So that code must be identicaly by definition.
As specific example, this code works:
$sql = "SELECT * FROM AngebotsDB";
$result = mysqli_query($link, $sql);
But this code:
$sql = "SELECT * FROM AngebotsDB";
// $result = mysqli_query($link, $sql);
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt,$sql);
mysqli_execute($stmt);
$resultReference = mysqli_store_result($link); //throws exception
$result = mysqli_fetch_array($resultReference);
ends in:
Fatal error: Uncaught exception 'mysqli_sql_exception' with message
'Malformed packet' in /home/cgroschupff/public_html/custom_code/DB
structure.php:16 Stack trace: #0 /home/cgroschupff/public_html/custom_code/DB structure.php(16):
mysqli_store_result(Object(mysqli)) #1 {main} thrown in
/home/cgroschupff/public_html/custom_code/DB structure.php on line 16
All I could really find is some old information of this happening when Connecting to the DB.
Note that the used MySQLi/PHP version is rather old (5.2.17?). So this could be a "long ago fixed" bug?
If you initialize a statement than you have to call other functions according to mysqli_stmt class so your code should be .
$sql = "SELECT * FROM AngebotsDB";
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt,$sql);
mysqli_stmt_execute($stmt);
$resultReference = mysqli_stmt_store_result($link);
Now if you try var_dump($resultReference) than return true or false .
if you want to show result with mysqli_fetch_array so you have to pass mysqli_result parameter so for this you have to use mysqli_stmt_get_result .
$sql = "SELECT * FROM AngebotsDB";
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt,$sql);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt) ;
$output = mysqli_fetch_array($result) ;
Now you can see var_dump($output) than you have result .

PHP prepared statement not working [duplicate]

This question already has answers here:
How do I escape reserved words used as column names? MySQL/Create Table
(4 answers)
Closed 2 years ago.
I am making a prepared statement in PHP and my code is fine until I add in 'id' and 'key' to my parameters. They are definitely in the table that I am requesting too. What is wrong? Thanks in advance!
ERROR: Call to a member function bind_param() on boolean
if($_POST['userx']){
echo '<div id="div2"><div id="font2">Dashboard</div>';
$queryA = "SELECT name,profo,password,id,key FROM collegestudents WHERE email = ?";
$stmt = $connection->prepare($queryA);
$stmt->bind_param('s',$_POST['userx']);
$stmt->bind_result($name1,$profo,$password1,$key,$id);
$stmt->execute();
$stmt->fetch();
$stmt->close();
Key is a reserved keyword in mysql.
It's a good habit to enclose field names and table names in backticks in queries but also to check for errors.
$queryA = "SELECT `name`,`profo`,`password`,`id`,`key` FROM `collegestudents` WHERE `email` = ?";
$stmt = $connection->prepare($queryA);
if ($stmt) {
$stmt->bind_param('s',$_POST['userx']);
...
}
else {
echo "MySQL ERROR: " . $connection->error;
}
$stmt = $connection->prepare($queryA);
returns boolean(false)
make sure your query is correct
you can do a simple check like this
$stmt = $connection->prepare($queryA);
if (!$stmt) {
echo "failed to run";
} else {
$stmt->bind_param('s',$_POST['userx']);
$stmt->bind_result($name1,$profo,$password1,$key,$id);
$stmt->execute();
$stmt->fetch();
}
Edit:
if you are using PDO you were doing it wrong it should be like this
$stmt = $conn->prepare("SELECT name,profo,password,id,key FROM
collegestudents WHERE email = :email");
$stmt->bindParam(':email', $email);
Change your database connection file with
<?php $con = new PDO('mysql:host=127.0.0.1;dbname=yourdatabasename;','username',''); ?>
Then change below line
$queryA = "SELECT name,profo,password,id,key FROM collegestudents WHERE email = ?";
$stmt = $connection->prepare($queryA);
$stmt->bind_param('s',$_POST['userx']);
$stmt->bind_result($name1,$profo,$password1,$key,$id);
$stmt->execute();
with
$queryA = "SELECT name,profo,password,id,key FROM collegestudents WHERE email = :v";
$stmt = $connection->prepare($queryA);
$stmt->execute( array('v' => $_POST['userx']) );

PDO order by throws error

I am confused.
This is working:
$sql = 'SELECT * FROM TABLE ORDER BY DATEOFUPLOAD DESC';
$stmt = $conn->prepare($sql);
$stmt->execute();
This is not:
$sql = 'SELECT * FROM TABLE ORDER BY DATEOFUPLOAD :orderbydateofupload';
$stmt = $conn->prepare($sql);
$stmt->bindValue(':orderbydateofupload', $orderbydateofupload, PDO::PARAM_STR);
$stmt->execute();
I have checked and set $orderbydateofupload by $orderbydateofupload='DESC', so it's definitely not null.
I get an error to the last line ($stmt->execute()):
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 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 ''DESC'' at line 1' in /home/gh6534/public_html/query.php:77 Stack trace: #0 /home/gh6534/public_html/query.php(77): PDOStatement->execute() #1 {main} thrown in /home/gh6534/public_html/query.php on line 77
I also tried to use the column as parameter:
$sort = 'DATEOFUPLOAD';
$sql = 'SELECT * FROM TABLE ORDER BY :sort :orderbydateofupload';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':sort', $sort);
$stmt->bindParam(':orderbydateofupload', $orderbydateofupload);
$stmt->execute();
This does not throw an exception, but all items are queried without any sorting. What's wrong?
Try this
$orderbydateofupload = 'ASC'; //Or DESC
if($orderbydateofupload == 'DESC')
$sql = 'SELECT * FROM TABLE ORDER BY DATEOFUPLOAD DESC';
else
$sql = 'SELECT * FROM TABLE'
You can't bind identifiers with PDO because prepared statements can be used only with data, but not with identifiers or syntax keywords.
So, you have to use whitelisting, as shown in the example I posted before
That's why in my own class I use identifier placeholder, which makes whole code into one line (when you need to set the order by field only):
$data = $db->getAll('SELECT * FROM TABLE ORDER BY ?n',$sort);
but with keywords whitelisting is the only choice:
$order = $db->whiteList($_GET['order'],array('ASC','DESC'),'ASC');
$data = $db->getAll("SELECT * FROM table ORDER BY ?n ?p", $sort, $order);

Warning: mysqli_num_rows(): supplied argument is not a valid MySQL result [duplicate]

This question already has answers here:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result [duplicate]
(6 answers)
Closed 9 years ago.
The code:
$stmt = mysqli_prepare($link, "SELECT * FROM adm_users WHERE users_username = ? AND users_password = ?");
mysqli_stmt_bind_param($stmt, 'ss', $user_adm_name, $user_adm_password);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_fetch($stmt);
$adm_check_log = mysqli_num_rows($stmt);
mysqli_stmt_close($stmt);
Return:
Warning: mysqli_num_rows(): supplied argument is not a valid MySQL
result
Why? Can someone explain for me?
You should check the return values of your functions!
(As a programmer do this in every situation when you encounter an error)
Seems that something is going wrong with the query. So change the code to something like:
$result = mysqli_query(...);
if(!$result) {
die(mysqli_error($link);
}
Do the same with all of the mysqli functions that you are using.
That simply means that the value for $stmt that is being passed in here:
$adm_check_log = mysqli_num_rows($stmt);
isn't of the correct type. Usually it indicates that you either didn't return anything from your query or there was an error with it.
Try outputting it to see what you get:
var_dump($stmt);
Replace what you have with this. What error is reported?
if($stmt = mysqli_prepare($link, "SELECT * FROM adm_users WHERE users_username = ? AND users_password = ?")) {
$stmt->bind_param("ss", $user_adm_name, $user_adm_password);
$stmt->execute();
printf("Error: %d.\n", $stmt->error);
$stmt->bind_result($foo);
$stmt->fetch();
var_dump($foo);
$stmt->close();
}

Categories