Converting to PDO prepared statements from mysqli - php

I have the following bit of code, that selects a table, loops through all the values which match an actor and displays the reviews for that actor.
include("app/config/db.php");
$aid=$actor['id'];
$query = "SELECT * FROM `reviews` WHERE `actor_id` = $aid";
$result = $mysqli->query($query);
$num_results = $result->num_rows;
if( $num_results ){
//loop to show each records
while( $row = $result->fetch_assoc() ){
extract($row);
echo "<span class=\"review-score\">";
echo $row['score']*10;
echo "</span>";
echo " by <strong>";
echo $row['author'];
echo "</strong>";
echo " on <strong>";
echo $row['created_at'];
echo "</strong>";
echo "<p class=\"review-body\">";
echo $row['body'];
echo "</p>";
echo "</br>";
}
}else{
echo "No records found.";
}
$result->free();
$mysqli->close();
I want to convert to using PDO prepared statements.
This is what I've tried. It doesn't display any of the reviews assigned to the actor. Please help
include("app/config/db.php");
$aid=$actor['id'];
$st = DBase::singleton()
->prepare(
'select * ' .
'from `reviews` ' .
'where `actor_id` like :aid ' .
'limit 0,10');
$st->bindParam(':aid', $aid, PDO::PARAM_STR);
if ($st->execute())
{
while ($row = $st->fetch(PDO::FETCH_OBJ))
{
echo "<span class=\"review-score\">";
echo $st['score']*10;
echo "</span>";
echo " by <strong>";
echo $st['author'];
echo "</strong>";
echo " on <strong>";
echo $st['created_at'];
echo "</strong>";
echo "<p class=\"review-body\">";
echo $st['body'];
echo "</p>";
echo "</br>";
}
}
DBase:singleton
static public function singleton()
{
if (!is_object(self::$pdo))
{
self::$pdo = new PDO('mysql:dbname=' . self::DATABASE . ';host=' . self::HOST,
self::USERNAME,
self::PASSWORD);
}
return self::$pdo;
}

