How to echo each row from mySQLi query using PHP? - php

The following query returns all rows from the campaign table that have the user_id of 1:
SELECT * FROM campaign WHERE user_id=1
In the case of testing this is two results. How would I be able to echo a set column from each of the rows. For example, I want to echo the campaign_name from each of the results. I have tried various methods however, I have had no success.
My end goal would be something like this:
<?php foreach($queryRow as $row) { ?>
<li>
<a>
<div>
<p><?php echo($row['campaign_name']); ?></p>
<p>
Description Text
</p>
</div>
</a>
</li>
<?php } ?>
I'm quite at lost with this so I apologise if my intended result is completely off...

Try this:
$qry = "SELECT * FROM campaign WHERE user_id=1";
$res = mysqli_query($conn, $qry);
if(mysqli_num_rows($res) > 0) // checking if there is any row in the resultset
{
while($row = mysqli_fetch_assoc($res)) // Iterate for each rows
{
?>
<li>
<a>
<div>
<p><?php echo($row['campaign_name']); ?></p>
<p>
Description Text
</p>
</div>
</a>
</li>
<?php
}
}
It will iterate for each row in the resultset.

I looked into the documentation as Oldskool kindly suggested and realised I was using the wrong method to create an array. I instead use the fetch_all feature of the mysqli_results class to create a multidimensional array with my results. Then I was able to use the following code to echo out the results:
<!DOCTYPE html>
<html>
<body>
<?php
include('inc/database_initiation.php');
//print_r($userCampaigns);
foreach ($userCampaigns as $row) {
//echo $row[2];
//echo $row[4];
echo $row['campaign_name'];
echo '<br>';
echo $row['promotion_coins'];
echo '<br>';
}
?>
</body>
</html>
The include 'inc/database_initiation is as follows'
<?php
session_start();
include_once 'userManagement/dbconnect.php';
if(!isset($_SESSION['userSession']))
{
header("Location: login.php");
}
$query = $MySQLi_CON->query("SELECT * FROM users WHERE user_id=".$_SESSION['userSession']);
$userRow=$query->fetch_array();
$campaignQuery = $MySQLi_CON->query("SELECT * FROM campaign WHERE user_id=1");
$userCampaigns = $campaignQuery->fetch_all(MYSQLI_ASSOC);
//$MySQLi_CON->close();
?>

Related

How to retrieve/display multi columns single row from database to different html tags

