Output database variable with multiple line breaks - php

I've read about the nl2br() command but they echo out the variable to make it work but my variable is inside a list that I echo out.
Should I somehow put the nl2br() command in my if statement where I'm setting up the output or should I be looking somewhere else for my answer.
I have made 2 extra detail variables to output so I get 3 lines of text for the description of my product but there has to be a better way of doing it than that. I would think 1 detail variable with all the info would be the preferred way of doing it
I have tried to search for it but I'm afraid I'm just not asking the right question so any help in the right direction is appreciated.
<?php require_once './connections/connect_mysqli.php';
$conn = dbConnect('read');
$sql = "SELECT * FROM products ORDER BY id ASC LIMIT 6 ";
$result = $conn->query($sql) or die($conn->error);
$i = 0;
$flatlist = "";
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$id = $row["id"];
$product_name = $row["product_name"];
$details = $row["details"];
$details2 = $row["details2"];
$details3 = $row["details3"];
$price = $row["price"];
if ($i % 4 == 0) {
$flatlist .='<tr><td width="250px" align="center"><img src="images/' . $id . '.jpg"><br/>
<p style=color:blue font-size=14px;>' . $product_name . '</p><br/>
<p style=font-size:14px;>' . $details . '</p><br />
' . $details2 . '<br />
' . $details3 . '<br />
<p style=font-size:14px;>$' . $price . '</p><br />
<input type="button" value="Order" style=color:blue></td>';
} else {
$flatlist .= '<td width="250px" align="center"><img src="images/' . $id . '.jpg"><br/>
<p style=color:blue font-size=14px;>' . $product_name . '</p><br />
<p style=font-size:14px;>' . $details . '</p><br />
' . $details2 . '<br />
' . $details3 . '<br />
<p style=font-size:14px;>$' . $price . '</p><br />
<input type="button" value="Order" style=color:blue></td>';
}
$i++;
}
$flatlist .= '</tr></table>';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Flats</title>
</head>
<body>
<?php require 'includes/skyline.php'; ?>
<?php require 'includes/menu.php'; ?>
<table width="1200" border="0" align="center">
<tr>
<?php echo $flatlist ?>
</tr>
</table>
<?php require 'includes/footer.php';?>