You're storing each row's result in $row, but not accessing $row when you want to display the data.
while ($row = $st->fetch(PDO::FETCH_OBJ))
{
...
echo $st['score']*10;
The echo line should be:
echo $row->score*10;
You're also fetching objects but accessing the data as an array.
thats how I was taught to write a while loop.. how else could I do it?
My point is that if assign a variable with successive values of the row, then the data is in that variable, not in the object that iterates over rows. What you've done is analogous to this:
for ($i = 0; $i < $count; $i++) {
echo $count;
}
Whereas in that example one should do this instead to get successive values in the loop:
for ($i = 0; $i < $count; $i++) {
echo $i;
}

Related

How to convert from mysqli to PDO with function that hides empty columns

I have an html-form to read out data from a DB that are then dislayed in an html-table. Columns that contain no values should not be displayed. This works well with the following code using array_column and array_filter:
$sql = "SELECT DISTINCT $selection FROM $table WHERE $where";
$result = mysqli_query($db, $sql) or die("<b>No results</b>"); //Running the query and storing it in result
$numrows = mysqli_num_rows($result); // gets number of rows in result table
$numcols = mysqli_num_fields($result); // gets number of columns in result table
$field = mysqli_fetch_fields($result); // gets the column names from the result table
$custom_column_arr = array('Color' => 'color_comment', 'Weight' => 'weight_comment');
if($numrows > 0) {
echo "<table id='myTable'>";
echo "<thead>";
$results = array();
while($row = mysqli_fetch_assoc($result)) {
$results[] = $row;
}
echo "<tr>";
echo "<th>" . 'Nr' . "</th>";
for($x = 0; $x < $numcols; $x++) {
$column[$x] = array_column($results, $field[$x]->name); // puts all existing values of a column into the field-name
if(array_filter($column[$x])) { // displays only those columns with at least one value in it
$key = array_search($field[$x]->name, $custom_column_arr);
if($key !== FALSE) {
echo "<th>" . $key . "</th>";
} else {
echo "<th>" . $field[$x]->name . "</th>";
}
}
}
echo "</tr></thead>";
echo "<tbody>";
$nr = 1;
$result = mysqli_query($db, $sql);
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $nr . "</td>";
for($k = 0; $k < $numcols; $k++) { // goes around until there are no columns left
$column[$k] = array_column($results, $field[$k]->name); // puts all existing values of a column into the field-name
if(array_filter($column[$k])) { // displays only those columns with at least one value in it
echo "<td>" . $row[$field[$k]->name] . "</td>"; //Prints the data } } echo "</tr>"; $nr = $nr + 1;
} // End of while-loop
echo "</tbody></table>";
}
}
mysqli_close($db);
}
Due to security reasons, I switched to PDO prepared statements to avoid SQL-injection:
enter code here
$sql = "SELECT DISTINCT $selection FROM $table WHERE color = :color AND weight = :weight";
$stmt = $pdo->prepare($sql);
$renalstatus = '10';
$bindValue = implode("/n ", $bindValue);
$stmt->bindValue(':color', $color, PDO::PARAM_STR);
$stmt->bindValue(':weight', $weight, PDO::PARAM_INT);
$stmt->execute();
$zeilen = $stmt->rowCount();
$spalten = $stmt->columnCount();
if($zeilen > 0) {
echo "<table id='myTable'>";
echo "<thead>";
$results = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$results[] = $row;
}
echo "<tr>";
echo "<th>" . 'Nr' . "</th>";
for($x = 0; $x < $spalten; $x++) {
$column[$x] = array_column($results, $fields[$x]->name); // puts all existing values of a column into the field-name
if(array_filter($column[$x])) { // displays only those columns with at least one value in it
$key = array_search($fields[$x], $custom_column_arr);
if($key !== FALSE) {
echo "<th>" . $key . "</th>";
} else {
echo "<th>" . $fields[$x] . "</th>";
}
}
}
echo "</tr></thead>";
echo "<tbody>";
$nr = 1;
$stmt = $pdo->query($sql);
while($row = $stmt->fetch(PDO::FETCH_NUM)) {
echo "<tr>";
echo "<td>" . $nr . "</td>";
for($k = 0; $k < $spalten; $k++) { // goes around until there are no columns left
$column[$k] = array_column($results, $fields[$k]->name); // puts all existing values of a column into the field-name
if(array_filter($column[$k])) { // displays only those columns with at least one value in it
echo "<td>" . $row[$k] . "</td>"; //Prints the data}
}
echo "</tr>";
$nr = $nr + 1;
} // End of while-loop
echo "</tbody></table>";
}
}
$stmt->close();
The query results are correctly displayed as before. However, completely empty columns are displayed as well and shoul be hidden.
After having built the headline, in mysqli there is a second query before the rows are generated:
$result = mysqli_query($db, $sql);
Unfortunately, using PDO this does not work with:
$stmt = $pdo->query($sql); or $stmt->execute();
I would be more than happy if someone could help me make this function work again!

passing variable to another page for sql query

