This question already has answers here:
How can I get useful error messages in PHP?
(41 answers)
Closed 6 years ago.
I'm creating some code to display all the records from a MySQL database into a PHP view.
The query is perfect: using HeidiSQL it retrieves all the values needed:
At the moment, is giving the following error:
How can I debug this?
The code:
<?php $sql = "select * from specials group by Start_Date DESC";
$result = #mysqli_query($sql)
if($result){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo '<div class='deal-item col-md-12'>
<div class='col-md-4'>
<img src='lascruces_styles/img/deals-img/oil-deal.jpg' alt='' class='deal-thumb'>
<p class='expire'>The deal expires '.$row['End_Date'].'</p>
</div>
<div class='col-md-6 info-container'>
<h2 class='deal-title'>'.$row['Special_Name'].'</h2>
<p class='offer-user'>Offered by
<a href=''>'.$row['Added_By'].'</a></p>
<p class='deal-desc'>'.$row['Description'].'</p>
<div class='share-row'>
<a href='' class='share'>Share this deal</a>
<div class='social'>
<i class='icon-facebook'></i>
<i class='icon-gplus'></i>
<i class='icon-linkedin'></i>
<i class='icon-mail-squared'></i>
</div>
</div>
</div>
<div class='col-md-2 view-deal-container'>
<p class='old-price'>'.$row['Normal_Price'].'</p>
<p class='current-price'>'.$row['Special_Price'].'</p>
<a href=''><div class='view-deal'>
<p>VIEW DEAL</p>
</div>
</a>
</div>
</div>';
mysqli_free_result ($result); // Free up the resources }
}
?>
You're missing a couple of things.The main things are that you're missing the connection parameter in your mysqli_query() call, and your single quotes are messing all your syntax. Try in this manner:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "select * from specials group by Start_Date DESC";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while ($row = mysqli_fetch_assoc($result)) {
echo '<div class="deal-item col-md-12">
<div class="col-md-4">
<img src="lascruces_styles/img/deals-img/oil-deal.jpg" alt="" class="deal-thumb">
<p class="expire">The deal expires ' . $row['End_Date'] . '</p>
</div>
</div>';
}
} else {
echo "0 results";
}
mysqli_close($conn);
You're not quoting your string properly, which is causing syntax errors. You're also mixing mysql_* with mysqli_* here.
I'm assuming the MySQLi connection you're using is called $mysqli here, change it accordingly (or if you're using another API, you need to adapt to use that, APIs don't mix).
Properly quoted it should look something like this.
<?php
$sql = "select * from specials group by Start_Date DESC";
if ($result = mysqli_query($mysqli, $sql)) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<div class='deal-item col-md-12'>
<div class='col-md-4'>
<img src='lascruces_styles/img/deals-img/oil-deal.jpg' alt='' class='deal-thumb'>
<p class='expire'>The deal expires ".$row['End_Date']."</p>
</div>
<div class='col-md-6 info-container'>
<h2 class='deal-title'>".$row['Special_Name']."</h2>
<p class='offer-user'>Offered by
<a href=''>".$row['Added_By']."</a></p>
<p class='deal-desc'>".$row['Description']."</p>
<div class='share-row'>
<a href='' class='share'>Share this deal</a>
<div class='social'>
<i class='icon-facebook'></i>
<i class='icon-gplus'></i>
<i class='icon-linkedin'></i>
<i class='icon-mail-squared'></i>
</div>
</div>
</div>
<div class='col-md-2 view-deal-container'>
<p class='old-price'>".$row['Normal_Price']."</p>
<p class='current-price'>".$row['Special_Price']."</p>
<a href=''><div class='view-deal'>
<p>VIEW DEAL</p>
</div>
</a>
</div>
</div>";
}
mysqli_free_result ($result); // Free up the resources
}
?>
Related
I'm trying to echo certain elements from my news table throughout an article. This involves fields such as the author, headline, content and date. At the moment I can only echo the row and any attempt to echo elements in the page itself is either met with small errors or it outputs nothing. I've had a look around and only found people having problems with simply printing out the row database which I can already do.
Basically when I have Author in my article I want to echo author from my database and it will show next to Author. I'm not sure how possible it is as I am yet to find anything on this or I'm overlooking it.
Here is my current PHP file and I've left in the initial part with the article author, date and headline.
<?php
/* Database connection settings */
$host = 'xxxxx';
$user = 'xxxxx';
$pass = 'xxxxx';
$db = 'xxxxx';
$dbconnect=mysqli_connect($host,$user,$pass,$db);
if ($dbconnect->connect_error) {
die("Database connection failed: " . $dbconnect->connect_error);
}
$query = mysqli_query($dbconnect, "SELECT * FROM news WHERE news_Id = 1")
or die (mysqli_errr($dbconnect));
while ($row = mysqli_fetch_array($query)) {
echo
"<tr>
<td>{$row['headline']}</td>
<td>{$row['content']}</td>
<td>{$row['author']}</td>
<td>{$row['date']}</td>
</tr>\n";
}
?>
<div class="container-fluid bg">
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-10">
<div class="container">
<div class="row mb-2">
<div class="col-md-12">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="news-title">
<h2><?php echo $row['headline']; ?></h2>
</div>
<div class="news-cats">
<ul class="list-unstyled list-inline mb-1">
<li class="list-inline-item">
<i class="fa fa-folder-o text-danger"></i>
<small>Author:</small>
</li>
<li class="list-inline-item">
<i class="fa fa-folder-o text-danger"></i>
<small>Posted:</small>
</li>
</ul>
</div>
<hr>
Since your query only returns one row, a while loop is inappropriate for fetching the data, as at the end of the loop, $row will be left as a false value, thus making any attempt to access e.g. $row['headline'] fail. Change your while loop
while ($row = mysqli_fetch_array($query)) {
to a simple assignment:
$row = mysqli_fetch_array($query) or die(mysqli_error($dbconnect));
Note you have a typo earlier in your code,
or die (mysqli_errr($dbconnect));
should be
or die (mysqli_error($dbconnect));
You are just printing out the result, but don't have a label. You can add one like this:
while ($row = mysqli_fetch_array($query)) {
echo
"<tr>
<td>Headline: {$row['headline']}</td>
<td>Content: {$row['content']}</td>
<td>Author: {$row['author']}</td>
<td>Date: {$row['date']}</td>
</tr>\n";
}
Im a PHP newbie. I am creating a jobs website and my search function tells me when there is no result but if there is, it displays ALL the jobs I have entered on the database. Please assist, I have tried everything.
here is my code:
<?php
if(isset($_POST['submit']))
{
$search = $_POST['keyword'];
$query = "SELECT * FROM jobs WHERE job_tags LIKE '%$search%'";
$search_query = mysqli_query($connection, $query);
if(!$search_query) {
die ("query failed" . mysqli_error($connection));
}
$count = mysqli_num_rows($search_query);
if($count == 0){
echo "<h3> NO RESULT</h3>";
}else{
$query = "SELECT * FROM jobs";
$job_display = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($job_display)){
$job_title = $row['job_title'];
$employer = $row['employer'];
$job_date = $row['job_date'];
$job_logo = $row['job_logo'];
$job_desc = $row['job_desc'];
?>
<div class="row">
<div>
<div class="media img-responsive">
<div class="media-left media-middle">
<a href="#">
<img class="media-object" src="images/<?php echo $job_logo; ?>" class="img-responsive" alt="Absa Insurance Logo">
</a>
</div>
<div class="media-body">
<h4 class="media-heading"><span class="job-tittle"><?php echo "{$job_title}";?> </span>(<i class="glyphicon glyphicon-map-marker"> </i>Gauteng, <span class="type blue"> Short-Term Insurance</span>)</h4>
<P>
<?php echo $job_desc;?>
... <i class="glyphicon glyphicon-plus"> </i> Read More</P>
</div>
<div class=" media-right media-middle job-location">
<p> <?php echo $job_date;?> </p>
</div>
</div>
</div>
</div>
<?php }
}
}
?>
here is the Form
<form class=" form-inline" action="search.php" method="post">
<div class="form-group">
<input type="text" name="keyword" class="form-control" placeholder="Job Key Word">
</div>
</form>
Please let me know if you need more information.
you need to remove this line or just filter here
$query = "SELECT * FROM jobs";
In first query You are looking for only selected records
$query = "SELECT * FROM jobs WHERE job_tags LIKE '%$search%'";
$search_query = mysqli_query($connection, $query);
If it find something You search one more time with
$query = "SELECT * FROM jobs";
You don't put WHERE in this query.
I'm trying to generate dynamic contents fill from mysql db
here is my php code:
<?php
include 'header.php';
error_reporting(1);
$user = "root";
$pass = "";
$dbName = "haimi";
mysql_connect('localhost', $user, $pass) or
die("Could not connect: " . mysql_error());
mysql_select_db($dbName);
$sql = "SELECT * FROM Projects ";
$result = mysql_query($sql);
?>
<?php
while ($line = mysql_fetch_array($result)) {
?>
<li class="filter" data-filter=".cat<?php echo $line['Category'];?>"><?php echo $line['Category'];?></li>
<?php
}
?>
The li displays correctly, but the following does not:
<div class="row projects m0">
<?php
while ($line = mysql_fetch_array($result)) { ?>
<div class="project mix catHouses">
<div class="tint"></div>
<a href="images/projects/".<?php echo $line['ProjectImage1']; ?> data-
lightbox="project" data-title="Central Hospital (building)">
<img src="images/projects/".<?php echo
$line['ProjectImage1']; ?> alt="<?php echo $line['ProjectTitle'];?>"
class="projectImg"> </a>
<div class="projectDetails row m0">
<div class="fleft nameType">
<div class="row m0 projectName"><?php echo $line['ProjectTitle'];?></div>
<div class="row m0 projectType"><?php echo $line['ProjectType'];?></div>
</div>
<div class="fright projectIcons btn-group" role="group">
<a href="images/projects/<?php echo $line['ProjectImage1']; ?>" data-lightbox="project" data-title="Central Hospital (building)" class="btn btn-default">
<i class="fa fa-link"></i></a>
<i class="fa fa- search"></i>
</div>
</div>
</div>
<?php
}
?>
</div>
It data in the divs doesn't appear.
You're making a single call, but trying to loop through it twice. To do so, you need to reset the pointer back to the beginning:
//Add this after the first loop, but before the second
mysql_data_seek( $result, 0 );
The way you have it now, it's while($line = mysql_fetch_array($result)), but the second loop is never entered since it has already reached the end. Since the loop is ended, it never displays the contents.
Important Note
The mysql_* functions are deprecated, and is removed in PHP 5.5. You should use Mysqli or PDO. They have better protections against mysql injections (see Bobby Tables).
You have some HTML mistakes here:
<a href="images/projects/".<?php echo $line['ProjectImage1']; ?>
First, there is no need to use . operator (as you are in HTML, not PHP),
Also you shoud put your <?php ?> tag inside the href quotations, here is the correct code:
<a
href="images/projects/<?php echo $line['ProjectImage1']; ?>"
data-lightbox="project"
data-title="Central Hospital (building)"
>
<img
src="images/projects/<?php echo $line['ProjectImage1']; ?>"
alt="<?php echo $line['ProjectTitle']; ?>"
class="projectImg"
>
</a>
You will get older fast writing code like that ;)
How about this:
while ($line = mysql_fetch_array($result)) {
$category = $line['Category'];
echo <<< LOB
<li class="filter" data-filter="$category">$category</li>
LOB;
}
Like what Mr #matthew said
I was making a single call, and I was trying to loop through it twice.
The problem solved with this code before the while loop:
$result = mysql_query($sql);
Hi guys I have an application that allows users to post content on an empty div. I need some advice on making it scalable as I have to make sure if users are posting a lot of content the browser will not slow down or crash. I am a beginner so please put up with me. So in my code below I have an echo statement that prints out html content. I want to know how to make that function scalable in the long run? should I set the html as a variable then print it? should I encode it with JSON? please advice me as such. Thank-you
PHP Code
<?php
include_once("connection.php");
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
//You can use Inner Join to display the matched records in between the two tables
$query = "SELECT * FROM `qpost` A INNER JOIN `user` B ON A.id=B.id ";
$result = $conn->query($query);
if($result) {
} else {
echo "bitch: " . $conn->error;
}
while($row = $result->fetch_assoc()) {
$time = time();
if( $time < $row['logged_time'] + 30) {
echo " <div class='row'>
<div class='col-md-8'>
<div id='thePost' class='panel panel-default'>
<div class='panel-heading'>
<h3 class='panel-title'><span class='glyphicon glyphicon-user'> <b>{$row['username']}</b></span>       <span class='glyphicon glyphicon-time'></span> Posted_on: {$row['time']} </h3>
</div>
<div class='panel-body' style='word-break:break-all'>
<h4>{$row['question']} </h4>
<p> {$row['description']}</p>
</div>
<div class='panel-footer'>
<button class='btn btn-primary'>Request Connection</button>
<button class='btn btn-success'>Chat <span class='glyphicon glyphicon-comment'></button>
</div>
</div>
</div>
</div> ";
}//end if
}//end while
?>
Did you try to separate the data logic and data display ? if you used php MVC framework which will more convenient on your case.
Following is a simple example.
//demo.html code
<?php
include_once("connection.php");
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
//You can use Inner Join to display the matched records in between the two tables
$query = "SELECT * FROM `qpost` A INNER JOIN `user` B ON A.id=B.id ";
$result = $conn->query($query);
if ($result) {
} else {
echo "bitch: " . $conn->error;
}
$time = time();
$data_result = array(); // focus on your data logic process
while ($row = $result->fetch_assoc()) {
if ($time < $row['logged_time'] + 30) {
$data_result[] = $row;
}
}
?>
<?php foreach($data_result as $index => $row) { ?>
<div class='row'>
<div class='col-md-8'>
<div id='thePost' class='panel panel-default'>
<div class='panel-heading'>
<h3 class='panel-title'><span class='glyphicon glyphicon-user'> <b><?php echo $row['username']?></b></span>
      <span class='glyphicon glyphicon-time'></span> Posted_on: <?php echo $row['time']?>
</h3>
</div>
<div class='panel-body' style='word-break:break-all'>
<h4><?php echo $row['question']?></h4>
<p> <?php echo $row['description']?></p>
</div>
<div class='panel-footer'>
<button class='btn btn-primary'>Request Connection</button>
<button class='btn btn-success'>Chat <span class='glyphicon glyphicon-comment'></button>
</div>
</div>
</div>
</div>
<?php } ?>
It's fine what you're doing.
However as Eric has said you can exit and re-enter your PHP
You could store the html in a file, grab it using file_get_contents then use sprintf to manipulate it
In a file called "row.html"
<div class='row'>
<div class='col-md-8'>
<div id='thePost' class='panel panel-default'>
<div class='panel-heading'>
<h3 class='panel-title'>
<span class='glyphicon glyphicon-user'>
<b>%s</b> <!-- username -->
</span>      
<span class='glyphicon glyphicon-time'>
Posted_on: %s <!-- time -->
</span>
</h3>
</div>
<div class='panel-body' style='word-break:break-all'>
<h4>%s</h4> <!-- question -->
<p> %s</p> <!-- description -->
</div>
<div class='panel-footer'>
<button class='btn btn-primary'>Request Connection</button>
<button class='btn btn-success'>Chat <span class='glyphicon glyphicon-comment'></button>
</div>
</div>
</div>
</div>
Then in your PHP....
<?php
while($row = $result->fetch_assoc()) {
$time = time();
if( $time < $row['logged_time'] + 30) {
$rowHtml = file_get_contents('row.html');
echo sprintf($rowHtml,
$row['username'],
$row['time'],
$row['question'],
$row['description']);
}
}
?>
I personally like as much abstraction as possible between my languages :)
Good luck!
One way to echo out HTML with PHP is using Heredoc syntax (http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc)
<?php
$name = 'MyName';
echo <<<MYHTML
<p>
My name is <b>"$name"</b>.
</p>
MYHTML;
?>
I am building a blog and trying to show all comments that apply to the post.
Each post has an ID and each comment is stored with the post ID.
here is my code:
<?php
$con = mysql_connect("localhost","cl49-XXX-b","X");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cl49-XXX-b", $con)or die( "Unable to select database line 873");
$result=mysql_query("SELECT * FROM blogcomments WHERE ID='".$ID."'") or die('Error on Line 215 :'.mysql_error());
echo " <ul class='comments'> "; // first row beginning
for ($i = 1; $i <= mysql_num_rows($result); $i++)
{
$row = mysql_fetch_array($result);
$name = $row['name'];
$email = $row['email'];
$comment = $row['comment'];
$created=$row['created'];
echo" <li>
<div class='comment'>
<div class='thumbnail'>
<img class='avatar' alt='' src='img/avatar.jpg'>
</div>
<div class='comment-block'>
<div class='comment-arrow'></div>
<span class='comment-by'>
<strong>$name</strong>
<span class='pull-right'>
<span> <a href='#'><i class='icon-reply'></i> Reply</a></span>
</span>
</span>
<p>$comment</p>
<span class='date pull-right'>$created</span>
</div>
</div> ";
echo " </li>"; // it's time no move to next row
}
?>
When I run this code the page only shows one comment, although my DB has 3 comments with the correct ID.
I would consider using mysqli_ as mysql_ has been depreciated. I'd also consider using a while loop, hopefully this will help:
<?php
$DBServer = 'localhost';
$DBUser = 'xxxx';
$DBPass = 'xxxx';
$DBName = 'xxxx';
$mysqli = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
if ($mysqli->connect_errno) {
echo "Failed to connect to the database: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$query = "SELECT * FROM blogcomments WHERE ID='". $ID ."'";
echo " <ul class='comments'> ";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
?>
<li>
<div class='comment'>
<div class='thumbnail'>
<img class='avatar' alt='' src='img/avatar.jpg'>
</div>
<div class='comment-block'>
<div class='comment-arrow'></div>
<span class='comment-by'>
<strong><?php echo $row['name']; ?></strong>
<span class='pull-right'>
<span><a href='#'><i class='icon-reply'></i> Reply</a></span>
</span>
</span>
<p><?php echo $row['comment']; ?></p>
<span class='date pull-right'><?php echo $row['created']; ?></span>
</div>
</div>
</div>
</li>
<?php
} $result->close();
} $mysqli ->close();
echo "</ul>";
?>
I haven't tested this for bugs, but let me know if you like further information.
When you do this :
mysql_query("SELECT * FROM blogcomments WHERE ID='".$ID."'")
You select just one comment in the database.
Maybe you have to do that :
mysql_query("SELECT * FROM blogcomments WHERE post_ID='".$post_ID."'")
Because you are selecting the row where ID field value is $ID in the table blogcomments.
I guess you store the referred post_id to whom the comment is connected in a field called something like "post_id". You better point your select query to that field ;)
If you put the structure of the table in the question, I might help :)
You're not closing your <ul>. Might it just be a HTML formatting issue?