Convert mysql_query to PDO statements - php

While there are a large number of PDO usage examples I have not been able to successfully convert from mysql_query to PDO statements.
Here's what works but is insecure:
<?php
$db = mysql_connect("localhost","username","passphrase");
mysql_select_db("database",$db);
$cat= $_GET["cat"];
/* grab a row and print what we need */
$result = mysql_query("SELECT * FROM cat WHERE cat = '$cat' ",$db);
$myrow3 = mysql_fetch_row($result);
echo "$myrow3[2]";
/* here's an array */
echo '<div class="container">';
$q = mysql_query("SELECT * FROM name WHERE Field4 = '$cat'",$db);
while ($res = mysql_fetch_array($q)){
echo '<div class="item"><p>' . $res['Field1'] . '</p></div>';
}
echo '</div>';
?>
Here is my attempt thus far at attempting to convert the mysql_query* to PDO statements based on How to prevent SQL injection in PHP?. Currently the page does not display, well anything. Any insight would be appreciated!
<?php
$pdo = new PDO('mysql:host=localhost;dbname=database','username','password');
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$cat= $_GET["cat"];
/* let try grabbing one of those rows, do not think an array should be here? */
$stmt = $pdo->prepare('SELECT * FROM cat WHERE cat = :cat');
$stmt->bindParam(':cat', $cat);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result[2];
/* Now we need an array similar to what we had before */
echo '<div class="container">';
$stmt = $pdo->prepare('SELECT * FROM name WHERE Field4 = :Field4');
while ($res = $stmt->execute(array(':cat' => $cat))) {
echo '<div class="item"><p>' . $res['Field1'] . '</p></div>';
}
echo '</div>';
?>

