PDO Select form MYSQL db [duplicate] - php

This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 8 years ago.
There are many hints for this topic, I tried this: How to create a secure mysql prepared statement in php?
and many others, but nothing is working. If I want to select something from the database and query without parameters, it's ok. But if I want data for a column and table with parameters, it doesn't work, it returns empty array. Any hints?
There is my code:
function getDataByColumn($column, $table) {
try {
$connection = new PDO("mysql:dbname=vydap;charset=utf8;host=127.0.0.1", "...","...");
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$query = "SELECT ? FROM ?";
// $query = "SELECT :column FROM :table";
$stmt = $connection->prepare($query);
// $stmt->bindParam(':column', $column);
// $stmt->bindParam(':table', $table);
$stmt->bindParam(1, $column);
$stmt->bindParam(2, $table);
$stmt->execute();
$result = $stmt->fetchAll();
var_dump($result);
}

This is flat-out wrong:
$query = "SELECT ? FROM ?";
placeholders can represent only VALUES. You cannot use placeholders for field/table/db names - those aren't values - they're idenfifiers.
SELECT foo FROM bar WHERE foo = 'baz'
a b c d e f g h
a- sql keyword
b- field identifier
c- sql keyword
d- table identifier
e- sql keyword
f- field identifier
g- operator
h- value
Of that entire query, only the h portion is a candidate for using a placeholder.

You can't use PDO placeholders on table or columns names. Those are only used for values:
$query = "SELECT * FROM yourTable WHERE someCol = ?";
$stmt->bindParam(1, $value);

Related

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.

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);

How to use IN dynamically with mysqli prepare statement [duplicate]

This question already has answers here:
PDO binding values for MySQL IN statement [duplicate]
(8 answers)
PreparedStatement IN clause alternatives?
(33 answers)
Closed 7 years ago.
I was trying to use IN with mysqli prepare statment
$user_in = "'28','22'";
$stmt = $this->connection->prepare("SELECT `id` FROM `$this->table_name` WHERE `user_id` IN (?) ");
if($stmt){
$stmt->bind_param('s',$user_in);
if($stmt->execute()){
$result = $stmt->get_result();
if($result !== false && $result->num_rows >= 1){
$row = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();
var_dump($row);
}
}
}
echo $this->connection->error;
return false;
But the approach above is not able to fetch any result sets
Placeholders represent a SINGLE value. If you have a variable and placeholder-using query:
$var = '1,2,3';
SELECT ... WHERE foo IN (?)
then the query will be executed as the SQL had literally been
SELECT ... WHERE foo IN ('1,2,3')
and your 3 separate csv values will be treated as a single monolithic string.
IN clauses are one place where placeholders are somewhat useless, since you have dynamically build up a string with as many placeholders as you have values, e.g.
$vals = array(1,2,3);
$placeholders = '?' . str_repeat(',?', count($vals) - 1);
$stmt = $db->prepare("SELECT ... WHERE foo IN ($placeholders)");
foreach($vals as $i => $val) {
$stmt->bind($i, $vals[$i]);
}
and then

PDO:: Confusion [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 7 years ago.
I have no idea why this is not returning anything. I'll show the code and talk through the steps I've taken.
if (isset($_GET['observation'])) {
require_once("../func/connect.php");
$query = "SELECT * FROM observations WHERE option = ?";
$stmt = $db->prepare($query);
$stmt->bindValue(1, $_GET['observation']);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo $row['question'];
} else {
echo 'nope';
}
$row dumps a false boolean, $row['question'] is null.
I've wrote about a million queries and don't have a clue why this doesn't work.
Database table observations consists of id, question & option and the bindValue is correct to match a string in the database.
However, it returns null.
option is a reserved word in mysql so you need to quote it with backticks:
$query = "SELECT * FROM observations WHERE `option` = ?";

How to represent a PHP array as a comma-delimited string? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP/MYSQL using an array in WHERE clause
I have an array with ID values [1,5,2,6,7...] and I need to use that in a MySQL item_id IN (1,5,2,6,7...) statement to select only rows with an ID listed in the array. How can I go about converting the $arrIDs to something that I can insert into my SQL query?
EDIT- context of the call:
if(!IsNullOrEmptyString($_GET["view_playlist"])) {
session_destroy();
}
$id_list = implode(",", $_SESSION("playlist"));
$sql = 'SELECT t.track_id, t.track_title, t.track_num, al.album_title, g.genre_name, a.artist_name, t.length, t.track_rating '.
'FROM track t, genre g, artist a, album al '.
'WHERE t.track_id IN('.$id_list.' AND t.genre = g.genre_id AND t.artist = a.artist_id AND t.album = al.album_id';
Use implode();
$ids = implode(',', $your_array);
If you're using PDO or mysqli (which you should, as the mysql_ functions are antiquated and should be abandoned), then you'll want to construct a parameterized query using the number of elements in your array to match the number of ?'s in your SQL.
Here's an example in PDO:
$ids = array(1, 2, 3, 4);
try {
$dbh = new PDO("mysql:host=localhost;dbname=mydbname", 'username', 'password');
} catch(PDOException $e) {
die($e->getMessage());
}
$inClause = trim(str_repeat('?, ', count($ids)), ', ');
$stm = $dbh->prepare('SELECT * FROM mytable WHERE id IN ('.$inClause.')');
$stm->execute($ids);
// resulting SQL: SELECT * FROM mytable WHERE id IN (?, ?, ?, ?)

Categories