I am trying to pass a variable from a page to another page so that i can display more information on the other page by getting the idea. I am not really sure what is going wrong and because I use bluemix it doesn`t display an error it just gives me the page 500 error. Here is my code:
<?php
$strsql = "select id, name, problem, urgency, technology from idea WHERE status='saved'";
if ($result = $mysqli->query($strsql)) {
// printf("<br>Select returned %d rows.\n", $result->num_rows);
} else {
//Could be many reasons, but most likely the table isn't created yet. init.php will create the table.
echo "<b>Can't query the database, did you <a href = init.php>Create the table</a> yet?</b>";
}
?>
<?php
echo "<tr>\n";
while ($property = mysqli_fetch_field($result)) {
echo '<th>' . $property->name . "</th>\n"; //the headings
}
echo "</tr>\n";
while ( $row = mysqli_fetch_row ( $result ) ) {
$idea_id= $row['id'];
echo "<tr>\n";
for($i = 0; $i < mysqli_num_fields ( $result ); $i ++) {
echo '<td>' . "$row[$i]" . '</td>';
}
echo "</tr>\n";
}
$result->close();
mysqli_close();
?>
There's a small bug in your code. Your echo <a href ="... line should be like this,
echo '<td>' . $row[$i] . '</td>';

For each results- Mysql - JSON

How i separate the first result of for each loop and remaining. I have 2 divs, i want first result to be displayed there and rest on another div.
Also is there any way that i can get json decode without for each loop, i want to display result based on for each values from database, and querying database in for each loop is not recommended.
Here is my code, What i want
<div class="FirstDiv">
Result1
</div>
<div class="RemDiv">
Remaining result from for each loop
</div>
Here is full code
$data = json_decode($response->raw_body, true);
$i = 0;
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
if (++$i == 6)
break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if (mysqli_num_rows($rs)==1) //uid found in the table
{
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
}
Try this:
$data = json_decode($response->raw_body, true);
$i = 0;
echo '<div class="FirstDiv">'; // add this line here
foreach( $data['photos'][0]['tags'][0]['uids'] as $value ) {
if (++$i == 6) break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if ( mysqli_num_rows($rs) == 1 ) { //uid found in the table
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
// Echo celebrity information:
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
if ($i==1) { echo '</div><div class="RemDiv">'; }; // add this line here
}
echo '</div>'; // close the last tag
$predictions=array();
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
$predictions[]="'" . mysqli_real_escape_string($con, $value[prediction]) . "'";
}
$check="SELECT fullname FROM test_celebrities WHERE shortname IN (" . implode(',' $predictions) . ")";
$rs = mysqli_query($con,$check);
while ($row = mysqli_fetch_assoc($rs)) {
if (!$count++) {
// this is the first row
}
But note that you now have two sets of data which are sorted differently - hence you'll need to iterate through one and lookup values in the other.

How can I arrange this code so I can get different entry from database for each table row

I want every different record of database to be display on each table rows, but I'm unable to retrieve different record for each row and column. Please give me suggestion where I can paste than while block so it will give different result for each row and column.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$rec_limit = 10;
$scriptname=$_SERVER['PHP_SELF'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('online_shopping'); // include your code to connect to DB.
$tbl_name="mobile_db"; //your table name
$start = 0;
$limit = 5;
$sql = "SELECT id,company,model,price,availability,image FROM $tbl_name LIMIT $start, $limit";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$company=$row['company'];
$model=$row['model'];
$available=$row['availability'];
$price=$row['price'];
}
echo "<table border='2'>";
$j = 0;
for($j = 0; $j<5; $j++)
{
echo "<tr>";
for($i = 0; $i<3; $i++)
{
echo "<td>";
echo "<table border='2'>";
echo "<tr>";
echo "<td><img src='abc.jpg' height='250' width='250'/></td>";
echo "</tr>";
echo "<tr>";
echo "<td>";
echo "<table border='2'>";
echo "<tr>";
echo "<td><b>Brand : </b></td>";
echo '<td>'.$company.'</td>';
echo "</tr>";
echo "<tr>";
echo "<td><b>Model : </b></td>";
echo '<td>'.$model.'</td>';
echo "</tr>";
echo "<tr>";
echo "<td><b>Availability : </b></td>";
echo '<td>'.$available.'</td>';
echo "</tr>";
echo "<tr>";
echo "<td><b>Price : </b></td>";
echo '<td>'.$price.'</td>';
echo "</tr>";
echo "</table>";
echo "</td>";
echo "</tr>";
echo "</table>";
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
You need to move the table rows inside the fetch loop or store the row in an array. I have simplified your tables to make the example clearer:
$result = mysql_query($sql);
if (!$result) {
/* Error */
}
echo '<table>';
while ($row = mysql_fetch_array($result)) {
echo '<tr><td><img src="', htmlspecialchars ($row['image']), '">';
echo '<tr><td><table>';
echo ' <tr><th>Brand<td>', htmlspecialchars ($row['company']);
echo ' <tr><th>Model<td>', htmlspecialchars ($row['model']);
echo ' <tr><th>Availability<td>', htmlspecialchars ($row['availability']);
echo ' <tr><th>Price<td>', htmlspecialchars ($row['price']);
echo ' </table>';
}
echo "</table>\n";
Some notes about the code:
Test the return value of mysql_query(). The query might fail.
Escape your output using htmlspecialchars().
You should use <th> elements for your headings and style those, instead of using inline <b> elements.
I added output of $row['image'] which might not do what you want.
And do not use the deprecated mysql extension. Use PDO or mysqli instead.
In your while loop you always rewrite the same variables, after loop you have only last record saved.
In the loop, you have to save records into array.
In your code you have nested tables, but in the first one, there is only one row and one table cell which contains another table. I use just nested table.
<?php
...
$result = mysql_query($sql);
$data = array();
while($row = mysql_fetch_array($result)) {
$data[] = $row;
}
if (count($data) > 0) {
echo '<table>';
foreach ($data as $row) {
echo '<tr>';
echo '<td>Brand: ' . $row['company'];
echo '<td>Model: ' . $row['model'];
echo '<td>Availability: ' . $row['availability'];
echo '<td>Price: ' . $row['price'];
}
echo '</table>';
} else {
echo 'no records';
}
?>
Not sure I fully understand what you are trying to accomplish but try this.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$rec_limit = 10;
$scriptname=$_SERVER['PHP_SELF'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('online_shopping'); // include your code to connect to DB.
$tbl_name="mobile_db"; //your table name
$start = 0;
$limit = 5;
$sql = "SELECT id,company,model,price,availability,image FROM $tbl_name LIMIT $start, $limit";
$result = mysql_query($sql);
echo "<table border='2'>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>".$row['company']."</td>";
echo "<td>".$row['model']."</td>";
echo "<td>".$row['availability']."</td>";
echo "<td>".$row['price']."</td>";
echo "</tr>";
}
echo "</table>";
?>

How do I display two rows from sql side-by-side using php?

My code below displays 10 entries, but it displays it in 10 rows and 1 column. I would like for it to display 10 entries, but in 2 columns and 5 rows. Can anyone help? Thanks in advance.
< ?php
mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$result = mysql_query("SELECT * FROM Members LIMIT 0, 10")
or die(mysql_error());
echo '<table>';
echo '<tr>';
while($row = mysql_fetch_array( $result )) {
if ($row['Approved']=='No')
{
continue;
}
else{
echo '<td>';
echo "ID Number: ".$row['id'];
echo "<br/>";
echo '<img src="'.$row['Pic'].'">';
echo "<br/>";
echo '<hr>';
echo '<tr>';
}
}
echo '</table>'
?>
<?php
mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error()); mysql_select_db($dbname) or die(mysql_error());
$result = mysql_query("SELECT * FROM Members LIMIT 0, 10") or die(mysql_error());
$i = 1; //The following logic only works if $i starts at '1'.
$numofcols = 2; //Represents the number of columns you want in the table.
echo '<table>'; //Open table.
while($row = mysql_fetch_array( $result )) {
if ($row['Approved']=='No'){
continue;
}
else{
//If it's the beginning of a row...
if( $i % $numofcols == 1 ){
echo '<tr>'; //Open row
}
//Table Cell.
echo '<td>'; //Open Cell
echo 'ID Number: '.$row['id'];
echo '<br/> <img src="'.$row['Pic'].'"> <br/>';
echo '</td>'; //Close Cell
//If we have already placed enough cells, close this row.
if( $i % $numofcols == 0) {
echo '</tr>'; //Close Row.
}
//Now that we've made a table-cell, lets increment our counter.
$i = $i + 1;
}
}
//So we make sure to close our rows if there are any orphaned cells
if( ($i % $numofcols) > 0){
echo '</tr>';
}
echo '</table>' //Close Table
?>
Please note that the mod logic will only work if the starting value of $i is '1'.
This code will create a table with 2 columns.
Not tested, but basically you can call $row = mysql_fetch_array() in the loop as well to grab another row.
while($row = mysql_fetch_array( $result ))
{
echo "<tr>";
echo "<td>";
echo "ID Number: ".$row['id'];
echo "<br/>";
echo '<img src="'.$row['Pic'].'">';
echo "<br/>";
echo '<hr>';
echo "</td>";
$row = mysql_fetch_array( $result );
if($row)
{
echo "ID Number: ".$row['id'];
echo "<br/>";
echo '<img src="'.$row['Pic'].'">';
echo "<br/>";
echo '<hr>';
}
else
{
// Empty cell
echo "<td> </td>";
}
echo "</tr>";
}
Use modulo for echo "< tr>"
$result = mysql_query("SELECT * FROM Members LIMIT 0, 10")
or die(mysql_error());
$i = 0;
echo '<table>';
echo '<tr>';
while($row = mysql_fetch_array( $result )) {
if ($row['Approved']=='No')
{
continue;
}
else{
echo '<td>';
echo "ID Number: ".$row['id'];
echo "<br/>";
echo '<img src="'.$row['Pic'].'">';
echo "<br/>";
echo '<hr>';
if ($i % 5)
echo '</tr>';
$i++;
}
echo '</table>'

Categories