How to bind column = value to a PDO statement [duplicate] - php

This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 7 years ago.
I have a Query like this in my PDO statement:
SELECT * FROM table WHERE ? = ? ORDER BY id DESC
I wanted to bind column name to first ? and the value to second ? (column = value)
I tried many things such as below, but they all fail or return empty array (when there should be result)
This returns empty array
$query = "SELECT * FROM table WHERE ? = ? ORDER BY id DESC"
$db->prepare($query);
$stmt->bindValue(1, $column, PDO::PARAM_STR);
$stmt->bindValue(2, $value, PDO::PARAM_STR);
and this one displays an error
$query = "SELECT * FROM table WHERE column = :value ORDER BY id DESC"
$db->prepare($query);
$stmt->bindColumn('column', $column);
$stmt->bindValue(':value', $value, PDO::PARAM_STR);
Column is variable, so i had to bind it and can't put it in query directly.
What am I doing wrong here? I tried many things but no luck...
Please note that I know how to bind values if column is static, my issue is when column is also variable like above.

It should be bindParam, but you can execute it with an array inside too that's the way I do it:
$query = $db->prepare( 'SELECT * FROM table WHERE column=\':value\' ORDER BY id DESC' );
$query->execute(array(
':value' => $value
));

Related

MySQL LIKE operator in PHP [duplicate]

This question already has an answer here:
Correct way to use LIKE '%{$var}%' with prepared statements?
(1 answer)
Closed 1 year ago.
I should execute this method,
but I don't know how pass %research value as LIKE parameter in bind:
public function researchElements($research) {
$stmt = $this->db->prepare("SELECT * FROM product WHERE product_name LIKE "'%?%'"");
$stmt->bind_param('s', $research);
$stmt->execute();
$result = $stmt->get_result();
$result = $result->fetch_all(MYSQLI_ASSOC);
return $result;
}
At least you can use in your query CONCAT function like next:
$stmt = $this->db->prepare("SELECT * FROM product WHERE product_name LIKE CONCAT('%',?,'%')");
Note: if $research variable gets value '', then query will return all rows from the table.

PHP PDO mysql query to work with both column = '$var' and column IS NULL [duplicate]

This question already has an answer here:
Write a prepared statement with nullable values in conditions
(1 answer)
Closed 2 years ago.
I have a quite long mysql query, selecting data according to status field. I'm calling it for different statuses and it works well, but I have a scenario when I should get all records where status is null ONLY. Is there a way to do this without having to write 2 different sql queries?
Looks like I can't insert 'IS NULL' or '=' without it being rendered as a string.
I want to achieve this:
$sql = "SELECT name, surname FROM ...
...
WHERE status ?;";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($status === 'undefined' ? 'IS NULL' : " = '$status'"));
After all, here's what I did:
$sql = "SELECT name, surname FROM ...
...
WHERE status <=> ?;";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($status === 'unfinished' ? null : $status));
Using parameterised queries, as indicated, is a safer way of introducing user input into your SQL statements. However, it has the effect of treating all input as a parameter, and therefore will surroung any string literals with quotes - giving rise to the problem you have.
To deal with this issue, why not just modify the logic of the code:
$sql = "SELECT name, surname FROM ...
...
WHERE status";
if ($status === 'undefined') {
$sql .= " IS NULL";
$stmt = $pdo->prepare($sql);
$stmt->execute();
} else {
$sql .= " = ?"
$stmt = $pdo->prepare($sql);
$stmt->execute(array($status));
}
Edit
Updated to move the execution into the relevant part of the if statement becuase the parameters must not be specified if there is no placeholder in the SQL statement.

Select from table, where column is foreign key in PHP [duplicate]

