PHP prepared statments with select query - php

I just started learning PHP today and am trying to write a few queries using prepared statements. so far I have this:
$query = "select * from users where 1 = ?";
$result = sqlsrv_query($connection,$query,array(1));
if($result === false){
echo "error";
}
while($row = sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC)){
print_r($row);
}
It produces the desired result (simply printing everything returned).
I am struggling on making it a prepared query, to avoid SQL injection

This already is a prepared query, where the third argument of sqlsrv_query is the array of variables you want to bind.

Related

select sql row using pdo with where statement

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.

PHP SQLSRV PDO number of results [duplicate]

This question already has answers here:
Row count with PDO
(21 answers)
Closed 2 years ago.
Having issues returning number of results in PHP SQLSRV PDO connection, when I try $stmt->rowCount(); get -1 result, really don't get it.
...
...
...
if(empty($region)){
$query2 = "SELECT [QuotID], [QuotNumber], CreationDate, QuotDate
FROM [dbo].[vQuotaion]
GROUP BY [QuotID]
,[QuotNumber]
,[CreationDate]
,[QuotDate]
HAVING CreationDate >='".$fdate."' AND CreationDate <='".$edate."' AND ProType = 'OPSFi' ORDER BY CreationDate DESC";
$stmt2 = $conn->query( $query2 );
} else {
...
...
...
}
...
...
...
<?php
if(empty($stmt2)){
echo '';
}else{
while ($result = $stmt2->fetch(PDO::FETCH_ASSOC)){
bla bla bla;
}
}
?>
If you want to count the rows without a separate query you can do this with PDO:
$rows = $stmt2->fetchAll();
$num_rows = count($rows);
There is no way to directly count rows when using a SELECT statement with PDO for all database drivers. You could create a function using the code above if you need to retrieve counts regularly.
Warning!
Little Bobby says your script is at risk for SQL Injection Attacks.. Even escaping the string is not safe! Learn about prepared statements for PDO.
You can get the row count of a select query with the PDO versions of the sqlsrv drivers however, like the standard version of the drivers (non-PDO), you have to specify a scrollable cursor. Like so:
$query = "SELECT * FROM myTable";
$stmt = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
$rows = $stmt->rowCount();
The default cursor used is PDO::CURSOR_FWDONLY which, when rowCount() is used, returns -1.
Microsoft documentation.

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.

Writing this MySQLi query as a prepared statement

I have an existing MySQLi query:
$conn = dbConnect('query');
$galNumb = "SELECT COUNT(pj_gallery_id) FROM pj_galleries WHERE project = {$project}";
$gNumb = $conn->query($galNumb);
$row = $gNumb->fetch_row();
$galTotal = $row[0];
This counts the number of galleries per project that match the value in the query string contained in $project.
It works perfect but is not secure compared to a prepared statement. I have been researching this for two days and can not learn how to write this statement as a prepared statement. Any and all help will be insanely appreciated.
UPDATE:
I am flying by the seat of my pants here. I simply need to be shown how to code the above as a prepared statement. This sort of thing isn't resonating with my brain like learning PHP did and I'm just not getting any of this. The PHP manual is confusing and seems to be written for people who already understand PHP.
In short, I need a prepared statement version of the above code so that I can echo the result on the page. Currently, with what is in my DB, the number should be 3, and it consistently returns 1.
I wish I knew more so that I could better phrase my questions, but alas, I'm still learning. My apologies.
UPDATE 2:
Based on suggestions and research, I have this query written, but it ALWAYS returns the value 1, regardless of what's actually in the database:
$galNumb = "SELECT COUNT(pj_gallery_id) FROM pj_galleries WHERE project_part = ?";
$stmt = $conn->prepare($galNumb);
$stmt->bind_param('i', $project);
$gNumb = $stmt->execute();
Again, All I want to do is COUNT how many galleries are in each project. I know this should be simple but it isn't for me. There is currently 1 project in the DB with 3 galleries. The query should return 3.
This is as simple as it gets. This will prepare a sql statement, execute it and fetch the first row.
<?php
// create the prepared statement
$stmt = $conn->prepare('SELECT COUNT(pj_gallery_id) FROM pj_galleries WHERE project = ?');
// bind a variable to the statment
// the character denotes the type of the variable
// 's' for string
// 'i' for integer
$stmt->bind_param('i', $project);
// execute the query
$stmt->execute();
// get the result variable
$result = $stmt->get_result();
// fetch the row
$row = $result->fetch_row();
if ($row) {
echo "The count is " . $row[0];
}
?>
The documentation is pretty straightforward. You have a code example at the bottom.
http://php.net/manual/en/mysqli.prepare.php
$stmt = $dbConnection->prepare('SELECT COUNT(pj_gallery_id) FROM pj_galleries WHERE project = ?');
$stmt->bind_param('s', $project);
$stmt->execute();

Calling MySQL procedure from PHP

As an example, suppose I want to execute the following query:
SELECT * FROM posts;
Therefore, I write the following:
CREATE DEFINER=`root`#`localhost` PROCEDURE `get_posts`(IN `zip` INT)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
SELECT * FROM posts WHERE posts.zip = zip;
END
Is the following change the only one I have to make:
mysql_query("SELECT * FROM posts");
// to
mysql_query("CALL get_posts");
...and then I can fetch rows, etc.?
you also need to supply the parameter
mysql_query("CALL get_posts(11)");
another suggestion is by using PDO extension on this.
Example of using PDO,
<?php
$zipCode = 123;
$stmt = $dbh->prepare("CALL get_posts(?)");
$stmt->bindParam(1, $zipCode);
if ($stmt->execute(array($_GET['columnName'])))
{
while ($row = $stmt->fetch())
{
print_r($row);
}
}
?>
this will protect you from SQL Injection.
Your procedure expects an input parameter, so call it with one:
$result = mysql_query("CALL get_posts(12345)");
This will supply a result resource on a successful call, then you can run a fetch loop as you would a normal query.
if ($result) {
// fetch in a while loop like you would any normal SELECT query...
}

Categories