How do you fetch all rows with pdo? - php

I am making a blog and I want to fetch all rows using a pdo statement but no matter what I do only one row comes back even though there are two rows in my database.
Here's the code sample where I connect:
<?php
try{
$link=new PDO('mysql:host=127.0.0.1;dbname=blog1','root','');
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
echo $e->getMessage();
die();
}
?>
Then I try to fetch all rows
<?php
require 'Escape.php';
$posts_query=$link->query('SELECT * FROM posts');
$posts_query->execute();
/* variable that holds a with the database link and query in it then fetches
all the data related to the query into and assoc array */
$result=$posts_query->fetchAll();
//counting all rows
$count=$posts_query->rowCount();
if($count>0){
foreach($result as $r){
$id= $r['id'];
$title= $r['title'] ;
$content=$r['content'];
$date= $r['date'];
//admin buttons
$admin="";
//keeping title safe
$Title=htmlentities($title);
//keeping output safe
$output=htmlentities($content);
// styling the posts to be echoed with secure variables
$posts= "<div><h2><a href='view_post.php?pid=$id' class='names'>$Title</a>
</h2><h3>$date</h3><p>$output</p>$admin</div>";
escape($posts);
}
echo"<div id=posts>$posts</div>";
} else{
echo 'There are no posts to display.';
}
?>

Your $posts's value is reset to the latest row when you loop, either you append the value of each post using concat . operator:
if($count>0){
$posts = "";
foreach($result as $r){
// Define your variable
$posts .= "<div><h2><a href='view_post.php?pid=$id' class='names'>$title</a></h2><h3>$date</h3><p>$output</p>$admin</div>";
escape($posts);
}
echo"<div id=posts>$posts</div>";
} else { ... }
Or printing each post while looping:
if($count>0){
$posts = "";
echo "<div id='posts'>";
foreach($result as $r){
// Define your variable
$posts = "<div><h2><a href='view_post.php?pid=$id' class='names'>$title</a></h2><h3>$date</h3><p>$output</p>$admin</div>";
escape($posts);
echo $posts;
}
echo"</div>";
} else { ... }

Looks like you are re-assigning posts on every iteration, try adding the values to an array and imploding them when you would like to echo them out.
require 'Escape.php';
$posts_query=$link->query('SELECT * FROM posts');
$posts_query->execute();
$result=$posts_query->fetchAll();
$count=$posts_query->rowCount();
if($count>0){
$posts=[];
foreach($result as $r){
$id= $r['id'];
$title= $r['title'] ;
$content=$r['content'];
$date= $r['date'];
$admin="";
$Title=htmlentities($title);
$output=htmlentities($content);
// Add the HTML to the $posts array, also taking advantage of NOWDOCS
$posts[]= <<< HTML
<div>
<h2>
<a href='view_post.php?pid={$id}' class='names'>{$Title}</a>
</h2>
<h3>{$date}</h3>
<p>{$output}</p>
{$admin}
</div>
HTML;
escape($posts);
}
echo"<div id='posts'>" . implode('', $posts) . "</div>";
} else {
echo 'There are no posts to display.';
}
Here is a reference to PHP HEREDOCS.

Related

decoding a php array to get a variable