This question already has answers here:
mysqli prepared statement num_rows returns 0 while query returns greater than 0 [duplicate]
(3 answers)
Closed 3 years ago.
Even though there is an entry in the database, with this query, I always get 0 entries back
$sql = "SELECT * FROM saved_food WHERE user_id = ? AND favorite_food LIKE ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("is", $me['id'], $favFood);
$stmt->execute();
var_dump($stmt->num_rows);
the dump is 0
The user_id colum is a foreign key, and shows to the id of the table "user".
I can't see the error here.
Is there a special method for foreignkey values?
I got the error... facepalm
I forgot to call ->get_result();
$sql = "SELECT * FROM saved_food WHERE user_id = ? AND favorite_food LIKE ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("is", $me['id'], $favFood);
$stmt->execute();
$result = $stmt->get_result();
var_dump($result->num_rows);

SQL prepared statement returns no result (empty result) [duplicate]

This question already has answers here:
How do I create a PDO parameterized query with a LIKE statement?
(9 answers)
PDO Parameterized Query - Reuse named placeholders?
(5 answers)
Closed 4 years ago.
Following prepared statement returns no result if I try like search('samsung').
public function search($searchFor) {
try{
//connect to db
$pdo = $this->_db->connect();
//set up SQL and bind parameters
$sql = "select * from item where itemName like '%:searchfor%' or description like '%:searchfor%'";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':searchfor', $searchFor, PDO::PARAM_STR);
//execute SQL
$rows = $this->_db->executeSQL($stmt);
return $rows;
}
catch (PDOException $e)
{
throw $e;
}
}
$rows return an empty array. But if I try
select * from item where itemName like '%samsung%' or description like '%samsung%;
it returns a matched item and works as expected.
I found
$sql = "select * from item where itemName like :searchfor or description like :searchfor";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(":searchfor", "%$searchFor%");
works. I had to use bindValue instead. This was a totally different issue in that the SQL was correct but I used bindParam instead of bindValue (which is the correct method), hence this is not a duplicate.
did you try to use a placeholder for the whole part of the statement?
$sql = "select * from item where itemName like :searchfor or description like :searchfor";
$stmt = $pdo->prepare($sql);
$search_string = "'%" . $searchFor . "'%";
$stmt->bindParam(':searchfor', $search_string, PDO::PARAM_STR);
Altenatively without named params:
$sql = "select * from item where itemName like ? or description like ?";
$stmt = $pdo->prepare($sql);
$search_string = "'%" . $searchFor . "'%";
$stmt->bindParam('ss', $search_string, $search_string);
As far as I remember the manual, like need to thave the whole string in the variable, not only the content to look after.
Aug
The prepared statement's placeholder tells php to treat the specific value that is passed into the placeholder, as a string. Instead of this:
$sql = "select * from item where itemName like '%:searchfor%' or
description like '%:searchfor%'";
Do this:
$sql = "select * from item where itemName like :searchfor or
description like :searchfor";
Then bind whole values into the placeholders:
$stmt->bindParam(':searchfor', '%yourkeyword%', PDO::PARAM_STR);

PHP MySQLi prepared statements - SELECT

I have problems with my SELECT syntax.
Code:
$stmt = $this->con->prepare("SELECT ? FROM `shop_items` WHERE `id` = ?");
$stmt->bind_param("si", $what, $itemsId);
$stmt->execute();
$stmt->bind_result($res);
$stmt->fetch();
echo $res;
When I want to select "name", it echo "name" instead of result from DB. How to solve it?
Placeholder ? can be used in prepared statement only in substitution of values, not for field names, table names or statement.
You're trying to use it for a field name.
You can build up your query string
$stmt = $this->con->prepare("SELECT " . $what . " FROM `shop_items` WHERE `id` = ?");
but you must be sure you can trust what's inside $what in order to avoid sql injection.
Otherwise you may get all fields
$stmt = $this->con->prepare("SELECT * FROM `shop_items` WHERE `id` = ?");
Fetch results in an associative array (see http://it1.php.net/manual/en/mysqli-result.fetch-assoc.php) and then get only the field value pointed by $what
It looks like you use question mark (?) after SELECT. It should be * symbol where you can select it all from 'shop_items'. You can try again with that.

Categories