PHP variable in SQLite query - php

I'm a beginner with web-related coding and I'm trying to make a web-interface from where I can read and write to the sqlite database. My current problem is implementing a PHP-variable ($inNodeID) to sqlite query:
SELECT * FROM data WHERE NodeID = "$inNodeID"
If I replace the variable in query to the value of the variable ("ID007") everything seems to work. So what is wrong with my syntax in this manner?
$inNodeID = "ID007";
echo "Requested node: $inNodeID \n";
print "<table border=1>";
print "<tr><td>NodeID</td><td>MemoryIndex</td><td>DataIndex</td><td>TimeStamp</td></tr>";
$result = $db->query('SELECT * FROM data WHERE NodeID = "$inNodeID"');
//$result->bindParam(':inNodeID', $inNodeID, PDO::PARAM_STR);
foreach($result as $row)
{
print "<td>".$row['NodeID']."</td>";
print "<td>".$row['MemoryIndex']."</td>";
print "<td>".$row['DataIndex']."</td>";
print "<td>".$row['TimeStamp']."</td></tr>";
}
print "</table>";

It seems you were about to use the right way but for some reason gave up
Here you go:
$result = $db->prepare('SELECT * FROM data WHERE NodeID = ?');
$result->execute(array($inNodeID));
$data = $result->fetchAll();
foreach($data as $row)
...

With SQLite3, you can do it like this:
$query = $db->prepare('SELECT * FROM data WHERE NodeID = ? OR NodeID = ?');
$query->bindParam(1, $yourFirstNodeID, SQLITE3_INTEGER);
$query->bindParam(2, $yourSecondNodeID, SQLITE3_INTEGER);
$result = $query->execute();
var_dump($result->fetchArray());
You can find the documentation about bindParam here.

Problem is because of you have enclosed variable $inNodeID. If a variable is enclosed in Quotes PHP behave in different ways based on the Quote thats used. PHP evaluates a variable only when its enclosed in Double quotes, if its used with Single Quote then PHP treats it as a STRING.
please change your code to any one of the below option, your issue will be solved
Option 1
$result = $db->query("SELECT * FROM data WHERE NodeID = $inNodeID");
Option 2
$result = $db->query('SELECT * FROM data WHERE NodeID = '.$inNodeID);
For more info Check Out PHP Manual

you should do Three steps:
prepare your sql code with imaginary word and ":" instead of your variable like this:
$statement = $db -> prepare("SELECT * FROM table WHERE col_test = :imaginary_word");
bind your php variable with the previous step "imaginary word" like this:
$statement -> bindValue(':imaginary_word', $php_variable);
your statement which is a combination of your SQL code and PHP variables is ready and it's the time to execute it like this:
$your_result = $statement -> execute();
♦ now you can use this "$your_result" for fetch_array() , fetch_all Or anything you want...

You don't need to put " around the variable. So try:
$result = $db->query('SELECT * FROM data WHERE NodeID = ' . $inNodeID );

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

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

What can be problem in this line with PDO? [duplicate]

I have a mysql query that targets a single column in a single row
"SELECT some_col_name FROM table_name WHERE user=:user"
After I execute the statement $stmt->execute(); how do I get this single cell directly placed into a variable with no loops? In other words how to get
from $stmt->execute();
to $col_value = 100;
I tried the 2 below, but neither worked.. The column is number 4 in the original table, but I'm assuming since in my select statement I'm selecting it only, it should be 1 when I specify the parameter for fetchColumn.
$col_value = $stmt->fetchColumn();
$col_value = $stmt->fetchColumn(0);
As you can see, I'm trying to do it in as few lines as possible.
Are you sure it's returning any rows?
$stmt->fetchColumn()
is correct way to fetch a single value, so either you probably didn't bind the :user parameter or it simply returned no rows.
$sql='SELECT some_col_name FROM table_name WHERE user=?';
$sth=$pdo_dbh->prepare($sql);
$data=array($user);
$sth->execute($data);
$result=$sth->fetchColumn();
I'm not sure why so many people mess this up:
$stmt = $dbh->prepare("SELECT `column` FROM `table` WHERE `where`=:where");
$stmt->bindValue(':where', $MyWhere);
$stmt->execute();
$SingleVar = $stmt->fetchColumn();
Make sure that you are selecting a specific column in the query and not * or you will need to specify the column order number in fetchColumn(), example: $stmt->fetchColumn(2); That usually isn't a good idea because the columns in the database may be reorganized by, someone...
This will only work properly with unique 'wheres'; fetchColumn() will not return an array.
When you want to get the last insert you add the DESC Limit 1 to the sql statement.
$sql = "SELECT `some_col_name` FROM table_name\n"
. "ORDER BY `some_col_name` DESC\n"
. "LIMIT 1";
$stmt = $conn->prepare($sql);
$result = $stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//convert the array content to string and store in variable
$col = implode(" ", $row);
echo $col;
Have you prepared the statement first? (Before $stmt->execute())
$stmt = $db->prepare("SELECT some_col_name FROM table_name WHERE user=:user");
You could use this:
$stmt->fetch(PDO::FETCH_COLUMN, $number_of_column);

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.

Fetching single row, single column with PDO

I have a mysql query that targets a single column in a single row
"SELECT some_col_name FROM table_name WHERE user=:user"
After I execute the statement $stmt->execute(); how do I get this single cell directly placed into a variable with no loops? In other words how to get
from $stmt->execute();
to $col_value = 100;
I tried the 2 below, but neither worked.. The column is number 4 in the original table, but I'm assuming since in my select statement I'm selecting it only, it should be 1 when I specify the parameter for fetchColumn.
$col_value = $stmt->fetchColumn();
$col_value = $stmt->fetchColumn(0);
As you can see, I'm trying to do it in as few lines as possible.
Are you sure it's returning any rows?
$stmt->fetchColumn()
is correct way to fetch a single value, so either you probably didn't bind the :user parameter or it simply returned no rows.
$sql='SELECT some_col_name FROM table_name WHERE user=?';
$sth=$pdo_dbh->prepare($sql);
$data=array($user);
$sth->execute($data);
$result=$sth->fetchColumn();
I'm not sure why so many people mess this up:
$stmt = $dbh->prepare("SELECT `column` FROM `table` WHERE `where`=:where");
$stmt->bindValue(':where', $MyWhere);
$stmt->execute();
$SingleVar = $stmt->fetchColumn();
Make sure that you are selecting a specific column in the query and not * or you will need to specify the column order number in fetchColumn(), example: $stmt->fetchColumn(2); That usually isn't a good idea because the columns in the database may be reorganized by, someone...
This will only work properly with unique 'wheres'; fetchColumn() will not return an array.
When you want to get the last insert you add the DESC Limit 1 to the sql statement.
$sql = "SELECT `some_col_name` FROM table_name\n"
. "ORDER BY `some_col_name` DESC\n"
. "LIMIT 1";
$stmt = $conn->prepare($sql);
$result = $stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//convert the array content to string and store in variable
$col = implode(" ", $row);
echo $col;
Have you prepared the statement first? (Before $stmt->execute())
$stmt = $db->prepare("SELECT some_col_name FROM table_name WHERE user=:user");
You could use this:
$stmt->fetch(PDO::FETCH_COLUMN, $number_of_column);

Categories