How do I get fname from the result of SQL query and store it in $_SESSION['fname'].
<?php
include('init.php');
session_start();
if(isset($_POST))
{
$loginemail=$_POST["loginemail"];
$loginpassword=$_POST["loginpassword"];
$fname="";
$sql = "select count(*),fname from users where password='$loginpassword' and email='$loginemail'";
$result=mysqli_query($con,$sql);
if($result){
$response =array();
while($row=mysqli_fetch_array($result))
{
array_push($response,array("Count"=>$row[0],"name"=>$row[1]));
}
$_SESSION["fname"]=$fname;
echo json_encode(array("server_response"=>$response),JSON_FORCE_OBJECT);
}
else{
echo "error";
}
mysqli_close($con);
}
?>
This is my php code to get the count and fname(username) from database using sql query
init.php has the connection details
my aim here is to retrieve fname using emailid and password
i get the count which is always 1 as per my database restrictions and a fname i want to declare a session variable as this fname
how do i decode the array to get fname
thanks in advance
Seems that you don't assign a value to $fname
<?php
include('init.php');
session_start();
if(isset($_POST))
{
$loginemail=$_POST["loginemail"];
$loginpassword=$_POST["loginpassword"];
$fname="";
$sql = "select count(*),fname from users where password='$loginpassword' and email='$loginemail'";
$result=mysqli_query($con,$sql);
if($result){
$response =array();
while($row=mysqli_fetch_array($result))
{
array_push($response,array("Count"=>$row[0],"name"=>$row[1]));
//
// try assign $fname here if you want the first you can
//
if($fname ==""){
$fname = $row[1];
}
//
}
$_SESSION["fname"]=$fname;
echo json_encode(array("server_response"=>$response),JSON_FORCE_OBJECT);
}
else{
echo "error";
}
mysqli_close($con);
}
?>
Since you are making an associative array, you need to access Count and name as keys. Like:
foreach($response as $key => $value) {
echo "Key=" . $key . ", Value=" . $value;
echo "<br/>";
}
But if you are sure that you will always get a single row, why don't you just store them in scalar variables like $count and $fname and inside your code do this:
$count; $fname = "";
while($row=mysqli_fetch_array($result))
{
$count = $row[0];
$fname = $row[1];
}

How to make echo results in table hyperlinks