Want to point out you close the details <p> before the 2nd and 3rd lines. You probably want to close that after third line.
<p style=font-size:14px;>' . $details . '<!-- remove here: </p> --><br />
' . $details2 . '<br />
' . $details3 . '<br /><!-- add here: --></p>
If you keep your same database structure, you can define into one variable after retrieving like:
$details = $row["details"] . '<br/>' . $row['details2'] . '<br/>' . $row['details3'];
And then just refer back to $details later on.
Why don't you want to use nl2br()? This would allow you to store multiple lines all into details column. Then you would just use:
$details = nl2br( $row["details"] );`
Here are my edits to your code:
<?php require_once './connections/connect_mysqli.php';
$conn = dbConnect('read');
$sql = "SELECT * FROM products ORDER BY id ASC LIMIT 6 ";
$result = $conn->query($sql) or die($conn->error);
$i = 0;
$flatlist = "";
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$id = $row["id"];
$product_name = $row["product_name"];
$details = $row["details"] . '<br/>' . $row['details2'] . '<br/>' . $row['details3'];
$price = $row["price"];
if ($i % 4 == 0) {
$flatlist .='<tr><td width="250px" align="center"><img src="images/' . $id . '.jpg"><br/>
<p style=color:blue font-size=14px;>' . $product_name . '</p><br/>
<p style=font-size:14px;>' . $details . '</p><br />
<p style=font-size:14px;>$' . $price . '</p><br />
<input type="button" value="Order" style=color:blue></td>';
} else {
$flatlist .= '<td width="250px" align="center"><img src="images/' . $id . '.jpg"><br/>
<p style=color:blue font-size=14px;>' . $product_name . '</p><br />
<p style=font-size:14px;>' . $details . '</p><br />
<p style=font-size:14px;>$' . $price . '</p><br />
<input type="button" value="Order" style=color:blue></td>';
}
$i++;
}

Related

PHP display images dynamically in grid pattern

I'm new to php and I'm working with a tutorial about showing images dynamically on the page, it works fine but it shows them vertically and I would like them to be horizontal. I created a page with code to do that but I can't seem to figure out where to insert the code to get the images to show.
Thanks for any help.
Vertical output looks like this
$dynamicList = "";
$sql = mysql_query("SELECT * FROM products ORDER BY date_added ASC LIMIT 6");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$details = $row["details"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
$dynamicList .= '<table width="1000px" border="0" cellspacing="0" cellpadding="6" align="center">
<tr>
<td width="1000px" align="center"><img style="border:#666 0px solid;" src="images/' . $id . '.jpg" width="50%" height="50%" alt="' . $product_name . '" width="77" height="102" border="1" /></td>
<td width="83%" valign="top">' . $product_name . '<br />
$' . $price . '<br /> $' . $details . '<br />
order</td>
</tr>
</table>';
}
mysql_close();
?>
Grid Output
$sql = mysql_query("SELECT * FROM products ORDER BY id ASC LIMIT 15");
$i = 0;
// Establish the output variable
$dynamiclist = '<table width="1000px" border="1" cellspacing="2" cellpadding="10" align="center">';
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$product_name = $row["product_name"];
$details = $row["details"];
$price = $row["price"];
if ($i % 3 == 0) { // if $i is divisible by our target number (in this case "3")
$dynamiclist .= '<tr><td>' . $product_name . '</br>' . $details . '</br>' . $price . '</td>';
} else {
$dynamiclist .= '<td>' . $product_name . '</td>';
}
$i++;
}
$dynamiclist .= '</tr></table>';
?>
I got it figured out, Thanks for the help.
$sql = mysql_query("SELECT * FROM products ORDER BY id ASC LIMIT 15");
$i = 0;
// Establish the output variable
$dynamiclist = "";
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$product_name = $row["product_name"];
$details = $row["details"];
$price = $row["price"];
if ($i % 4 == 0) { // if $i is divisible by our target number (in this case "3")
$dynamiclist .= '<tr><td width="250px" align="center"><img src="images/' . $id . '.jpg"><br/>' . $product_name . '<br />
' . $details . '<br /> $' . $price . '<br />
order</td>';
} else {
$dynamiclist .= '<td width="250px" align="center"><img src="images/' . $id . '.jpg"><br/>' . $product_name . '<br />
' . $details . '<br /> $' . $price . '<br />
order</td>';
}
$i++;
}
$dynamiclist .= '</tr></table>';
?>

php Undefined offset 1

I seem to be getting Undefined offset 1 error when I hit submit. I have been trying to play with the numbers but nothing seems to help. I added a fourth column right after the commented last name. Before the addition the code worked. I realized later on that I needed that third column. Ever since then I get an error and can not update the sql table.
Thank you in advance,
Avi
<!DOCTYPE html>
<?php
echo '<link rel="stylesheet" type="text/css" href="css/newStyle.css"></head>';
session_start();
if (isset($_SESSION['loggedIn']) && ($_SESSION['loggedIn'] == true) && $_SESSION['admin'] == true) {
echo "<br><h3>Welcome to the administrative area Prof. " . $_SESSION['firstname'] . "!</h3><br><br>";
} else {
//echo "<br>Please log in first to see this page.";
header ('Location: index.php');
}
require_once 'login.php';
$connection = new mysqli($hn,$un,$pw,$db);
if($connection->connect_error) die($connection->connect_error);
if(isset($_POST['submit'])){
for($i = 0; $i < $_POST['totalGrades']; $i++){
echo $i . ': ' . $_POST['grade' .$i] . '<br>';
$parts = explode("|", $_POST['grade' .$i]);
$newGrade = "UPDATE Grades SET grade = '" . $parts[1] . "' WHERE gradeID = " .$parts[0];
$result = $connection->query($newGrade);
}
}
$username = "";
$courseId = "";
$grade = "";
$courseName = "";
?>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="">
</head>
<body>
<form method= "post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<link rel="stylesheet" href="css/style.css">
<?php
// $courseSct =
"SELECT username, courseName, grade, gradeID FROM Courses\n"
// . "JOIN Grades\n"
// . "ON courses.courseId = Grades.courseId";
$courseSct =
"SELECT u.firstname, u.lastname, c.courseName, g.grade "
. " FROM Grades g "
. " INNER JOIN Courses c ON c.courseID = g.courseID "
. " INNER JOIN Users u ON u.userID = g.userID "
. " WHERE c.professorID = " .$_SESSION['userID'];
$result = $connection->query($courseSct);
$rows = $result->num_rows;
echo
"<table border = '1' width = '50%'>"
. "<caption><h2>Grades Table</h2></caption>"
. "<tr>"
. '<th>First Name</th>'
. "<th>Last Name</th>"
. "<th>Course Name</th>"
. "<th>Grade</th>"
//. "<th>New Value</th>"
. "</tr>";
for($j = 0; $j < $rows; ++$j) {
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
echo
"<tr>" .
"<td>" . $row[0] . "</td>" . //First Name
"<td>" . $row[1] . "</td>" . //Last Name
"<td>" . $row[2] . "</td>";
"<td>"; //Grade
echo '<select name="grade' . $j . '" size="1" id="' . $row[3] . '">';
echo '<option value="select">Select</option>';
$letterGrade = 'A';
for($x = 0; $x < 6; $x++) {
echo '<option value="' . $row[3] . '|' . $letterGrade . '"';
if($letterGrade == $row[3]) {
echo ' selected';
}
echo '>' . $letterGrade++ . '</option>';
}
echo '</select><br>'. "</td>" . "</tr>";
}
echo "</table>";
?>
<input type="hidden" name="totalGrades" value="<?php echo $rows;?>">
<br>
<input type="submit" name="submit" value="Submit">
<br>
</form>
<a href='index.php?logout'><br>click here to log out<br></a>
</body>
</html>
Have you tried a foreach instead?
if(isset($_POST['submit'])){
foreach($_POST['totalGrades'] as $key => $value) {
echo $key . ': ' . $value . '<br>';
$parts = explode("|", $value);
$newGrade = "UPDATE Grades SET grade = '" . $parts[1]
. "' WHERE gradeID = " .$parts[0];
$result = $connection->query($newGrade);
}
}

Use PHP variable in href inside of html inside of php?

So I'm trying to make a cart for my website (nothing too special, uni project).
Currently I have
$product_id = $row["ID"];
$product_name = $row['name'];
$product_price = $row['price'];
$product_image = $row['img'];
$imgurl = ".\img\\".$product_image;
if ($i % 3 == 0) { // if $i is divisible by our target number (in this case "3")
$dyn_table .= '<tr><td align="center" valign="middle" width="350">'. "<img src=$imgurl width='100' hieght='100'> <br />" . $product_name . '<br /> &pound'.$product_price . '<br /><a href="./cart.php?product="$product_id"&action=add" />Add to Card</a></td>';
} else {
$dyn_table .= '<td align="center" valign="middle" width="350">'. "<img src=$imgurl width='100' hieght='100'> <br />" . $product_name . '<br /> &pound'.$product_price . '<a href="./cart.php?product=$product_id&action=add" />Add to Card</a></td>';
I need to have the product ID inserted in href where I have $product_id
<a href="./cart.php?product=$product_id&action=add" />Add to Card</a>
Currenly, it loads the links as domain.com/cart.php?product=$product_id&action=add
you can use variable name between quotes
provided if it is a single quoted you have to put {} around variable
else if it is a double quotes you can directly use the varibale
if ($i % 3 == 0) {
$dyn_table .= "<tr><td align='center' valign='middle' width='350'>". "<img src=$imgurl width='100' hieght='100'> <br />" . $product_name . "<br /> &pound".$product_price . "<br />
<a href='./cart.php?product={$product_id}&action=add' />Add to Card</a></td>";
} else {
$dyn_table .= "<td align='center' valign='middle' width='350'>". "<img src=$imgurl width='100' hieght='100'> <br />" . $product_name . "<br /> &pound".$product_price . "<a href='./cart.php?product={$product_id}&action=add' />Add to Card</a></td>";
}
The variable has to be extracted from the string, in PHP, so:
<a href="./cart.php?product='.$product_id.'&action=add" />Add to Card</a>
Like you did for your other variables.
this:
$dyn_table .= '<tr><td align="center" valign="middle" width="350">'."<img src=$imgurl width='100' hieght='100'><br />" . $product_name.'<br /> &pound'.$product_price .'<br /><a href="./cart.php?product=" .$product_id. "&action=add." />Add to Card</a></td>';
Your original problem was that you didn't jump out of single quotes properly to add $product_id in, however there's another instrumental problem in your code.
You should either use all '' single quotes or all "" double quotes, not a combination of both. It makes it hard to read and is unnecessary regardless.
Therefore, it should be either
$dyn_table .= '<tr><td align="center" valign="middle" width="350"><img src="' . $imgurl . '" width="100" hieght="100"> <br />' . $product_name . '<br /> £' . $product_price . '<br /><a href="./cart.php?product=' . $product_id . '&action=add" />Add to Card</a></td>';
or
$dyn_table .= "<tr><td align=\"center\" valign=\"middle\" width=\"350\"><img src=\"$imgurl\" width=\"100\" hieght=\"100\"> <br />$product_name<br /> £$product_price<br /><a href=\"./cart.php?product=$product_id&action=add\" />Add to Card</a></td>";
In this case, I'd probably use single quotes so I don't have to escape all the double quotes in the HTML, or perhaps even a heredoc, but I won't get into those for now.
Your code for single quotes would be
if ($i % 3 == 0) { // if $i is divisible by our target number (in this case "3")
$dyn_table .= '<tr><td align="center" valign="middle" width="350"><img src="' . $imgurl . '" width="100" height="100"> <br />' . $product_name . '<br /> £' . $product_price . '<br /><a href="./cart.php?product=' . $product_id . '&action=add" />Add to Card</a></td>';
} else {
$dyn_table .= '<td align="center" valign="middle" width="350"><img src="' . $imgurl . '" width="100" hieght="100"> <br />' . $product_name . '<br /> £' . $product_price . '<a href="./cart.php?product=' . $product_id . '&action=add" />Add to Card</a></td>';
I'd suggest you look up heredocs though, you may find those easier.

Session to echo a row retrieved from database

I have a system where users can send and receive messages and I need to make a way for them to directly reply to the messages.
This is a test code to make the page echo what should be retrieved and set as a session, but it is not echoing anything.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Clan Kaos ● View Post</title>
<link rel="stylesheet" type="text/css" href="include/style/content.css" />
</head>
<body>
<?php
include ("include/header.html");
include ("include/sidebar.html");
include ("include/testpost.html");
?>
<div class="container">
<?php session_start();
require_once('appvars.php');
require_once('connectvars.php');
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$query = "SELECT username FROM kaoscraft_user WHERE user_id = '" . $_SESSION['user_id'] . "'";
$data = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($data);
$username1 = $row['username'];
// Grab the profile data from the database
$query = "SELECT `to`, `from`, rank, gender, picture, title, msg FROM kaoscraft_pm WHERE `to` = '$username1' ORDER BY msg_id DESC";
$data = mysqli_query($dbc, $query);
$gender = $row['gender'];
$username2 = $_SESSION['reply'];
while ($row = mysqli_fetch_array($data)) {
$_SESSION['reply'] = $row['from'];
echo '<div class="viewpost">';
echo '<div class="vpside">';
if(!empty($row['picture'])) {
echo '<img class="pictest" src="' . MM_UPLOADPATH . $row['picture'] . '" alt="' . MM_UPLOADPATH . 'nopic.png' . '" />';
}
if(!empty($row['from'])) {
echo '<p>From:<br />' . $row['from'] . '</p>';
echo '<p> ' . $username2 . '</p>';
}
if(!empty($row['rank'])) {
echo '<p>Rank:<br />' . $row['rank'] . '</p>';
}
if(!empty($row['gender'])){
echo '<p>Gender:<br /> ' . $row['gender'] . '</p>';
}
echo '</div>';
if(!empty($row['title'])) {
echo'<h4><u>' .$row['title']. '</u></h4>';
}
if(!empty($row['msg'])) {
echo '<p class="">' . $row['msg'] . '</p>';
}
echo '<div class="sig">';
if(!empty($row['bio'])) {
echo '<p>' . $row['bio'] . '</p>';
}
echo '</div>';
echo '</div><br />';
}
mysqli_close($dbc);
?>
I need the session $_SESSION['reply'] to be set as the variable $username2 and it does not seem to be working.
Move session_start(); on top of the PHP code. You are accessing $_SESSION['reply'] = $username2; before that which wont work.
What I was doing was incorrect. I had to move
$_SESSION['reply'] = $row['from'];
$username2 = $_SESSION['reply'];`
from after the query to
while ($row = mysqli_fetch_array($data)) {
$_SESSION['reply'] = $row['from'];
$username2 = $_SESSION['reply'];`
and then it echo'd correctly. Thanks for the help from everyone :)

Update a variable on click

basically I've written the following but I'm wondering what the best way to get $message_id = to the $row['id'] you click on to view an inbox message. If I just statically set $message_id = to say 39 and click on the row that's $row['id'] is 39 it'll open the message.
Basically what it does is list inbox messages I have, and anchor tag them with its row id to be used in the header to show the full contents of that message.
<p>
<?php
$message_id = "39";
if (isset($_GET[$message_id]) && empty($_GET[$message_id])) {
$username = $user_data['username'];
$get_message = mysql_query("SELECT * FROM `users_inbox` WHERE `id` = '$message_id' AND `send_to` = '$username'");
$get_message_result = mysql_fetch_array($get_message);
echo '<h1><u>' . $get_message_result['subject'] . '</u></h1>';
echo $get_message_result['sent_from'] . '<br />';
echo $get_message_result['body'] . '<br />';
echo 'Back';
}
$username = $user_data['username'];
$result = mysql_query("SELECT * FROM `users_inbox` WHERE `send_to` = '$username'");
?>
<table border="1">
<tr>
<td>From</td>
<td>Subject</td>
<td>Date</td>
</tr>
<?php
while($row = mysql_fetch_array($result))
{
echo
'<tr>' .
'<td>' . $row['sent_from'] . '</td>' .
'<td>' . $row['subject'] . '</td>' .
'<td>' . $row['post_date'] . '</td>' .
'</tr>';
}
?>
</table>
</p>
Anyone know if this is even possible, as I know code is read from top to bottom and as far as I'm aware you cant go back upwards at all.
I assume that the $user_data['username'] is set or available,if yes then you could pass a variable name of you choice which points the message id instead of sending only the id (eg: i am setting it as msg_id ), Now you can access the message id via $_GET['msg_id']
<p>
<?php
$username = $user_data['username'];
if ( isset( $_GET['msg_id'] ) ) {
$get_message = mysql_query("SELECT * FROM `users_inbox` WHERE `id` = '$message_id' AND `send_to` = '$username'");
$get_message_result = mysql_fetch_array($get_message);
echo '<h1><u>' . $get_message_result['subject'] . '</u></h1>';
echo $get_message_result['sent_from'] . '<br />';
echo $get_message_result['body'] . '<br />';
echo 'Back';
}else{
$result = mysql_query("SELECT * FROM `users_inbox` WHERE `send_to` = '$username'");
?>
<table border="1">
<tr>
<td>From</td>
<td>Subject</td>
<td>Date</td>
</tr>
<?php
while($row = mysql_fetch_array($result))
{
echo
'<tr>' .
'<td>' . $row['sent_from'] . '</td>' .
'<td>' . $row['subject'] . '</td>' .
'<td>' . $row['post_date'] . '</td>' .
'</tr>';
}
?>
</table>
</p>

Categories