PHP "SHOW TABLES" MySQLi query not working - php

i'm trying to execute a prepared statement with php but it doesn't work. My prepared statement is like:
SHOW TABLES LIKE "italy_turin_mathematics"
and i do it like this:
if ($stmt = $this->mysqli->prepare("SHOW TABLES LIKE ?_?_?")) {
$stmt->bind_param('sss', "italy", "turin", "mathematics");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($column1);
while($stmt->fetch()) {
echo "Table: ".$column1;
}
}
I'm sure it must return something, because with PHPMyAdmin it does, but with PHP it always skips the while loop, i think there is something wrong with the prepared statement query, maybe it needs to escape the underscore char?
How can i do it?

Your database architecture is utterly wrong.
There should be only one table contains all the data, for all the places and sciences.
And you have to query it usual way, without employing SHOW TABLES at all.
So, it have to be something like
$sql = "SELECT * FROM t WHERE country=? AND city=? and science=?";
$stm = $pdo->prepare($sql);
$stm->execute(array("italy", "turin", "mathematics"));
$data = $stm->fetchAll();
the above code is in PDO, as you have to use it instead of mysqli.
Splitting tables is a very bad idea, violating the very fundamental rules of relational databases. As you can see, it makes you to run such a strange query and will make your further code even worse.

if ($stmt = $this->mysqli->prepare("SHOW TABLES LIKE ?")) {
$country = "italy";
$city = "turin";
$course = "mathematics";
$stmt->bind_param('s', $country . "_" . $city . "_" . $course);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($column1);
while($stmt->fetch()) {
echo "Table: ".$column1;
}
}
As far as I know the code you had would result in a query looking as follows:
SHOW TABLES LIKE 'italy'_'turin'_'mathematics'

You cannot concatenate like that in mySQL, or any form of SQL I can think of.
SHOW TABLES LIKE ?_?_?
Should be:
SHOW TABLES LIKE CONCAT(?, '_', ?, '_', ?) --this gives an error, see below
And I fully agree with #your-common-sense's commentary that this is a terrible way to design a database and you will come to regret it in more ways than just this one messed up query.
edit:
MySQL does not seem to allow functions in a SHOW TABLES statement, so either you'll have to concatenate the table name to a single string in PHP, or you can use a query like:
SELECT
TABLE_NAME
FROM
INFORMATION_SCHEMA.TABLES
WHERE
table_schema = 'mydb' AND
table_name LIKE CONCAT(?, '_', ?, '_', ?);

Related

MySQL PHP loop search query [duplicate]