I have retrieved data from DB and inserted into a html table however I want to make each value in the table a hyperlink to another page. Below I have tried making the pupil_id and link to a profile.php but all pupil_id values have now vanished!
(if (!isset($_POST['search'])) {
$pupils = mysql_query("SELECT * FROM pupil") or die("Cant find Pupils");
$count = mysql_num_rows($pupils);
if ($count == 0) {
$totalpupil = "There are currently no Pupils in the system.";
} else {
while ($row = mysql_fetch_array($pupils)) {
?>
<tr>
<td><?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?></td>
<td><?php echo $row['pupil_name'] ?></td>
<td><?php echo $row['class_id'] ?></td>
</tr>
<?php
}
}
})
The finishing table should display every hyperlink as a hyperlink to another page. Any help?
Because your HTML is invalid, you are missing a closing > and you have no text defined for the hyperlink
<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?> //Wrong
Correct would be
<?php echo ''.$row['pupil_id'].''; ?>
Try replace this:
<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?>
with this:
<?php echo "<a href='profile.php?id=".$row['pupil_id']."'>link</a>"; ?>
Also, you dont have <table> tags at all.
You don't put any text between your link tags, text here
Maybe this will help you:
<td><?php echo ''.$row['pupil_name'].'' ?></td>
http://uk3.php.net/mysql_query
Watch out, which ever resource you are learning from may well be quite old. mysql_query is now deprecated.
http://uk3.php.net/manual/en/ref.pdo-mysql.php is a replacement.
Here is a kick starter to using PDO (this is much much safer) i write a while ago.
Include this file in which ever php script needs to access your db. An example file name would be 'database.php' but that is your call. Set the namespace from 'yourproject' to whatever your project is called. Correct the database credentials to suit your database
This will save you a lot of headaches hopefully!
I have given some example uses at the bottom for you. I remember when i started out getting clear advice was sometimes hard to come by.
//***** in a database class file*****/
namespace yourproject;
class Database {
private $db_con = '';
/*** Function to login to the database ***/
public function db_login()
{
// Try to connect
try{
// YOUR LOGIN DETAILS:
$db_hostname = 'localhost';
$db_database = 'yourdatabasename';
$db_username = 'yourdatabaseusername';
$db_password = 'yourdatabasepassword';
// Connect to the server and select database
$this->db_con = new \PDO("mysql:host=$db_hostname;dbname=$db_database",
"$db_username",
"$db_password",
array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// Prevent emulation of prepared statements for security
$this->db_con->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
$this->db_con->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return true;
}
// If it fails, send user to maintenance page
catch(PDOException $e)
{
header("location:http://yourwebsiteurl.com/maintenance.php");
exit();
}
}
/*** Function for database control ***/
public function db_control($query , $parameters, $returnID = false)
{
if(!is_array($query) && is_array($parameters))
{
try{
//prepare the statement
$statement = $this->db_con->prepare($query);
//execute the statement
$statement->execute($parameters);
//check whether this is a select, if it is then we need to retrieve the selected data
if(strpos($query, 'SELECT') !== false)
{
//fetch the results
$result = array();
while( $row = $statement->fetch(\PDO::FETCH_ASSOC) )
{
$result[] = $row;
}
//count the results
$count = count($result);
//return the array
return array( 'results' => $result, 'result_count' => $count );
}
//else return the number of affected rows
else{
//count the affected rows and place into a returnable array
$affected_rows = $statement->rowCount();
$returnArray = array('result_count' => $affected_rows);
//check to see if we are to return a newly inserted autoincrement ID from an INSERT
if($returnID)
{
//find the newly created ID and add this data to the return array
$insertID = $this->db_con->lastInsertId();
$returnArray['ID'] = $insertID;
}
return $returnArray;
}
}
catch(PDOException $e)
{
return false;
}
}
else{
return false;
}
}
}
// Start the database class and connect to the database then create a globally accessible function for ease of reference
$db = new \yourproject\Database();
$db->db_login();
function _db( $sql , $params , $returnID = false ){
return $GLOBALS['db']->db_control( $sql , $params , $returnID );
}
When you include this file you now have a new function: _db(). As the function is global it can be called from within any class or std file. When called into a variable as demonstrated below will result in an array like this:
array(
'result_count' => 3,
'results' => array(
array(/*row 1*/),
array(/*row 2*/),
array(/*row 3*/),
.. etc etc
)
)
Now include your database file in your php script:
//call in the database file
require_once 'database.php';
//your query as in the op
$sql = 'SELECT * FROM pupil';
//your params for the query
$params = array();
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);
//if no results
if( $query['result_count'] == 0 )
{
echo 'sorry no pupils in the system';
}
else
{
//looping through each result and printing into a html table row
for( $i = 0 ; $i < $query['result_count'] ; ++$i )
{
echo '<tr><td><a href="profile.php?id=' . $query['results'][$i]['pupil_id'] . '"</a></td>';
echo '<td>'. $query['results'][$i]['pupil_name'] . '</td>';
echo '<td>'. $query['results'][$i]['class_id'] . '</td></tr>';
}
}
Your original query but with some parameters passed through
//Passing parameters to the query
//your query
$sql = 'SELECT * FROM pupil WHERE pupil_id = :pupil_id AND class_id = :class_id';
//your params for the query
$params = array(
':pupil_id' => 12,
':class_id' => 17,
);
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);
//deal with the results as normal...
If you set the 3rd param as true you can return the automatic id of the row just entered eg:
//where $sql is a query that will INSERT a row
$query = _db($sql,$params, true);

Outputting a PDO request from mySQL into a dropdown selector list

