$_SESSION variable in mysql query? - php

Whenever I try a query like:
mysql_query("SELECT * FROM data WHERE `user`=$_SESSION['valid_user'] LIMIT 1");
it doesn't work. Why? I escaped the variable, then tried it without, and tried putting quotes around the variable. I know i can do:
$user = $_SESSION['valid_user'];
but shouldn't it work without? Thanks.
THE ANSWER:
PHP can't recognize $_SESSION['valid_user'] due to the single quotes. So either
use curly braces {} or take our the single quotes.
Thanks for helping me everyone.

PHP can't recognise variables inside a string that have square brackets and so on, you have to wrap it in curly brackets to get it to recognise it.
mysql_query("SELECT * FROM data WHERE user={$_SESSION['valid_user']} LIMIT 1");
However - You should always escape any data going into a SQL query, try the example below.
$validUser = mysql_real_escape_string($_SESSION['valid_user']);
mysql_query("SELECT * FROM data WHERE user='$validUser' LIMIT 1");

Arrays/objects must be included in strings slightly differently:
mysql_query("SELECT * FROM data WHERE `user`={$_SESSION['valid_user']} LIMIT 1");
or, you can drop out of the string and concatenate it in:
mysql_query("SELECT * FROM data WHERE `user`=" . $_SESSION['valid_user'] . " LIMIT 1");

Same but with PDO and bound parameters
$stmt = $pdo->prepare('SELECT * FROM data WHERE `user`=:user LIMIT 1');
$stmt->execute(array(':user'=>$_SESSION['valid_user']));
$row = $stmt->fetch();
Note: you can't make LIMIT 1 into a bound parameter because LIMIT is not part of the standard sql and PDO has issues with it, so it has to be bound like this
$stmt = $pdo->prepare('SELECT * FROM data WHERE `user`=:user LIMIT :limit');
$limit = 1;
$user = $_SESSION['valid_user'];
$stmt->bindParam(':user', $user, PDO::PARAM_STR);
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch();
or like this
$limit = 1;
$stmt = $pdo->prepare('SELECT * FROM data WHERE `user`=:user LIMIT '.(int)$limit);
$stmt->execute(array(':user'=>$_SESSION['valid_user']));
$row = $stmt->fetch();
this is the way that I was taught to do it, so I wanted to point it out

try this:
mysql_query("SELECT * FROM data WHERE `user`={$_SESSION['valid_user']} LIMIT 1");
also remember to put session_start on the top of the page

your array is in this context just part of a string and nothing else. To mark an expression as what it is you have to embrace it curly ;-) works only with double quoted strings, though.
mysql_query("SELECT * FROM data WHERE user={$_SESSION['valid_user']} LIMIT 1");

You need to use the string concatenation operator '.' before and after the variable.
mysql_query("SELECT * FROM data WHERE `user`=".$_SESSION['valid_user']." LIMIT 1");
Since you are using a double quoted string, you can also use {} around the variable instead of string concatenation:
mysql_query("SELECT * FROM data WHERE `user`={$_SESSION['valid_user']} LIMIT 1");
By the way, you probably should look into the mysqli (http://php.net/manual/en/book.mysqli.php) library, and be using mysqli::real_escape_string (http://www.php.net/manual/en/mysqli.real-escape-string.php) to ensure that any non-literal variable values are properly escaped.

Related

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

how to write a php variable on a mysql query

I need to write my php variables correctly.
$query2 = mysqli_query($con,"SELECT * FROM palettes LIMIT '$starting_number, $palettes_per_page'");
I don't think you want single quotes on your LIMIT parameters. One way is to use . to concatenate strings.
Since $starting_number and $palettes_per_page are integers, you do not need to escape them. If they were strings, wrap them in mysqli_real_escape_string or mysqli_escape_string to escape special characters.
$query2 = mysqli_query( $con,
"SELECT * FROM palettes LIMIT " .
$starting_number .
"," .
$palettes_per_page );
Just remove the single quote, because double quote can read variable's value
$query2 = mysqli_query($con,"SELECT * FROM palettes LIMIT $starting_number, $palettes_per_page");
Hope this works for you
You could use parameterized queries which also prevent any need to use mysqli_real_escape_string
$stmt = $conn->prepare("SELECT * FROM palettes LIMIT ?, ?'");
$stmt->bind_param("ii", $starting_number, $palettes_per_page);
$stmt->execute();

Using this `{ ... }` brackets on PDO SQL

I ever see some article that use this { ... } brackets to insert their variable
EX:
$query = $this->pdo->prepare("SELECT * FROM administrator WHERE username = '{$ins}'");
Is it doesn't matter? or what is the difference with this one ?
$query = $this->pdo->prepare("SELECT * FROM administrator WHERE username = '$ins'");
Which is the best way to write the PDO SQL queries?
Neither.
Your SQL code should never contain variable input. You should use parameter binding.
$query = $this->pdo->prepare('SELECT * FROM administrator WHERE username = ?');
$query->execute([$ins]);
To be safe I recommend using single quotes ' ', because string interpolation works only with double quotes.
There might be situations when you would like to use a PHP constant as part of the SQL. In this case you can use simple concatenation.
define('ADMIN_TABLE', 'administrator');
$query = $this->pdo->prepare('SELECT * FROM '.ADMIN_TABLE.' WHERE username = ?');
$query->execute([$ins]);

PHP variable in SQLite query

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

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