This is my first time to try PDO and still learning it. I am more familiar in using mysql or mysqli in developing php system.
After deep searching and searching I still can't seem to understand how to query using PDO
In my code I used mysqli inside a function to be called in index.php
function getUsery(){
$ip = getIPAddress();
$query = mysqli_query("select userID from tblUsers where logged='1' AND ip='$ip'");
$row = mysqli_fetch_array($query);
$emp = $row['userID'];
$logged = $row['logged'];
$userlvl = $row['userLevel'];
$_SESSION['logged'] = $logged;
$_SESSION['userLevel'] = $userlvl;
return $emp;
}
I don't really know how to select sql query using PDO with 'where' statement. Most of what I found is using array with no 'where' statement
How can I select the userID where logged is equal to '1' and ip is equal to the computer's ip address and return and display the result to the index.php
There's SQL statement with WHERE in PDO
$sql = "SELECT * FROM Users
WHERE userID = ?";
$result = $pdo->prepare($sql);
$result->execute([$id]);
Assuming that you know how to connect database using PDO, here is how to select SQL with PDO.
$stmt = $db->prepare("select userID from tblUsers where logged = '1' AND ip = :ip");
$stmt->execute(array('ip' => $ip));
$listArray = $stmt->fetchAll();
Notice the :ip at the end of SELECT. If you don't use ? as a parameters, the prefix : is mandatory and the word after that should be the same as the key in the execute function.
EDIT
In case that the above code is inside the function and $db is outside the function, declare $db as global variable inside the function.
This one is imo one of best guides on PDO and how to use it:
https://phpdelusions.net/pdo
WHERE is a part of query and queries in PDO are not much different from pure *sql queries, just there is going on a bit filtering on execution. Read the guide carefully and you will be able to execute any query you need to.
Related
I have a table structure like this:
sender| receiver| message|date|time
----------------------------------
How do I select all the messages written on the same date, with them appearing at the top, just like Facebook Chat?
I've tried something like this:
<?php
$con=mysql_connect("localhost","root","");
$db=mysql_select_db ("chat",$con);
$query=" select * from chat where sender='$send'
and receiver='$rec' order by date";
$result=mysql_query($query);
while($r2=mysql_fetch_array($result))
echo "<div>{$r2['date']}</div>";
{
echo"<div>{$r2['message']}</div>";
}
?>
You're trying to run an SQL query directly from PHP, which you can't do - you'll need to connect to your database first. Then you need to pass the $send and $rec variables to your database, preferably through prepared statements to prevent SQL injection.
It depends on whether you're using MySQLi or PDO as to exactly how you should do that, but I'll assume you're not using the mysql_ constructor, as that was deprecated as of PHP 5.5, and is removed in PHP 7.
As such, here's an example of how to do this through MySQLi with prepared statements:
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
$stmt = $mysqli->prepare(
"SELECT * FROM tablename WHERE sender = ? && receiver = ?");
$stmt->bind_param("ss", $send, $rec);
// "ss' is a format string, each "s" means string
// Each variable gets passed to the question marks, in order
$stmt->execute();
$stmt->bind_result($result);
You then have the results stored in $result, and are free to manipulate from there.
Hope this helps! :)
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.
My question supposed to be simple! although, I couldn't find the correct answer!
I need to retrieve the "hashed password" for the giving "username" from mySql database with php, then I need to store it in a variable, how could I do that?
All what I get is "Resource id #5"!
This is my code:
$query = "SELECT hashed_password ";
$query .= "FROM users ";
$query .= "WHERE username = '{$username}' ";
$query .= "AND hashed_password = '{$hashed_password}' ";
$query .= "LIMIT 1";
$result_set = mysql_query($query);
echo "$result_set";
echo '</br>';
To start off, let's use a MySQL library that supports prepared statements - otherwise, we'll run into SQL Injection issues in the future. Now, back to the actual question / answer.
If we use MySQLi, we have a few functions that will help us. Here's an example of an answer to your question w/ code comments to help walk through it:
// create our db connection
$mysqli = new mysqli('localhost', 'db_username', 'db_password', 'db_table');
// create a Prepared Statement to query to db
$stmt = $mysqli->prepare('SELECT hashed_password FROM users WHERE username = ? LIMIT 1');
// dynamically bind the supplied "username" value
$stmt->bind_param('s', $username);
// execute the query
$stmt->execute();
// get the first result and store the first column in the `$hashed_password` variable
$stmt->bind_result($hashed_password);
$stmt->fetch();
// close our Prepared Statement and the db connection
$stmt->close();
$mysqli->close();
echo $hashed_password;
Check out the PHP Doc for mysqli::prepare() for more examples =]
Note: I highly recommend avoiding the mysql_query() (and family) functions. They are not only deprecated, but they are quite insecure to use.
You need to fetch the data out of the mysql-resource that is returned by a query.
Just pass it through mysql_fetch_assoc($result_set). It will return your data in a nice and ordered arraay, moving ahead one row every call.
Meaning you can do
while ($row = mysql_fetch_assoc($result_set).
Also, please use mysqli. Its basically the same just with mysqli instead of mysql in commands. See the docs here for more info: http://php.net/manual/en/book.mysqli.php
I have this code for selecting fname from the latest record on the user table.
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$sdt=$mysqli->('SELECT fname FROM user ORDER BY id DESC LIMIT 1');
$sdt->bind_result($code);
$sdt->fetch();
echo $code ;
I used prepared statement with bind_param earlier, but for now in the above code for first time I want to use prepared statement without binding parameters and I do not know how to select from table without using bind_param(). How to do that?
If, like in your case, there is nothing to bind, then just use query()
$res = $mysqli->query('SELECT fname FROM user ORDER BY id DESC LIMIT 1');
$fname = $res->fetch_row()[0] ?? false;
But if even a single variable is going to be used in the query, then you must substitute it with a placeholder and therefore prepare your query.
However, in 2022 and beyond, (starting PHP 8.1) you can indeed skip bind_param even for a prepared query, sending variables directly to execute(), in the form of array:
$query = "SELECT * FROM `customers` WHERE `Customer_ID`=?";
$stmt = $db->prepare($query);
$stmt->execute([$_POST['ID']]);
$result = $stmt->get_result();
$row = $result->fetch_assoc();
The answer ticked is open to SQL injection. What is the point of using a prepared statement and not correctly preparing the data. You should never just put a string in the query line. The point of a prepared statement is that it is prepared. Here is one example
$query = "SELECT `Customer_ID`,`CompanyName` FROM `customers` WHERE `Customer_ID`=?";
$stmt = $db->prepare($query);
$stmt->bind_param('i',$_POST['ID']);
$stmt->execute();
$stmt->bind_result($id,$CompanyName);
In Raffi's code you should do this
$bla = $_POST['something'];
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$stmt = $mysqli->prepare("SELECT `fname` FROM `user` WHERE `bla` = ? ORDER BY `id` DESC LIMIT 1");
$stmt->bind_param('s',$_POST['something']);
$stmt->execute();
$stmt->bind_result($code);
$stmt->fetch();
echo $code;
Please be aware I don't know if your post data is a string or an integer. If it was an integer you would put
$stmt->bind_param('i',$_POST['something']);
instead. I know you were saying without bind param, but trust me that is really really bad if you are taking in input from a page, and not preparing it correctly first.
Can I use my own functions from PHP directly in SQL queries (using mySQL and PDO)? For example:
$query = null;
$result = null;
$query = $this->database_0->prepare("SELECT `id`, `salt` FROM `general_users` WHERE `username` = :username AND `password` = CONCAT(generatePassword(:password, `salt`)) LIMIT 1");
$query->bindValue(':username', $this->input->getValue('username'), PDO::PARAM_STR);
$query->bindValue(':password', $this->input->getValue('password'), PDO::PARAM_STR);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
$query->closeCursor();
Look at line 3 in "WHERE" case.
If it is not possible, I must use two queries just for check if a user exists, it do not look very optimal.
Thanks for your help, Bartek.
Can I use my own functions from PHP directly in SQL queries
No.
Mysql knows nothing of PHP and its functions. You are bound to use mysql functions in mysql and PHP functions in PHP. Quite easy to memorize.
So, here you go, with one single query
$sql = "SELECT id, salt, password FROM general_users WHERE username = ?";
$stmt = $this->db->prepare($sql);
$query->execute([$this->input->getValue('username')]);
$row = $query->fetch();
if (generatePassword($row['password'], $row['salt']) == $this->input->getValue('password'))
{
You can't use a PHP function in a MySQL query.
You can still do this with a single query. Just retrieve user info (including password) by comparing only its username. Then, in PHP, compare stored password with the one you have just computed. That would even allow you to distinguish two cases: "user exists, but password is wrong" and "user does not exist".