I have a table with 2 columns and i am looking to output only one of these columns into a drop down selector list with a button at the bottom. I am using PDO to connect to the database, This code is working but it is only giving me an array of all of the details of each row.
<?php
/* Execute a prepared statement by binding PHP variables */
$username = "mydb";
$password = "mydb";
$member = $_SESSION['SESS_MEMBER_ID'];
try {
$dbh = new PDO('mysql:host=;dbname=mydb', $username, $password);
$sth = $dbh->prepare('SELECT list_name FROM lists WHERE member_id = :member_id ');
$sth->execute(array('member_id' => $member));
$result = $sth->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
print_r($row);
}
} else {
echo "No rows returned.";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
This is the working code so far, how to i change the output from an array to a selector drop down list with buttons? even a scrolling box list would do?
You are just trying to display a query result in a drop down box.
This is only html depending on some variables.
Instead of displaying results like this :
foreach($result as $row) {
print_r($row);
}
you should display an HTML tag with PHP like this :
print '<select id="your_list">';
foreach ($result as $row) {
print '<option value="'.$row['list_name'].'">'.$row['list_name'].'</option>';
}
print '</select>';
print '<input type="submit" value="Submit">';
If you want be able to submit this form and get the value, you have to surround it with a form tag with right options.
You access the element in the array by column name e.g. $row['list_name']
Something like:
<select name='x'>
<?php
foreach($result as $row) {
echo "<option value='".$row['list_name']."'>".$row['list_name']."</option>";
}
?>
</select>

Hide the heading if mysql query is empty

Is there a way to hide a section of html if it is used to display a php/mysql query result that comes back empty. Below is the query:
try
{
$park_id = $_GET['park_id'];
$query2="SELECT `name` FROM `tpf_rides` WHERE `park_id` = $park_id AND `top_ride` = 1 ORDER BY `name` ASC";
$result2 = $pdo->query($query2);
}
catch (PDOException $e)
{
$output = 'Unable to pull rides.';
include 'output.html.php';
}
$output = 'Sucessfully pulled rides';
//include 'output.html.php';//
and the part of code used to display the results:
<h2>Top Attractions</h2>
<ul>
<?php foreach ($result2 as $row2): ?>
<li><h3><?php echo $row2['name']; ?></h3></li>
<?php endforeach; ?>
</ul>
<hr>
There are a number of parks on the site that don't yet have top attractions - indicated by "top_ride = 1". Rather than have "<h2>Top Attractions</h2>" show up with no rides listed below I would ideally have the whole code above not show if there are no "top ride = 1" for a particular park.
Is this possible?
Thanks
Try this;
<?php
if($count = $query2->rowcount() < 1) {
echo "No results found";
} else {
echo "<h2>Top Attractions</h2>";
foreach($result2 as $row2) {
if(!empty($row2['name'])) {
echo "<li><h3>{$row2['name']}</h3></li>";
} else {
}
}
}
?>

Help with PHP While function

Why is this not working?
<?php
$select = "select * from messages where user='$u'";
$query = mysqli_query($connect,$select) or die(mysqli_error($connect));
$row = mysqli_num_rows($query);
$result = mysqli_fetch_assoc($query);
$title = mysqli_real_escape_string($connect,trim($result['title']));
$message = mysqli_real_escape_string($connect,trim($result['message']));
while(($result = mysqli_fetch_assoc($query))){
echo $title;
echo '<br/>';
echo '<br/>';
echo $message;
}
?>
where as this works -
<?php
echo $title;
?>
SORRY TO SAY, BUT NONE OF THE ANSWERS WORK. ANY OTHER IDEAS?
If your mysqli query is returning zero rows then you will never see anything printed in your while loop. If $title and $message are not set (because you would want reference them by $result['title'] & $result['message'] if that are the field names in the database) then you will only see two <br /> tags in your pages source code.
If the while loop conditional is not true then the contents of the while loop will never execute.
So if there is nothing to fetch from the query, then you won't see any output.
Does you code display anything, or skip the output entirely?
If it skips entirely, then your query has returned 0 rows.
If it outputs the <br /> s, then you need to check your variables. I could be wrong, not knowing te entire code, but generally in this case you would have something like
echo $result['title'] instead of echo $title
If $title and $message come from your mysql query then you have to access them through the $result array returned by mysqli_fetch_assoc.
echo $result['title'];
echo $result['message'];
Also if your using mysqli you'd be doing something like this:
$mysqli = new mysqli("localhost", "user", "password", "db");
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
print $row['title'];
}
$result->close();
}
Try this:
<?php
$result = mysql_query($query);
while($row = mysqli_fetch_assoc($result)){
echo $title.'<br/><br/>'.$message;
}
?>
Does this work;
<?php
$select = "select * from messages where user='$u'";
$query = mysqli_query($connect,$select) or die(mysqli_error($connect));
$row = mysqli_num_rows($query);
while(($result = mysqli_fetch_assoc($query))){
echo $result['title'];
echo '<br/>';
echo '<br/>';
echo $result['message'];
}
?>
Basically I've made sure that it's not picking the first result from the query & then relying on there being more results to loop through in order to print the same message repeatedly.

Categories