MySQL IN() to work with PDO query [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP PDO: Can I bind an array to an IN() condition?
I have only made websites with PHP and MySQL for a hobby, my whole life I've always used unprepared statements until I decided to try PDO queries last night. I've successfuly gotten them all to work except when I use IN(). For Example when i do this:
$stmt3 = $dbConnection->prepare("SELECT * FROM member_search WHERE zip IN(:zip_codes_in_distance)");
$stmt3->execute(array(':zip_codes_in_distance' => $zip_codes_in_distance ));
foreach ($stmt3 as $user_list) {
//do cool stuff here
}
This returns this error:
Syntax error or access violation: 1064
After googling it, I've tried with no success a few of the solutions like using query() instead of execute()
This only happens when I use IN()
the $zip_codes_in_distance are zipcodes in this format '07110', '07109', '07050'
What am I doing wrong?

Couldn't get this to work correctly using PDO, so I used MySQLi instead.
Establish Database Connection in a separate file:
$Connect = new mysqli($host, DB_Username, DB_password, DB_Name);
Ran the Query like this:
include 'DbConnectFIle.php';
$zips = "07110, 07109";
$sql = "SELECT * FROM table WHERE zip IN(".$zips.") ";
$result = $Connect->query($sql);
while($row = $result->fetch_assoc()){
$MemberName = $row['first_name'];
}
$Connect->close();
echo $MemberName;
Tried for four hours using PDO, MySQLi was the only way I could get it to work.
I used this tutorial: http://codular.com/php-mysqli

Related

PHP not showing MySQL results with variable in query [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
How can I prevent SQL injection in PHP?
(27 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
I have been using the same code for years and all of a sudden I'm having problems that I cannot figure out. I am making a very simple query to MySQL in PHP using a variable in the statement. When I use the variable, it returns no results. When I manually type in the value of the variable instead, it works. I use this syntax all day long and never have had a problem. What on earth is wrong?
$name = "Fred";
$query = "SELECT * FROM database WHERE name='".$name."'";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) != 0) {
echo "Found record.";
}
If I replace the $name variable with Fred, it finds the record. If I echo the query with the variable before it executes and place that exact statement into MySQL directly in phpMyAdmin, I also get the result. If I leave the statement as-is with the variable in place, I get no result. Please help.
your query states SELECT * FROM database WHERE name='".$name."', this means that your table name is database, now i dont know how you actually created this table but database is a MYSQL reserved keyword change the name of your table to something else or just change your query to
$query = "SELECT * FROM `database` WHERE name='$name'";
assuming that your database connection is fine your code should now work
also worth noting, whenever acquiring data from a database use prepared statements instead of raw data as it makes you vulnerable to sql injection, in your case your code should be something like this
$name = "Fred";
$stmt = $dbconnection->prepare("SELECT * FROM table_name WHERE name=?")
$stmt->bind_param("s", $name);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows != 0)
{
echo "Found record.";
}
this is more secure
You shouldn't use mysqli excepted for old projects you can't upgrade, it's outdated and suffers from potential sql injection vulnerabilities.
Instead, I recommand you to learn PDO and prepared statements.
Your request should look like this :
$name = 'Fred';
$sql = "SELECT * FROM my_user_table WHERE name = :name";
// You should have set your pdo instance in a script handling your database connexion and reusing it in any script making requests.
$result = $pdo->prepare($sql);
// Here you dynamically inject values in your request and tells pdo what type of data you are expecting
$result->bindValue(':name', $name, PDO::PARAM_STR);
$result->execute();
if( $result->rowCount()) {
echo "{$result->rowCount()} result(s) found";
}
else {
echo 'No result found';
}
Here's the official doc :
https://www.php.net/manual/fr/book.pdo.php
This will also more than probably fix your problem.