OK so what I'm am trying to do is retrieve multiple columns of data from a single row in mysql database and basically place the data of the different columns into multiple places on my html code such as in "p" and "td" tags to display on webpage.
I have successfully been able to display the "description"(description is the name of 1 of the database columns) inside the "p" tags using PHP but I don't know how to display any other columns of the database into other html tags such as the "td" tags. There is probably going to be a total of roughly 10 columns of text in database I want to display in the webpage but again where it's displaying is in various html tags and not a table which is what I keep finding when researching and tired of banging my head on the desk. There is a small example below. I'm learning as I go so any help would be great. Thank you!
<?php
$sql = "SELECT * FROM Parts;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
?>
<div class="description">
<h3>Descrption</h3>
<p>
<?php
if($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['Description'];
}
}
?>
</p>
</div>
<td>
<?php
if($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row["Material"];
}
}
?>
</td>
Try this
<?php
$sql = "SELECT * FROM Parts;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<div class="description">
<h3>Descrption</h3>
<p>
<?php
echo $row['Description'];
?>
</p>
</div>
<td>
<?php
echo $row["Material"];
?>
</td>
<?php
}
}
?>
My preference is to fetch all rows first, rather then fetching rows while rendering html, otherwise if there is an error fetching rows, it becomes mixed in with your html
I also recommend using htmlentities() to escape any html data (assuming that description or material does not already include valid html
<?php
$sql = "SELECT * FROM Parts;";
$result = mysqli_query($conn, $sql);
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
?>
<div class="description">
<h3>Descrption</h3>
<p>
<?php
foreach ($rows as $row) {
echo htmlentities($row['Description']);
}
?>
</p>
</div>
<td>
<?php
foreach ($rows as $row) {
echo htmlentities($row["Material"]);
}
?>
</td>

Inserting PHP database into HTML table

Hey I've recently been making a website and want to display the data from my database in a grid format opposed to it just listing down the page.
Here is my code right now:
<p>
<a href="pokemondetails.php?dex=<?php echo $row['dex'];?>">
<?php echo $row['name']; ?>
<br>
<img src="assets/<?php echo $row['dex']?>.png">
</a>
</p>
I was wondering how I would go about creating a for loop to allow the data from this database in conjunction with the image to span across the page with 7 columns and however many rows down until it reaches the end of the database.
Thanks!
<?php
$query = "Select * from tablename";
$bind = $conn->query($query);
if ($bind->num_rows > 0){
while ($row = $bind->fetch_assoc()){
?>
<p>
<a href="pokemondetails.php?dex=<?php echo $row['dex'];?>">
<?php echo $row['name']; ?>
<br>
<img src="assets/<?php echo $row['dex']?>.png">
</a>
</p>
<?php
}
}
?>
Try this, I just add while loop until End Of file (EOF table)

Displaying content but not the latest one

I have these codes to display content on my website.
Index.php
$rest = new rest;
$list = $rest->fetch_all();
<?php foreach ($rest->fetch_all() as $rest) { ?>
<br>
<a href="episode.php?id=<?php echo $rest['cast_id']; ?>">
#<?php echo $rest['cast_id']; ?>: <?php echo $rest['cast_title']; ?>
<br>
<font size="2" color="red">
<?php echo $rest['cast_about']; ?></font></a><br>
<br><div class="divider"> </div><br>
<?php } ?>
And include.php
class rest {
public function fetch_all(){
global $pdo;
$query = $pdo->prepare("SELECT * FROM podcast ORDER BY cast_id DESC");
$query->execute();
return $query->fetchAll();
} }
Please can someone tell me how I can get this to show results but not the latest result?
All fields are numbered using an ID tag in mysql.
On my site I have the latest entry listed above this list so I do not require the latest one appearing here.
Please help.
Thank you.
The easiest way to do this is to discard the row in the application. You can do it in SQL by using a calculated limit. Calculate it as (SELECT COUNT(*) FROM podcast) - 1.
Or:
SELECT *
FROM podcast
EXCEPT
SELECT TOP 1 *
FROM podcast
ORDER BY cast_id ASC
Excluding the last row.
You can either use array_shift or array_pop depending on your query sorting as shown bellow:
Assuming the latest result is the first raw on your query result.
$rest = new rest;
$list = $rest->fetch_all();
$latest = array_shift($list);
<?php foreach ($list as $rest) { ?>
<br>
<a href="episode.php?id=<?php echo $rest['cast_id']; ?>">
#<?php echo $rest['cast_id']; ?>: <?php echo $rest['cast_title']; ?>
<br>
<font size="2" color="red">
<?php echo $rest['cast_about']; ?></font></a><br>
<br><div class="divider"> </div><br>
<?php } ?>
If it's the last raw that you need to hide, then use array_pop

Output Name in PHP From mysql Database

I have a list of names in a database that i want to display one by one
(also for bonus points, another column in the database is a Boolean value for if a task is completed or not. if this is true i want the css content box background to be green instead of red.)
so how can i select a name from row one, put it to a PHP variable, then select the value from the "Name" column in row 2 and put that to another PHP variable or the next item in the array?
thanks for any help!
<html>
<head>
<title>Title</title>
<link rel="stylesheet" type="text/css" href="mngPWinCSS.css"/>
</head>
<body>
<?php
$dsn ='mysql:host=****.******.com;dbname=o****_**n';
$username='********';
$password ='******';
mysql_connect('localhost',$username,$password);
$query=mysql_query("SELECT Name FROM CLOAS_Team LIMIT 0,1");
$bob="dkajfk";
$url=$_SERVER['REQUEST_URI'];
header("Refresh: 60; URL=$url");
$com[1]="i";
$com[2]="i";
$com[3]="i";
$com[4]="i";
$com[5]="i";
$com[6]="i";
$name=mysql_fetch_array($query);
?>
<div id="content">
<img src="logjpg.JPG" alt="Smiley face" height="50" width="200">
<h3>CLOAS Tracker</h3>
</div>
<div id="Content">
<?php
?>
<div id="complete">
<h3names>
<?php
echo $name['Name'];
?>
</h3names>
</div>
<div id="incomplete">
<h3names>Name2</h3names>
</div>
</div>
</body>
</html>
First you need to change your SELECT query to select all of the rows that you wish to display, perhaps by taking off the LIMIT clause. Something like this;
$result=mysql_query("SELECT Name FROM CLOAS_Team");
(This will get you all of the names in your table.)
Next, you need to loop through the results you got from this query, like so;
$names = array();
while($row = mysql_fetch_assoc($result))
{
$names[] = $row['Name'];
}
This will put them into the array $names for you, which you can then work with. Instead of putting them into the array, you might want to output them immediately, perhaps like this;
while($row = mysql_fetch_assoc($result))
{ ?>
<div>
<h3>
<?php
echo $row['Name'];
?>
</h3>
</div>
<?php } ?>
However, you have many more errors in your code. Such as;
You can't just invent html elements called <h3names>
I doubt that you want to set the id attribute to 'incomplete'. An id should be unique, I expect you should be putting this in as a class (class = "incomplete")
I don't think your line header("Refresh: 60; URL=$url"); will do anything as your headers have already been sent to the page. If you want this line to work, it needs to be right at the top, BEFORE any output has been sent to the browser.
And for the bonus point, include the 'Completed' field in your query (if that is what it is called) and use this to add a style to each <div> element that you display in your loop. So your query might become;
$result=mysql_query("SELECT Name, Completed FROM CLOAS_Team");
And your loop would now be like this;
while($row = mysql_fetch_assoc($result))
{ ?>
<div style = "background-color:<?php echo $row['Completed'] == true ? 'green' : ' red'; ?>">
<h3>
<?php
echo $row['Name'];
?>
</h3>
</div>
<?php } ?>

How to return a specific row in PHP and MySQL?

I am trying to add a mouseover hover which basically works on the first MySQL returned query. However it will not work. It does not recognise my IF ELSE statement and it just returns the ELSE command.
My data is like
gallery
----------------------
id sku img types
1 454_red front.jpg F
2 454_red back.jpg F
3 452_red front.jpg F
4 452_red back.jpg F
5 452_red a1.jpg S
6 452_red a2.jpg S
My PHP
<?
$imgsql=mysql_query("SELECT * FROM `gallery` WHERE `gallery`.`sku` = '".$r['sku']."' ORDER BY `gallery`.`type` ASC");
while($rimg=mysql_fetch_array($imgsql)){
?>
<? if($rimg == $rimg['0']){ ?>
<div>
<img src="//super.cdn.com/<?=$r['sku']?>/<?=$rimg['img']?>.jpg" onmouseover="this.src='//super.cdn.com/<?=$r['sku']?>/back.jpg'" onmouseout="this.src='//super.cdn.com/<?=$r['sku']?>/<?=$rimg['img']?>.jpg'"/>
</div>
<? } else { ?>
<div>
<img src="//super.cdn.com/<?=$r['sku']?>/<?=$rimg['img']?>.jpg"/>
</div>
<? } ?>
<? } ?>
The $r["sku"] is called at the top of the code, this sits inside a product listing loop.
To make it simple, then take another variable say counter or flag as below
<?
$count = 1;
$imgsql=mysql_query("SELECT * FROM `gallery` WHERE `gallery`.`sku` = '".$r['sku']."' ORDER BY `gallery`.`type` ASC");
while($rimg=mysql_fetch_array($imgsql)){
?>
<? if($count==1){ ?>
<div>
<img src="//super.cdn.com/<?=$r['sku']?>/<?=$rimg['img']?>.jpg" onmouseover="this.src='//super.cdn.com/<?=$r['sku']?>/back.jpg'" onmouseout="this.src='//super.cdn.com/<?=$r['sku']?>/<?=$rimg['img']?>.jpg'"/>
</div>
<? } else { ?>
<div>
<img src="//super.cdn.com/<?=$r['sku']?>/<?=$rimg['img']?>.jpg"/>
</div>
<? } ?>
<?
$count = 0;
}
?>

Categories