The way you are doing it, first off, isn't protecting you.
A PDO statement should look like (from the manual):
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
So, for your example:
$stmt = $pdo->prepare('SELECT * FROM cat WHERE cat = :cat');
$stmt->bindParam(':cat', $cat);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
Or you could do:
$stmt = $pdo->prepare("SELECT * FROM cat where cat = ?");
if ($stmt->execute(array($cat)) {
while ($row = $stmt->fetch()) {
//print stuff or whatever
}
}
Finally, in your last part:
while $stmt->execute(array(':cat' => $cat));
echo '<div class="item"><p>' . $res['Field1'] . '</p></div>';
It doesn't look like $res ever gets set. It should look like:
while ($res = $stmt->execute(array(':cat' => $cat)) {
echo '<div class="item"><p><a href="bits.php?page=' . $res['Field2'] .
'&' . $res['Field6'] . '">' . $res['Field1'] . '</a></p></div>';
}

Related

How to add a while loop to a variable to display and if - else if result?

I have a if - else if statement changing the query from a db based on user input, and I'm displaying the respective results in while loop one for all the if - else if statements however how can I put the while loop into a variable such as $output then just echo that when the if conditions are met?
<?php include 'db_connect.php';
$job_title = $_POST['job_title'];
$company_name = $_POST['company_name'];
$salary = $_POST['salary'];
if($job_title !== " "){
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE jobTitle LIKE :job_title");
$sql->bindValue(':job_title', '%' . $job_title . '%', PDO::PARAM_INT);
if($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
}
// while loop here //
} else if($company_name !== " ") {
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE company_name LIKE :company_name");
$sql->bindValue(':company_name', '%' . $company_name . '%', PDO::PARAM_INT);
if($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
}
// while loop here //
}else if($salary !== " ") {
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE salary_info LIKE :salary");
$sql->bindValue(':salary', '%' . $salary . '%', PDO::PARAM_INT);
if($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
}
// while loop here //
} ?>
You can save the entire query result in a variable using PDOStatement::fetchAll. Later you use the query result outside of if-else block as per your requirement.
<?php
include 'db_connect.php';
$job_title = $_POST['job_title'];
$company_name = $_POST['company_name'];
$salary = $_POST['salary'];
$output = "";
if($job_title !== " "){
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE jobTitle LIKE :job_title");
$sql->bindValue(':job_title', '%' . $job_title . '%', PDO::PARAM_STR);
if($sql->execute()){
$output = $sql->fetchAll();
}
} else if($company_name !== " ") {
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE company_name LIKE :company_name");
$sql->bindValue(':company_name', '%' . $company_name . '%', PDO::PARAM_STR);
if($sql->execute()) {
$output = $sql->fetchAll();
}
}else if($salary !== " ") {
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE salary_info LIKE :salary");
$sql->bindValue(':salary', '%' . $salary . '%', PDO::PARAM_INT);
if($sql->execute()) {
$output = $sql->fetchAll();
}
}
// Now you can use that query result `$output` as per your requirement.
?>
Also, I changed the datatypes in ->bindValue() methods, and that's because I'm assuming jobTitle and company_name are of string datatype whereas salary is of integer type. If that's not the case then you need to change the datatypes in ->bindValue() methods accordingly.
Here's the reference:
http://php.net/manual/en/pdo.constants.php
Sidenote: If you want to see the entire query result structure, do var_dump($output);
You can just use the while loop just once after all the if-else statement has ended.

PHP Prepared Statements: Echo the Result

i want to Display the Result ('Positio: 2' or 'Position: 1') via a Echo
but $statement is a Object of class PDOStatement and not a String, how do i get it to see only the result of $statement? Thank you
<?php
$pdo = new PDO('mysql:host=localhost;dbname=testdb1', 'root', '');
$idV = $_GET['id'];
$statement = $pdo->prepare("SELECT position FROM idtabelle WHERE idnumber = ?");
$statement->execute(array($idV));
echo "Position: //$result_Of_Statement\\ ";
?>
Here's how I would do it:
$statement = $pdo->prepare("SELECT position FROM idtabelle WHERE idnumber = :idV");
$statement->bindParam(':idV', $idV);
$statement->execute();
while ($row = $statement->fetch(PDO::FETCH_ASSOC))
{
echo $row['position'];
}
You could also do away with the while loop if you wanted to.
I would fetch the result and use print_r or var_dump to see the result quickly.
$statement = $pdo->prepare("SELECT position FROM idtabelle WHERE idnumber = ?");
$statement->execute(array($idV));
$result = $statement->fetch(PDO::FETCH_ASSOC); //Or fetchAll()
echo "Position: ". print_r($result);
That's a quick and dirty way to inspect the result. If you want to add some formatting:
$result = $statement->fetch(PDO::FETCH_ASSOC);
for( $result as $key=>$value ){
echo ucfirst($key) .": $value \n";
}
If you want to get multiple rows wrap that in a loop where you fetch a new row each iteration
while( $result = $statement->fetch(PDO::FETCH_ASSOC) ){
echo "===New Row===";
for( $result as $key=>$value ){
echo ucfirst($key) .": $value \n";
}
}

Select * from table not working SQL

I am trying to select all records from a table and then output them below, however I am only able to get the most recent output out.
The table structure is Id, Start, End, DistanceDirections and Date
I am using the code below to get them and then output each Start as a H1 on the page. As mentioned I am only getting the last value out not all as I would expect, I have also tried to be more specific which can be seen in the code below that and it didn't have an effect on the result.
$sql = "SELECT * FROM `searchdata`";
$stmt = $conn->prepare($sql);
$stmt->execute();
foreach($stmt as $row) {
$htmlResult = "<h1>" . $row['Start'] . "</h1>";
}
Here is the other try:
$sql = "SELECT * FROM `searchdata` WHERE DistanceDirections = 'distance'";
$stmt = $conn->prepare($sql);
$stmt->execute();
foreach($stmt as $row) {
$htmlResult = "<h1>" . $row['Start'] . "</h1>";
}
Is there something simple I am missing?
You're only executing the query, you'll also need to fetch the rows.
$sql = "SELECT * FROM `searchdata`";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
$htmlResult = "";
foreach($result as $row) {
$htmlResult .= "<h1>" . $row['Start'] . "</h1>";
}
echo $htmlResult;
More info:http://php.net/manual/en/pdostatement.fetchall.php

Run a second query inside a foreach loop?

Need to run 2 queries inside a foreach but cant do it without errors.
So, i have this for showing comments:
$query = 'SELECT * FROM comments WHERE updatepostid = "' . $postID . '"';
try {
$stmt = $db->prepare($query);
$stmt->execute();
$countcomments = $stmt->rowCount();
}
catch (PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
foreach ($rows as $row):
$commentID = $row['commentID'];
$usercommentID = $row['userID'];
$commentusername = ucfirst($row['commentusername']);
$comment = ucfirst($row['comment']);
$updatepostid = $row['updatepostid'];
<div class="textcomment">
<?php
echo "<a class='$rightscommentcolor'>$commentusername:</a> $comment";
?>
</div>
<?php endforeach; ?>
I then however want to run another query on the users database to check what rights the user has and then set the class of the comments username to that class.
That query would be e.g.
<?php
$query2 = 'SELECT * FROM users WHERE id = "' . $usercommentID . '"';
try {
$stmt = $db->prepare($query2);
$stmt->execute();
}
catch (PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
foreach ($rows as $row):
$rights = $row['rights'];
if ($rights = '1') {
$rightscommentcolor = 'userrights1';
} else if ($rights = '5') {
$rightscommentcolor = 'userrights5';
}
?>
<?php endforeach; ?>
How is the proper way to go about this?
P.S. i understand that the above code will probably make people cry.
Use a single query with a join. Also, since you're using PDO, you should use parametrized queries rather than concatenating strings.
$query = "SELECT * FROM comments c
JOIN users u ON u.id = c.userID
WHERE updatepostid = :updatepostid";
try {
$stmt = $db->prepare($query);
$stmt->execute(array(':updatepostid' => $postID));
}
catch (PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
You can join the tables in select as mentioned:
<?php
$query = "SELECT * FROM comments c
JOIN users u ON u.usercommentID = c.userID
WHERE updatepostid = :updatepostid";
try {
$stmt = $db->prepare($query);
$stmt->execute();
$countcomments = $stmt->rowCount();
}
catch (PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
foreach ($rows as $row):
$commentID = $row['commentID'];
$usercommentID = $row['userID'];
$commentusername = ucfirst($row['commentusername']);
$comment = ucfirst($row['comment']);
$updatepostid = $row['updatepostid'];
if ($rights = '1') {
$rightscommentcolor = 'userrights1';
} else if ($rights = '5') {
$rightscommentcolor = 'userrights5';
}
echo "<div class="textcomment"><a class='$rightscommentcolor'>$commentusername:</a> $comment</div>";
endforeach;
?>
You also could insert the second loop within the first and assign separate variables to that second loop so that it does not conflict with the first as below, but joining would be a better option:
<?php
$query = 'SELECT * FROM comments WHERE updatepostid = "' . $postID . '"';
try {
$stmt = $db->prepare($query);
$stmt->execute();
$countcomments = $stmt->rowCount();
}
catch (PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
foreach ($rows as $row):
$commentID = $row['commentID'];
$usercommentID = $row['userID'];
$commentusername = ucfirst($row['commentusername']);
$comment = ucfirst($row['comment']);
$updatepostid = $row['updatepostid'];
$query2 = 'SELECT * FROM users WHERE usercommentID = "' . $usercommentID . '"';
try {
$stmt2 = $db->prepare($query2);
$stmt2->execute();
}
catch (PDOException $ex2)
{
die("Failed to run query: " . $ex2->getMessage());
}
$rows2 = $stmt2->fetchAll();
foreach ($rows2 as $row2):
$rights = $row2['rights'];
if ($rights = '1') {
$rightscommentcolor = 'userrights1';
} else if ($rights = '5') {
$rightscommentcolor = 'userrights5';
}
endforeach;
echo "<div class="textcomment"><a class='$rightscommentcolor'>$commentusername:</a> $comment</div>";
endforeach;
?>

PHP: Separate MySQL query values with a comma

I have a MySQL query like this written in PHP:
$merkki = $_GET["merkki"];
// Retrieve all the data from the table
//to show models based on selection of manufacturer
$result = mysql_query("SELECT * FROM Control_Mallit WHERE merkki_id = $merkki")
or die(mysql_error());
echo '{';
while($row = mysql_fetch_array($result)){
echo '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
}
echo '}';
Result is correct, but how I can get a comma after each record? If I echo (,) after each row my code doesn't work. I need it formatted as described below.
{
"":"--",
"series-1":"1 series",
"series-3":"3 series",
"series-5":"5 series",
"series-6":"6 series",
"series-7":"7 series"
}
What's the best way to do this?
Immediately stop using your code. It is vulnerable to SQL injection. Think of what would happen if the value of merkki was 1 OR 1=1. The statement would return all records:
SELECT * FROM Control_Mallit WHERE merkki_id = 1 OR 1=1
You need to bind parameters to your query using mysqli_ or PDO functions (mysql_ functions are being deprecated. Also, use a column list and do not SELECT *.
Here is a possible solution using mysqli_ (not tested):
<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
/* check connection */
if (!$link) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$array = array();
/* create a prepared statement */
$stmt = mysqli_prepare($link, "SELECT id, malli FROM Control_Mallit WHERE merkki_id = ?");
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, 'i', $_GET[merkki]);
/* execute query */
$result = mysqli_stmt_execute($stmt);
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
$array[] = '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
}
/* free result set */
mysqli_free_result($result);
/* close connection */
mysqli_close($link);
echo '{' . implode(',', $array) . '}';
?>
Edit
Following your original code, this solution should work:
$merkki = $_GET["merkki"];
$array = array();
// Retrieve all the data from the table to show models based on selection of manufacturer
$result = mysql_query("SELECT * FROM Control_Mallit WHERE merkki_id = $merkki")
or die(mysql_error());
while($row = mysql_fetch_array($result)){
$array[] = '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
}
echo '{' . implode(',', $array) . '}';
Try:
$merkki = $_GET["merkki"];
$merkki = mysql_real_escape_string($merkki);
// Retrieve all the data from the table to show models based on selection of manufacturer
$result = mysql_query("SELECT * FROM Control_Mallit WHERE merkki_id = $merkki")
or die(mysql_error());
$numRows = mysql_num_rows($result);
$row = 1;
echo '{';
while($row = mysql_fetch_array($result)){
echo '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
if ($row < $numRows) {
echo ',';
}
$row++;
}
echo '}';
It just uses the row count to determine if it should echo a comma or not based on whether or not it is on the last result.
Also, be sure to escape any input you pass to mysql queries or you are vulnerable to SQL injection. See about switching to PDO or Mysqli in the future.
I'd just stick everything in an array and use json_encode() to output it, eg
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[$row['id']] = $row['malli'];
}
echo json_encode($data);
Small example here - http://codepad.viper-7.com/My27XJ
Also, you should not be using the deprecated mysql extension. Instead, I recommend PDO, eg
$db = new PDO(/* connection details */);
$stmt = $db->prepare('SELECT id, malli FROM Control_Mallit WHERE merkki_id = ?');
$stmt->bindParam(1, $_GET['merkki']);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// and so on

Categories