Database data appears in single line - php

I'm only getting started with PHP and I have this problem that the data that I wish to display inside a html table from my phpmyadmin database appears in a single row rather than in multiple rows
attached screenshot here
Here's the code:
try {
$conn = new PDO("mysql:host=127.0.0.1;port=3306;dbname=iwp_proj", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$query = "SELECT * FROM `blog`";
$sql = $conn->prepare($query) ;
$sql->execute();
$q = $sql->fetchAll(PDO::FETCH_ASSOC);
?>
<div align='center' style="background-color: white; opacity: 0.9">
<h1>REVIEWS</h1>
<table align='center' border='2' style=" border-collapse: collapse; bordercolor=#272121">
<thead align='center'>
<tr align='center'>
<th>Destination</th>
<th>Rating</th>
<th>Date of Journey</th>
<th>Comments</th>
</tr>
</thead>
<tbody>
<tr>
<?php foreach($q as $row){ ?>
<td><?php echo ($row['dest']); ?></td>
<td><?php echo ($row['rating']); ?></td>
<td><?php echo ($row['bdate']); ?></td>
<td><?php echo ($row['content']); ?></td>
<?php } ?>
</tr>
<br>
</tbody>
</table>
</div>
If I use the following code then nothing appears at all
<?php while($row = $sql->fetch(PDO::FETCH_ASSOC)) { ?>
<?php foreach($q as $row){ ?>
<td><?php echo ($row['dest']); ?></td>
<td><?php echo ($row['rating']); ?></td>
<td><?php echo ($row['bdate']); ?></td>
<td><?php echo ($row['content']); ?></td>
<?php } ?>
<?php } ?>
What am I doing wrong?

What happens is that you're iterating over "td" elements only, instead of doing it on the "tr" elements. The line which contains the forEach method should be extracted from its current scope. An example follows:
<?php foreach($q as $row){ ?>
<tr>
<td><?php echo ($row['dest']); ?></td>
<td><?php echo ($row['rating']); ?></td>
<td><?php echo ($row['bdate']); ?></td>
<td><?php echo ($row['content']); ?></td>
</tr>
<?php } ?>

Related

PHP MYSQL and updating data in a table

Good day, all!
I am trying to figure out how to get this chunk of code to do what I want but it eludes me.
What this script is supposed to do is to look through a database of consignment items, pick out the ones that have sold='n' and list them by item number. It displays all of the items in a list with a "Sell" link at the end of each item row. Once the Buyer Number and Amount are entered, the Sell link is clicked, the UPDATE updates the item and changes sold from 'n' to 'y' and once that happens, the item disappears from the list. It works exactly as I expect, except for one little issue that has eluded me. Each time the page is loaded, it doesn't change the amount and buyernumber, but it does change the sold from 'n' to 'y' for the first item only and after that it works as expected, adding the buyernumber and amount to all subsequent items. Until you browse away from it and then it won't do the first item correctly the next time you come back to the page. I have tried all kinds of things to make it work and this is the closest I have to what I want. Any help would be appreciated!
<?php
/**
* Sell an Item
*/
require "../config.php";
require "../common.php";
$success = null;
if (isset($_POST["submit"])) {
if (!hash_equals($_SESSION['csrf'], $_POST['csrf'])) die();
try {
$connection = new PDO($dsn, $username, $password, $options);
$itemnumber = $_POST["submit"];
$buyernumber = $_POST["buyernumber"];
$amount = $_POST["amount"];
$sql = "UPDATE consignitem SET sold='y', amount='$amount', buyernumber='$buyernumber' WHERE sold='n' AND itemnumber = $itemnumber";
$statement = $connection->prepare($sql);
$statement->bindValue(':itemnumber', $itemnumber);
$statement->bindValue(':buyernumber', $buyernuumber);
$statement->bindValue(':amount', $amount);
$statement->bindValue(':sold', $sold);
$statement->execute();
$success = "Item successfully updated";
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
try {
$connection = new PDO($dsn, $username, $password, $options);
$sql = "SELECT * FROM consignitem WHERE sold='n'";
$statement = $connection->prepare($sql);
$statement->execute();
$result = $statement->fetchAll();
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
?>
<?php require "templates/header.php"; ?>
<h2>Mark Items as Sold</h2>
<?php if ($success) echo $success; ?>
<style>
table, th, td {
border: 1px solid black;
}
</style>
<form method="post">
<input name="csrf" type="hidden" value="<?php echo escape($_SESSION['csrf']); ?>">
<table>
<thead>
<tr>
<th>Sale Number</th>
<th>Item Number</th>
<th>Lot Number</th>
<th>Category</th>
<th>Item Description</th>
<th>Reserve</th>
<th>Seller Number</th>
<th>Amount</th>
<th>Buyer Number</th>
<th>Sold</th>
<th>Paid</th>
<th>Date</th>
<th>Mark</th>
</tr>
</thead>
<tbody>
<?php foreach ($result as $row) : ?>
<tr>
<td><?php echo escape($row["salenumber"]); ?></td>
<td><?php echo escape($row["itemnumber"]); ?></td>
<td><?php echo escape($row["lotnumber"]); ?></td>
<td><?php echo escape($row["category"]); ?></td>
<td><?php echo escape($row["itemdescription"]); ?></td>
<td><?php echo escape($row["reserve"]); ?></td>
<td><?php echo escape($row["sellernumber"]); ?></td>
<td><?php echo escape($row["amount"]); ?><br><input type="text" name="amount" id="amount" size="8"></td>
<td><?php echo escape($row["buyernumber"]); ?><br><input type="text" name="buyernumber" id="buyernumber" size="12"></td>
<td><?php echo escape($row["sold"]); ?></td>
<td><?php echo escape($row["paid"]); ?></td>
<td><?php echo escape($row["date"]); ?> </td>
<td><button type="submit" name="submit" value="<?php echo escape($row["itemnumber"]); ?>">Sell</button></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</form>
<br>
<?php require "templates/footer.php"; ?>
You're repeating the same input names in all thr rows of the form. When the form is submitted, the $_POST variables will just contain the value from the last row of the form, not the row that the user clicked the submit button for.
You can give the inputs array-style names that are indexed by itemnumber. $_POST['buyernumber'] and $_POST['amount'] will then be arrays, and you can use $_POST['submit'] to get the appropriate array index.
You also need to use placeholders in the SQL that match the placeholders in bindValue(), rather than substituting the variables directly in the query.
<?php
if (isset($_POST["submit"])) {
if (!hash_equals($_SESSION['csrf'], $_POST['csrf'])) die();
try {
$connection = new PDO($dsn, $username, $password, $options);
$itemnumber = $_POST["submit"];
$buyernumber = $_POST["buyernumber"][$itemnumber];
$amount = $_POST["amount"][$itemnumber];
$sql = "UPDATE consignitem SET sold='y', amount= :amount, buyernumber= :buyernumber WHERE sold='n' AND itemnumber = :itemnumber";
$statement = $connection->prepare($sql);
$statement->bindValue(':itemnumber', $itemnumber);
$statement->bindValue(':buyernumber', $buyernuumber);
$statement->bindValue(':amount', $amount);
$statement->execute();
$success = "Item successfully updated";
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
try {
$connection = new PDO($dsn, $username, $password, $options);
$sql = "SELECT * FROM consignitem WHERE sold='n'";
$statement = $connection->prepare($sql);
$statement->execute();
$result = $statement->fetchAll();
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
?>
<?php require "templates/header.php"; ?>
<h2>Mark Items as Sold</h2>
<?php if ($success) echo $success; ?>
<style>
table, th, td {
border: 1px solid black;
}
</style>
<form method="post">
<input name="csrf" type="hidden" value="<?php echo escape($_SESSION['csrf']); ?>">
<table>
<thead>
<tr>
<th>Sale Number</th>
<th>Item Number</th>
<th>Lot Number</th>
<th>Category</th>
<th>Item Description</th>
<th>Reserve</th>
<th>Seller Number</th>
<th>Amount</th>
<th>Buyer Number</th>
<th>Sold</th>
<th>Paid</th>
<th>Date</th>
<th>Mark</th>
</tr>
</thead>
<tbody>
<?php foreach ($result as $row) : ?>
<tr>
<td><?php echo escape($row["salenumber"]); ?></td>
<td><?php echo escape($row["itemnumber"]); ?></td>
<td><?php echo escape($row["lotnumber"]); ?></td>
<td><?php echo escape($row["category"]); ?></td>
<td><?php echo escape($row["itemdescription"]); ?></td>
<td><?php echo escape($row["reserve"]); ?></td>
<td><?php echo escape($row["sellernumber"]); ?></td>
<td><?php echo escape($row["amount"]); ?><br><input type="text" name="amount[<?php echo escape($row["itemnumber"]); ?>]" size="8"></td>
<td><?php echo escape($row["buyernumber"]); ?><br><input type="text" name="buyernumber[<?php echo escape($row["itemnumber"]); ?>]" size="12"></td>
<td><?php echo escape($row["sold"]); ?></td>
<td><?php echo escape($row["paid"]); ?></td>
<td><?php echo escape($row["date"]); ?> </td>
<td><button type="submit" name="submit" value="<?php echo escape($row["itemnumber"]); ?>">Sell</button></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</form>
<br>
<?php require "templates/footer.php"; ?>

Using PHP to get data from MSQL and need a button in the foreach table

Let me post some code first so I can explain more of what I want to accomplish.
<?php
require "../config.php";
require "../common.php";
if (isset($_POST['submit'])) {
if (!hash_equals($_SESSION['csrf'], $_POST['csrf'])) die();
try {
$connection = new PDO($dsn, $username, $password, $options);
$sql = "SELECT * FROM saledata WHERE itemnumber = :itemnumber";
$itemnumber = $_POST['itemnumber'];
$statement = $connection->prepare($sql);
$statement->bindParam(':itemnumber', $itemnumber, PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetchAll();
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
?>
<?php require "templates/header.php"; ?>
<?php
if (isset($_POST['submit'])) {
if ($result && $statement->rowCount() > 0) { ?>
<h2>Results</h2>
<style>
table, th, td {
border: 1px solid black;
}
</style>
<table>
<thead>
<tr>
<th>Item Number</th>
<th>Sale Number</th>
<th>Lot Number</th>
<th>Item Description</th>
<th>Seller Number</th>
<th>Buyer Number</th>
<th>Sold</th>
<th>Sold</th>
<th>Paid</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php foreach ($result as $row) : ?>
<tr>
<td><?php echo escape($row["itemnumber"]); ?></td>
<td><?php echo escape($row["salenumber"]); ?></td>
<td><?php echo escape($row["lotnumber"]); ?></td>
<td><?php echo escape($row["itemdescription"]); ?></td>
<td><?php echo escape($row["sellernumber"]); ?></td>
<td><?php echo escape($row["buyernumber"]); ?></td>
<td><?php echo escape($row["sold"]); ?></td>
<td><?php echo escape($row["paid"]); ?></td>
<td><?php echo escape($row["amount"]); ?></td>
<td><?php echo escape($row["date"]); ?> </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php } else { ?>
<blockquote>No results found for <?php echo escape($_POST['itemnumber']); ?>.</blockquote>
<?php }
} ?>
<h2>Find item based on Item Number</h2>
<form method="post">
<input name="csrf" type="hidden" value="<?php echo escape($_SESSION['csrf']); ?>">
<label for="itemnumber">Item Number</label>
<input type="text" id="itemnumber" name="itemnumber"><br><br>
<input type="submit" name="submit" value="View Results">
</form>
<?php require "templates/footer.php"; ?>
(END)
This produces an HTML table containing the data in the database in rows. What I would like is a button at the beginning or end of the rows that will modify a field in that item's row. An example is the column for sold or not sold. What I would like is a button at either the beginning or the end of each row that modifies the "sold" column from N to Y for that item. I have tried to put a block of code in the code here at the end but I can't get it to do anything. I can get the button to show using the HTML tag but can't get it to actually do anything.
Here is the concept of the foreach:
<td><?php echo escape($row["sold"]); ?></td>
<td><?php echo escape($row["paid"]); ?></td>
<td><?php echo escape($row["amount"]); ?></td>
<td><?php echo escape($row["date"]); ?> </td>
<td>BUTTON and code to change Sold from N to Y</td>
</tr>
Any assistance would be greatly appreciated!
I know my stuff is probably elementary and not very efficient, but I have been working on this project for several weeks and never worked with a MYSQL database before.

php table not displaying contents and only creating table boxes

I would like the table to display all the values inside of it, but it is currently not displaying the values and only creating an empty table
[what the table is displayed as (image)][1]
$result = mysqli_query( $conn,'SELECT * FROM Pictures ');
$conn->close();
Html
<html>
<table border="2" style= "background-color: #84ed86; color: #761a9b; margin: 0 auto;"
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>image</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<?php
if( $result != null){
Result is not empty
while( $row1 = mysqli_fetch_assoc( $result ) ){
foreach ($row1 as $row){
?>
<tr>
<td><?php $row['id'] ?></td>
<td><?php $row['hname'] ?></td>
<td><?php $row['himage'] ?></td>
<td><?php $row['hdesc'] ?></td>
</tr>
<?php
}
}
}else{
echo "Something went wrong with the result";
}
?>
</tbody>
</table>
<?php //mysqli_close($conn); ?>
</body>
</html>
changed the out put to match the answer you gave but the output came out as picture 2 while my table is actually picture 3 any ideas
output:
table im trying to display
Display the data in this way:
<td><?php echo $row['id']; ?></td>
Try changing
<td><?php $row['id'] ?></td>
<td><?php $row['hname'] ?></td>
<td><?php $row['himage'] ?></td>
<td><?php $row['hdesc'] ?></td>
to
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['hname']; ?></td>
<td><?php echo $row['himage']; ?></td>
<td><?php echo $row['hdesc']; ?></td>
or the shorthand variant
<td><?= $row['id']; ?></td>
<td><?= $row['hname']; ?></td>
<td><?= $row['himage']; ?></td>
<td><?= $row['hdesc']; ?></td>
And as Samuel pointed out in a comment, are you sure there is a need for the extra foreach considering you're already looping with the while?
Update: OP have you tried the following?
while( $row = mysqli_fetch_assoc( $result ) ){
//removed foreach()
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['hname']; ?></td>
<td><?php echo $row['himage']; ?></td>
<td><?php echo $row['hdesc']; ?></td>
</tr>
<?php
}
}else{
Update 2 OP wishes to have the image load instead of showing the raw URL.
To do this, we need to use an actual image tag and insert the url into the src.
I assume that this line is the image URL
<td><?php echo $row['himage']; ?></td>
So change it to
<td> <img src="<?php echo $row['himage']; ?>" > </td>

PHP not displaying last column in table

I am trying to display all the info in the table but when I query the information then put it into a PHP table it doesn't show any data in the last table.
Here is my PHP code for the table
<table border='1'>
<tr>
<th>Ticket ID</th>
<th>Username</th>
<th>Message</th>
<th>Date</th>
<th>Error #</th>
<th>Priority</th>
</tr>
<?php
if(!$query){
die('Invalid query: ' .mysql_error());
}
while ($row = mysql_fetch_array($query)) { ?>
<tr>
<td><?php echo $row['TicketID']; ?></td>
<td><?php echo $row['Message']; ?></td>
<td><?php echo $row['Date']; ?></td>
<td><?php echo $row['Error']; ?></td>
<td><?php echo $row['Priority']; ?></td>
</tr>
<?php } ?>
</table>
Here is the PHP code for query
<?php
$server = mysql_connect("localhost", "root", "**password**");
$db = mysql_select_db("minecraft", $server);
$query = mysql_query("SELECT * FROM tickets");
?>
All of my row names are correct but it doesn't want to put the data into that column.
Here is my table structure
You Omitted
<td><?php echo $row['Username']; ?></td>
that should be after
<td><?php echo $row['TicketID']; ?></td>

PHP show MySQL table data PDO

I'm a PHP noob, I keep getting this error:
Parse error: syntax error, unexpected end of file...
The line it points to is at the very last line. My 'header.php' declares the !DOCTYPE html and my 'config.php' holds the database properties.
Any help would be greatly appreciated.
<?php
include 'config.php';
include 'header.php';
?>
<div id='wrapper'>
<div style='height:50em;width:100%;z-index:10;margin-top:1em;text-align:left;'>
<table id='mainDPUtable'>
<th class='cen'>NUM</th>
<th class='cen'>TYP</th>
<th class='cen'>LVL</th>
<th class='cen'>Job No.</th>
<th class='cen'>Responsible</th>
<th class='cen'>Rep</th>
<th class='cen'>Initiated</th>
<th class='cen'>Age</th>
<th class='cen'>Part Number</th>
<th class='cen'>Qty</th>
<th class='cen'>Description</th>
<th class='cen'>Location</th>
<th class='cen'>Complete</th>
<?php
$db = new PDO("mysql:host=localhost;dbname=".$dbname.",".$user.",".$pswd);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $db->prepare("SELECT NUM, TYP, LVL, JOBNO, RESP, REP, DATE_INITIATED, AGE, PARTNO, QTY, DESCRIPTION, LOC FROM ".$dbtable);
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$num=$row["NUM"];
$typ=$row["TYP"];
$lvl=$row["LVL"];
$jobNo=$row["JOBNO"];
$resp=$row["RESP"];
$rep=$row["REP"];
$date_initiated=$row["DATE_INITIATED"];
$age=$row["AGE"];
$partNo=$row["PARTNO"];
$qty=$row["QTY"];
$description=$row["DESCRIPTION"];
$loc = $row["LOC"];
$comp=$row["COMP"];
?>
<tr>
<td><?php echo $num; ?></td>
<td><?php echo $typ; ?></td>
<td><?php echo $lvl; ?></td>
<td><?php echo $jobNo; ?></td>
<td><?php echo $resp; ?></td>
<td><?php echo $rep; ?></td>
<td><?php echo $date_initiated; ?></td>
<td><?php echo $age; ?></td>
<td><?php echo $partNo; ?></td>
<td><?php echo $qty; ?></td>
<td><?php echo $description; ?></td>
<td><?php echo $loc; ?></td>
<td><input type='button' id=<?php echo 'btn'.$num; ?> value='Complete'/></td>
</tr>
<?php}?>
</table>
</div>
</div>
</body>
</html>
Missing spaces:
<?php}?>
should be
<?php } ?>
^-^--

Categories