Here's my attempt at it:
$query = $database->prepare('SELECT * FROM table WHERE column LIKE "?%"');
$query->execute(array('value'));
while ($results = $query->fetch())
{
echo $results['column'];
}
Figured it out right after I posted:
$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->execute(array('value%'));
while ($results = $query->fetch())
{
echo $results['column'];
}
For those using named parameters, here's how to use LIKE with % partial matching for MySQL databases: WHERE column_name LIKE CONCAT('%', :dangerousstring, '%')
where the named parameter is :dangerousstring.
In other words, use explicitly unescaped % signs in your own query that are separated and definitely not the user input.
Edit: Concatenation syntax for Oracle databases uses the concatenation operator: ||, so it'll simply become:
WHERE column_name LIKE '%' || :dangerousstring || '%'
However there are caveats as #bobince mentions here that:
The
difficulty
comes when you want to allow a literal % or _ character in the
search string, without having it act as a wildcard.
So that's something else to watch out for when combining like and parameterization.
$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->bindValue(1, "%$value%", PDO::PARAM_STR);
$query->execute();
if (!$query->rowCount() == 0)
{
while ($results = $query->fetch())
{
echo $results['column'] . "<br />\n";
}
}
else
{
echo 'Nothing found';
}
You can also try this one. I face similar problem but got result after research.
$query = $pdo_connection->prepare('SELECT * FROM table WHERE column LIKE :search');
$stmt= $pdo_connection->prepare($query);
$stmt->execute(array(':search' => '%'.$search_term.'%'));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
This works:
search `table` where `column` like concat('%', :column, '%')
I got this from php delusions
$search = "%$search%";
$stmt = $pdo->prepare("SELECT * FROM table WHERE name LIKE ?");
$stmt->execute([$search]);
$data = $stmt->fetchAll();
And it works for me, very simple. Like he says , you have to "prepare our complete literal first" before sending it to the query
PDO escapes "%" (May lead to sql injection): The use of the previous code will give the desire results when looking to match partial strings BUT if a visitor types the character "%" you will still get results even if you don't have anything stored in the data base (it may lead sql injections)
I've tried a lot of variation all with the same result PDO is escaping "%" leading unwanted/unexcited search results.
I though it was worth sharing if anyone has found a word around it please share it
I had a similar need but was using a variable grabbed from a form. I did it like this to get results from my PostgreSQL DB, using PHP:
<?php
$player = $_POST['search']; //variable from my search form
$find = $sqlPDO->prepare("SELECT player FROM salaries WHERE player ILIKE ?;");
$find->execute(['%'.$player.'%']);
while ($row = $find->fetch()) {
echo $row['player']."</br>";
}
?>
The "ILIKE" makes the search non-case sensitive, so a search for cart or Cart or cARt will all return the same results.
The only way I could get this to work was to put the %$search% into another variable.
if(isset($_POST['submit-search'])){
$search = $_POST['search'];
}
$query = 'SELECT * FROM posts WHERE post_title LIKE :search';
$value ="%$search%";
$stmt= $pdo->prepare($query);
$stmt->execute(array(':search' => $value));
I don't know if this is the best way to do it, in the while loop I used:
while ($r = $stmt->fetch(PDO::FETCH_ASSOC)){

how to use PDO prepared statements in PHP with SQL LIKE operator [duplicate]

Here's my attempt at it:
$query = $database->prepare('SELECT * FROM table WHERE column LIKE "?%"');
$query->execute(array('value'));
while ($results = $query->fetch())
{
echo $results['column'];
}
Figured it out right after I posted:
$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->execute(array('value%'));
while ($results = $query->fetch())
{
echo $results['column'];
}
For those using named parameters, here's how to use LIKE with % partial matching for MySQL databases: WHERE column_name LIKE CONCAT('%', :dangerousstring, '%')
where the named parameter is :dangerousstring.
In other words, use explicitly unescaped % signs in your own query that are separated and definitely not the user input.
Edit: Concatenation syntax for Oracle databases uses the concatenation operator: ||, so it'll simply become:
WHERE column_name LIKE '%' || :dangerousstring || '%'
However there are caveats as #bobince mentions here that:
The
difficulty
comes when you want to allow a literal % or _ character in the
search string, without having it act as a wildcard.
So that's something else to watch out for when combining like and parameterization.
$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->bindValue(1, "%$value%", PDO::PARAM_STR);
$query->execute();
if (!$query->rowCount() == 0)
{
while ($results = $query->fetch())
{
echo $results['column'] . "<br />\n";
}
}
else
{
echo 'Nothing found';
}
You can also try this one. I face similar problem but got result after research.
$query = $pdo_connection->prepare('SELECT * FROM table WHERE column LIKE :search');
$stmt= $pdo_connection->prepare($query);
$stmt->execute(array(':search' => '%'.$search_term.'%'));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
This works:
search `table` where `column` like concat('%', :column, '%')
I got this from php delusions
$search = "%$search%";
$stmt = $pdo->prepare("SELECT * FROM table WHERE name LIKE ?");
$stmt->execute([$search]);
$data = $stmt->fetchAll();
And it works for me, very simple. Like he says , you have to "prepare our complete literal first" before sending it to the query
PDO escapes "%" (May lead to sql injection): The use of the previous code will give the desire results when looking to match partial strings BUT if a visitor types the character "%" you will still get results even if you don't have anything stored in the data base (it may lead sql injections)
I've tried a lot of variation all with the same result PDO is escaping "%" leading unwanted/unexcited search results.
I though it was worth sharing if anyone has found a word around it please share it
I had a similar need but was using a variable grabbed from a form. I did it like this to get results from my PostgreSQL DB, using PHP:
<?php
$player = $_POST['search']; //variable from my search form
$find = $sqlPDO->prepare("SELECT player FROM salaries WHERE player ILIKE ?;");
$find->execute(['%'.$player.'%']);
while ($row = $find->fetch()) {
echo $row['player']."</br>";
}
?>
The "ILIKE" makes the search non-case sensitive, so a search for cart or Cart or cARt will all return the same results.
The only way I could get this to work was to put the %$search% into another variable.
if(isset($_POST['submit-search'])){
$search = $_POST['search'];
}
$query = 'SELECT * FROM posts WHERE post_title LIKE :search';
$value ="%$search%";
$stmt= $pdo->prepare($query);
$stmt->execute(array(':search' => $value));
I don't know if this is the best way to do it, in the while loop I used:
while ($r = $stmt->fetch(PDO::FETCH_ASSOC)){

Select records using PDO with where clause in PHP [duplicate]

Here's my attempt at it:
$query = $database->prepare('SELECT * FROM table WHERE column LIKE "?%"');
$query->execute(array('value'));
while ($results = $query->fetch())
{
echo $results['column'];
}
Figured it out right after I posted:
$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->execute(array('value%'));
while ($results = $query->fetch())
{
echo $results['column'];
}
For those using named parameters, here's how to use LIKE with % partial matching for MySQL databases: WHERE column_name LIKE CONCAT('%', :dangerousstring, '%')
where the named parameter is :dangerousstring.
In other words, use explicitly unescaped % signs in your own query that are separated and definitely not the user input.
Edit: Concatenation syntax for Oracle databases uses the concatenation operator: ||, so it'll simply become:
WHERE column_name LIKE '%' || :dangerousstring || '%'
However there are caveats as #bobince mentions here that:
The
difficulty
comes when you want to allow a literal % or _ character in the
search string, without having it act as a wildcard.
So that's something else to watch out for when combining like and parameterization.
$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->bindValue(1, "%$value%", PDO::PARAM_STR);
$query->execute();
if (!$query->rowCount() == 0)
{
while ($results = $query->fetch())
{
echo $results['column'] . "<br />\n";
}
}
else
{
echo 'Nothing found';
}
You can also try this one. I face similar problem but got result after research.
$query = $pdo_connection->prepare('SELECT * FROM table WHERE column LIKE :search');
$stmt= $pdo_connection->prepare($query);
$stmt->execute(array(':search' => '%'.$search_term.'%'));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
This works:
search `table` where `column` like concat('%', :column, '%')
I got this from php delusions
$search = "%$search%";
$stmt = $pdo->prepare("SELECT * FROM table WHERE name LIKE ?");
$stmt->execute([$search]);
$data = $stmt->fetchAll();
And it works for me, very simple. Like he says , you have to "prepare our complete literal first" before sending it to the query
PDO escapes "%" (May lead to sql injection): The use of the previous code will give the desire results when looking to match partial strings BUT if a visitor types the character "%" you will still get results even if you don't have anything stored in the data base (it may lead sql injections)
I've tried a lot of variation all with the same result PDO is escaping "%" leading unwanted/unexcited search results.
I though it was worth sharing if anyone has found a word around it please share it
I had a similar need but was using a variable grabbed from a form. I did it like this to get results from my PostgreSQL DB, using PHP:
<?php
$player = $_POST['search']; //variable from my search form
$find = $sqlPDO->prepare("SELECT player FROM salaries WHERE player ILIKE ?;");
$find->execute(['%'.$player.'%']);
while ($row = $find->fetch()) {
echo $row['player']."</br>";
}
?>
The "ILIKE" makes the search non-case sensitive, so a search for cart or Cart or cARt will all return the same results.
The only way I could get this to work was to put the %$search% into another variable.
if(isset($_POST['submit-search'])){
$search = $_POST['search'];
}
$query = 'SELECT * FROM posts WHERE post_title LIKE :search';
$value ="%$search%";
$stmt= $pdo->prepare($query);
$stmt->execute(array(':search' => $value));
I don't know if this is the best way to do it, in the while loop I used:
while ($r = $stmt->fetch(PDO::FETCH_ASSOC)){

Using PHP variable in SQL query

I'm having some trouble using a variable declared in PHP with an SQL query. I have used the resources at How to include a PHP variable inside a MySQL insert statement but have had no luck with them. I realize this is prone to SQL injection and if someone wants to show me how to protect against that, I will gladly implement that. (I think by using mysql_real_escape_string but that may be deprecated?)
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'hospital_name' AND value = '$q'";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried switching '$q' with $q and that doesn't work. If I substitute the hospital name directly into the query, the SQL query and PHP output code works so I know that's not the problem unless for some reason it uses different logic with a variable when connecting to the database and executing the query.
Thank you in advance.
Edit: I'll go ahead and post more of my actual code instead of just the problem areas since unfortunately none of the answers provided have worked. I am trying to print out a "Case ID" that is the primary key tied to a patient. I am using a REDCap clinical database and their table structure is a little different than normal relational databases. My code is as follows:
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'case_id' AND record in (SELECT distinct record FROM database.table WHERE field_name = 'hospital_name' AND value = '$q')";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried substituting $q with '$q' and '".$q."' and none of those print out the case_id that I need. I also tried using the mysqli_stmt_* functions but they printed nothing but blank as well. Our server uses PHP version 5.3.3 if that is helpful.
Thanks again.
Do it like so
<?php
$q = 'mercy_west';
$query = "SELECT col1,col2,col3,col4 FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
if($stmt = $db->query($query)){
$stmt->bind_param("s",$q); // s is for string, i for integer, number of these must match your ? marks in query. Then variable you're binding is the $q, Must match number of ? as well
$stmt->execute();
$stmt->bind_result($col1,$col2,$col3,$col4); // Can initialize these above with $col1 = "", but these bind what you're selecting. If you select 5 times, must have 5 variables, and they go in in order. select id,name, bind_result($id,name)
$stmt->store_result();
while($stmt->fetch()){ // fetch the results
echo $col1;
}
$stmt->close();
}
?>
Yes mysql_real_escape_string() is deprecated.
One solution, as hinted by answers like this one in that post you included a link to, is to use prepared statements. MySQLi and PDO both support binding parameters with prepared statements.
To continue using the mysqli_* functions, use:
mysqli_prepare() to get a prepared statement
mysqli_stmt_bind_param() to bind the parameter (e.g. for the WHERE condition value='$q')
mysqli_stmt_execute() to execute the statement
mysqli_stmt_bind_result() to send the output to a variable.
<?php
$q = 'Hospital_Name';
$query = "SELECT value FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
$statement = mysqli_prepare($conn, $query);
//Bind parameter for $q; substituted for first ? in $query
//first parameter: 's' -> string
mysqli_stmt_bind_param($statement, 's', $q);
//execute the statement
mysqli_stmt_execute($statement);
//bind an output variable
mysqli_stmt_bind_result($stmt, $value);
while ( mysqli_stmt_fetch($stmt)) {
echo $value; //print the value from each returned row
}
If you consider using PDO, look at bindparam(). You will need to determine the parameters for the PDO constructor but then can use it to get prepared statements with the prepare() method.

How do I create a PDO parameterized query with a LIKE statement?

Here's my attempt at it:
$query = $database->prepare('SELECT * FROM table WHERE column LIKE "?%"');
$query->execute(array('value'));
while ($results = $query->fetch())
{
echo $results['column'];
}
Figured it out right after I posted:
$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->execute(array('value%'));
while ($results = $query->fetch())
{
echo $results['column'];
}
For those using named parameters, here's how to use LIKE with % partial matching for MySQL databases: WHERE column_name LIKE CONCAT('%', :dangerousstring, '%')
where the named parameter is :dangerousstring.
In other words, use explicitly unescaped % signs in your own query that are separated and definitely not the user input.
Edit: Concatenation syntax for Oracle databases uses the concatenation operator: ||, so it'll simply become:
WHERE column_name LIKE '%' || :dangerousstring || '%'
However there are caveats as #bobince mentions here that:
The
difficulty
comes when you want to allow a literal % or _ character in the
search string, without having it act as a wildcard.
So that's something else to watch out for when combining like and parameterization.
$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->bindValue(1, "%$value%", PDO::PARAM_STR);
$query->execute();
if (!$query->rowCount() == 0)
{
while ($results = $query->fetch())
{
echo $results['column'] . "<br />\n";
}
}
else
{
echo 'Nothing found';
}
You can also try this one. I face similar problem but got result after research.
$query = $pdo_connection->prepare('SELECT * FROM table WHERE column LIKE :search');
$stmt= $pdo_connection->prepare($query);
$stmt->execute(array(':search' => '%'.$search_term.'%'));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
This works:
search `table` where `column` like concat('%', :column, '%')
I got this from php delusions
$search = "%$search%";
$stmt = $pdo->prepare("SELECT * FROM table WHERE name LIKE ?");
$stmt->execute([$search]);
$data = $stmt->fetchAll();
And it works for me, very simple. Like he says , you have to "prepare our complete literal first" before sending it to the query
PDO escapes "%" (May lead to sql injection): The use of the previous code will give the desire results when looking to match partial strings BUT if a visitor types the character "%" you will still get results even if you don't have anything stored in the data base (it may lead sql injections)
I've tried a lot of variation all with the same result PDO is escaping "%" leading unwanted/unexcited search results.
I though it was worth sharing if anyone has found a word around it please share it
I had a similar need but was using a variable grabbed from a form. I did it like this to get results from my PostgreSQL DB, using PHP:
<?php
$player = $_POST['search']; //variable from my search form
$find = $sqlPDO->prepare("SELECT player FROM salaries WHERE player ILIKE ?;");
$find->execute(['%'.$player.'%']);
while ($row = $find->fetch()) {
echo $row['player']."</br>";
}
?>
The "ILIKE" makes the search non-case sensitive, so a search for cart or Cart or cARt will all return the same results.
The only way I could get this to work was to put the %$search% into another variable.
if(isset($_POST['submit-search'])){
$search = $_POST['search'];
}
$query = 'SELECT * FROM posts WHERE post_title LIKE :search';
$value ="%$search%";
$stmt= $pdo->prepare($query);
$stmt->execute(array(':search' => $value));
I don't know if this is the best way to do it, in the while loop I used:
while ($r = $stmt->fetch(PDO::FETCH_ASSOC)){

Categories