Is it possible to pass a "PHP" variable that is passed by an URL as comparison element for a SQL query? [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 3 years ago.
I've set a local server using PHPMyAdmin, and I'm presenting some dynamic data that is stored in that server using some PHP, HTML and SQL. The problem is that whenever I pass a variable that is stored using $variable = mysqli_real_escape_string($conn, $_GET["variable"]); and then I use that variable in a SQL query similar to this one $sql = 'SELECT * FROM assets WHERE variable="$variable";. The array that is generated is empty.
When I do a print_r($variable);, I get the variable that the code is expecting, so I'm not sure why the query sends an empty array. Then, when I hardcode the SQL query with the value of print_r($variable), the correct array is obtained from the query.
Code in PHP that is not working
$variable = mysqli_real_escape_string($conn, $_GET["variable"]);
print_r($_GET["location"]);
// make SQL
$sql = 'SELECT * FROM assets WHERE variable="$variable"';
Where $conn = mysql_connect('localhost', 'user', 'password', 'table');
The connection is correct though
then for example when I hardcode it using the result I get from
print_r($_GET["variable"]); prints N1 on the screen
This PHP is working, but it won't be dynamic
$sql = 'SELECT * FROM assets WHERE variable="N1';
I'm expecting to see all the results were the field variable = to a $_GET["variable"], where $_GET["variable"] is stored in $variable, but all I'm getting is an empty string.
You could use a prepared statement and binding param (for this you don't need the real string escape id done by the msqli prepared and binding)
$conn= new mysqli('localhost', 'user', 'password', 'your_db');
$myVar = $_GET["location"];
$sql = 'SELECT * FROM assets WHERE variable=?';
$query = $conn->prepare( $sql);
$query->bind_param('s',$myVar);
$result = $query->execute();
Try this code may be solve issues.
$conn= new mysqli("localhost","my_user", "my_password", "world");
$sql = 'SELECT * FROM assets WHERE variable='.$_POST["variable"];
mysqli_query($conn,$sql);

PDO issues with binding IN operator [duplicate]

This question already has answers here:
Can I bind an array to an IN() condition in a PDO query?
(23 answers)
Closed 7 years ago.
Note: I see this question as a probable serious issue in PDO Drivers. I can pretty much understand the difference between an array and string. So, please consider testing this on your sandbox before Deleting or making duplicate.
$pdo = db()->getInstance();
$sql = "SELECT * FROM clients WHERE client_id IN :clients";
$params = [ ":clients" => "(223,224,225)" ];
$stmt = $pdo->prepare($sql);
try{
$stmt->execute($params);
} catch( \Exception $e){
die("Query Execution Failed" . $e->getMessage());
}
Query Execution FailedSQLSTATE[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 ''(223,224,225)'' at line 1
The issue here is instead of translating to:
SELECT * FROM clients WHERE client_id IN (223,224,225)
it is translating to:
SELECT * FROM clients WHERE client_id IN '(223,224,225)'
There are no arrays here. I am just providing a parameter clients to replace :clients. Why does it add the quotes around?
First of all, I agree with you (somewhat). It's a issue, not very serious one. Maybe they kept it knowingly. Or, maybe your stupid question has some debate potentials.
Every PDO parameter gets wrapped with quotes. (Personally I think should not be). When you pass the IN string at once, it puts quote around it which fails the query. But, you can do that (put quotes) with individual item. So, pass parameter to each item instead of preparing string before.
Now, to the solution:
$pdo = db()->getInstance();
$sql = "SELECT * FROM clients WHERE client_id IN :clients";
$clients = [223,224,225];
/* You could use bind with ? here. I am just making this with named parameters so that you could echo SQL */
$params = [];
$replacement = [];
foreach ($clients as $key => $value){
$replacement[] = ":client$key";
$params[":client" . $key] = $value;
}
$sql = str_replace(":clients", "(" . implode(",",$replacement) . ")", $sql);
echo $sql;
/* SELECT * FROM clients WHERE client_id IN (:client0,:client1,:client2) */
$stmt = $pdo->prepare($sql);
try{
$stmt->execute($params);
print_pre($stmt->fetchAll(PDO::FETCH_ASSOC));
} catch( \Exception $e){
die("Query Execution Failed" . $e->getMessage());
}
This works like a charm. I tried by creating a dummy clients table. But the thing is your actual SQL now becomes:
SELECT * FROM clients WHERE client_id IN ('223','224','225')
Most people might not give a shit about it but you might lose some performance because the query is converting the id to string with quotes, especially you have a large database, complex queries and prefer integers.

checking if SQL query was excuted in PDO [duplicate]

This question already has answers here:
How do I check db query returned results using PHP's PDO
(3 answers)
Closed 9 years ago.
in mysql_query we can check if the query was executed or not by doing this:
$query = $yourdbconnection->fetch_array(mysql_query("SELECT * FROM tbl_name"));
if ($query){ // query is working }
else { // query is not working }
in PDO, I am doing something like this:
$query = $yourdbconnection->query("SELECT * FROM tbl_name");
$fetchquery = $query->fetchAll();
if ($fetchquery) { // query is working}
else { // query not working}
Is my code effective? what exactly the if statement doing? Is it doing the same thing that mysql_query was doing? How can I check if the query is returning 0 rows or not?
[EDIT]
I have found those solutions as a workaround to the problem
using $stmt->fetch()
prepare($sql);
$stmt->execute();
if ($data = $stmt->fetch()) {
do {
echo $data['model'] . '<br>';
} while ($data = $stmt->fetch());
} else {
echo 'Empty Query';}
?>
adding another query to count the number of rows see this answer
However, I am still looking for better solutions
To see if your query was executed, I would suggest setting your PDO in exception mode like Your Common Sense suggested. You can do it like this:
$dbh = new PDO('mysql:host=localhost;dbname=db', 'user', 'pass');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Concerning the best way to check if a query returned values or not in PDO, I suggest just doing a SELECT COUNT(*) FROM table query, like this:
<?php
$query = $dbh->query('SELECT COUNT(*) FROM table');
if ($query->fetchColumn() != 0) {
/* Query has result(s) */
$query = $dbh->query('SELECT * FROM table');
/* ... */
} else {
/* Query has no results */
}
?>
Let me know if you have any other questions.
there are 2 questions in your post.
1) what is the best way to check if the query returned values or not in PDO?
check returned values
2) how to check if SQL query was excuted in PDO
set PDO in exception mode as described in the tag wiki
By the way, for the "SELECT * FROM tbl_name" query you may wish to use fetchAll() instead of fetch().

Outputting a list of MySQL table values in PHP/HTML

I have a MySQL list with a few categories and a lot of rows of data. I want to simply output that in PHP/HTML. How would I do that?
<?php
$query = "SELECT * FROM TABLE";
$res = mysql_query($query,$connection);
while($row = mysql_fetch_array($res)) {
print_r($row);
}
?>
To expand on what was already said: http://www.anyexample.com/programming/php/php_mysql_example__display_table_as_html.xml
This will produce a nice html table out of a query.
Please note that the mysql_* functions, as offered by some answers to this question, have been deprecated for quite some time. It is recommended to use either the mysqli_* functions (MySql Improved, which uses a newer underlying library for accessing mysql), or the PDO (PHP Data Objects, an object-oriented interface for connecting to various databases).
For example:
// Create a new PDO connection to localhost.
$dbh = new PDO("mysql:localhost;dbname=testdb", $user, $password);
// Create a PDO Statement object based on a query.
// PDO::FETCH_ASSOC tells PDO to output the data as an associative array.
$stmt = $dbh->query("SELECT * FROM Table", PDO::FETCH_ASSOC);
// Iterate over the statement, using a simple foreach
foreach($stmt as $row) {
echo $row['column1'].' and '.$row['column2'];
}

Categories