php echo not displaying - php

This code
<?php echo "Likes: ".$r['votes_up']." "; echo "Dislike: ".$r['votes_down'].""; ?>
Wont post the values from the table for 'votes_up' 'votes_down'
I cant get my head round this! Ive got this exact code working on a different page but it wont on this.
Heres the entire code ....
<div class="message">
<?php
$sql = mysql_query("SELECT * FROM threads WHERE id = '" . $_GET['id'] . "'") or die(mysql_error());
while($r = mysql_fetch_array($sql)) {
$posted = date("jS M Y h:i",$r['posted']); echo "".$r['author']." $posted";?>
<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-text="<?php echo "".$r['message'].""; ?>">
Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
<div class="message2"><?php echo "".$r['message'].""; }?></div>
<?php echo "Likes: ".$r['votes_up']." "; echo "Dislike: ".$r['votes_down'].""; ?>
</div>
<br/>
<hr>
Can anyone help? its driving me insane

Line 8 of your code
<div class="message2"><?php echo "".$r['message'].""; }?></div>
Why is that closing curly brace in there before the closing ?> ?

You seem to have closed the WHILE loop here:
<div class="message2"><?php echo "".$r['message'].""; }?></div>
Notice the curly bracket.
Therefore, votes_up and votes_down have no values.

Your curly bracket is being placed before the last echo statement, therefore the $r variable is out of scope.
Move the } to later in your page like so
<div class="message">
<?php
$sql = mysql_query("SELECT * FROM threads WHERE id = '" . mysql_real_escape_string($_GET['id']) . "'") or die(mysql_error());
while($r = mysql_fetch_array($sql))
{
$posted = date("jS M Y h:i",$r['posted']);
echo $r['author']." ".$posted;
?>
<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-text="<?php echo $r['message']; ?>">
Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
<div class="message2">
<?php
echo $r['message'];
?>
</div>
<?php
echo "Likes: ".$r['votes_up']." ";
echo "Dislike: ".$r['votes_down'];
}
?>
</div>
<br/>
<hr>
Also notice the call to mysql_real_Escape_string in the $sql var. this will prevent nasty sql injections

This is because the $r['...'] variable is out of the scope where you place it.
Better way to do it (assuming you only fetch one row:
<?
$sql = mysql_query("SELECT * FROM threads WHERE id = '" . $_GET['id'] . "'") or die (mysql_error());
$row = mysql_fetch_assoc($sql);
?>
<div> ... </div>
<?php echo "Likes: " . $row['votes_up'] . " Dislike: " . $row['votes_down']; ?>

Related

Returning SQL data within an image tag using PHP

When I run the following file I get the database data i.e it prints it out on the website so I know my connections are good.
<html>
<?php include 'config.php'?>
<?php include 'header.php'?>
<?php
$sql = "SELECT name, image FROM images";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo $row["name"], $row["image"];
}
?>
</div>
</html>
However when I try and format the results like below
<html>
<?php include 'config.php'?>
<?php include 'header.php'?>
<?php
$sql = "SELECT name, image FROM images";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo <div id = "bookbar">
<img src= "$row['image']" alt = "image">
<p> $row['name'] </p>
</div>
}
?>
</div>
</html>
it doesn't work. Can anyone help me fix the code?
Maybe try this your code didn't close/open the php tags properly also don't echo like that
<?php include 'config.php'?>
<?php include 'header.php'?>
<?php
$sql = "SELECT name, image FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<div id = "bookbar">
<img src= "<?php echo $row['image'] ?>" alt = "image">
<p><?php echo $row['name']; ?></p>
</div>
<?php
}
}
$conn->close();
?>
If you want to echo something out
Its better to close on open the php tags like so
PHP goes here
?>
HTML goes here
<?php
PHP goes here
And if you want to echo something inside the HTML just do this
<span> <?php echo "something" ?> </span>
much easier and makes the code easier to read.
change your echo statement to -
echo '<div id = "bookbar"><img src= "' . $row['image'] . '" alt = "image"><p>'. $row['name'] .'</p>'
Your issue is a syntax problem - you can't use echo like that, it has to echo a string variable. You should be seeing an error message about it.
You could keep the echo statement and put all the HTML inside a string, and concatenate (or interpolate) the PHP data into it. But IMO the easiest thing here in terms of readability and maintenance is to step out of the PHP tags, print the HTML, embed some PHP tags in it for the variables, and then step back in again to continue with the code. It makes the HTML far easier to understand:
?>
<div id="bookbar">
<img src="<?php echo $row['image'] ?>" alt="image">
<p><?php echo $row['name'] ?></p>
</div>
<?php
When you are in php mode you should echo strings as php variables wrapped with single quotes:
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo '<div id = "bookbar">';
echo '<img src="' . $row['image'] . '" alt = "image">';
echo '<p>' . $row['name'] . '</p>';
echo '</div>';
}

error in query using MySQL and PHP, based on showing data from database

code:
<!-- content -->
<article id="content" class="tabs">
<div class="wrapper">
<div class="box2">
<?php
//session_start();
$sql = "SELECT * FROM `db`.`news` ORDER BY `date` DESC LIMIT 20";
include 'php/dbconnection.php';
$conn = OpenCon(); //$conn=$_SESSION['conn'];
$result = mysqli_query($conn,$sql);
if($result){
$rows = mysqli_fetch_array($result);
echo "<div class='wrapper tab-content'>";
echo "<section class='col1'>";
echo "<h4><span>" . $rows['date']. "</span> </h4>";
echo "<p class='pad_bot2'><strong>". $rows['title']. "
</strong></p>";
echo "<p class='pad_bot1'>".$rows['des'] ."</p>";
echo "</section>";
echo "</div>";
}
?>
</div>
</div>
</article>
<!-- /content-->
Here I'm trying to, print 'news' table from database, but I'm unable to print anything on webpage.
can anyone point out, what is wrong in this ?
Thank You in advance for any help!
You have to put mysqli_fetch_row($result) inside a loop.
Example with your case:
if($result){
while ($rows=mysqli_fetch_row($result)){
echo "<div class='wrapper tab-content'>";
echo "<section class='col1'>";
echo "<h4><span>" . $rows['date']. "</span> </h4>";
echo "<p class='pad_bot2'><strong>". $rows['title']. "
</strong></p>";
echo "<p class='pad_bot1'>".$rows['des'] ."</p>";
echo "</section>";
echo "</div>";
}
}
// Free result set
mysqli_free_result($result);
Hope this helps!
For commented $conn=$_SESSION['conn'];
You cannot store resource handles within a $_SESSION. See PHP.net:
Some types of data can not be serialized thus stored in sessions. It
includes resource variables or objects with circular references (i.e.
objects which passes a reference to itself to another object).
As your object contains the connection link it can't be serialized, Just reconnect with every request.
And you can make clean template like below
<!-- content -->
<article id="content" class="tabs">
<div class="wrapper">
<div class="box2">
<?php
//session_start();
$sql = "SELECT * FROM `db`.`news` ORDER BY `date` DESC LIMIT 20";
include 'php/dbconnection.php';
$conn = OpenCon();
$result = mysqli_query($conn,$sql);
if($result):
while ($row=mysqli_fetch_row($result)):
?>
<div class='wrapper tab-content'>
<section class='col1'>
<h4><span><?php echo $row['date'];?></span></h4>
<p class='pad_bot2'>
<strong><?php echo $row['title'];?></strong>
</p>
<p class='pad_bot1'><?php echo $row['des'];?></p>
</section>
</div>
<?php
endwhile;
else:
?>
<p>No active news</p>
<?php
endif;
?>
</div>
</div>
</article>
<!-- /content-->
// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
// Associative array
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
So for your code, you need to change:
$rows = mysqli_fetch_array($result);
to:
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
Also, you should check for number of rows before fetching by using:
$rowcount=mysqli_num_rows($result);
Only if $rowcount is more than 0, you should mysqli_fetch_array.

how to use html inside php while loop

I have user information coming from database on a profile page using a while loop. I want to be able to write stuff like this, $username's profile. I can't seem to figure it out. Here is my code.
<?php
//open database connection
include 'page-start.php';
include 'core/init.php';
?>
<?php
$myQuery = ("SELECT user_id, username, profile, city FROM `users` WHERE user_id = '" . mysql_real_escape_string($_GET['ID']) . "' ") or die(mysql_error());
//run query
$result = $con->query($myQuery);
if (!$result) die('Query error: ' . mysqli_error($result));
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
} ?>
<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/studentsupport/defines.php'; ?>
<?php include_once("head.php");
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
echo '<div class="sixteen columns" id="user-profile">';
echo'<h2 class="username"> ' . $row['username'] . ' </h2> ';//bob's Profile
echo'<p>' . $row['city'] . '</p>'; //city: london
echo '<div class="eight columns" id="user-profile-img">';
echo'<img src="'. $row['profile'] . '"/>';
echo '</div>';
echo '</div>';
}
?>
edit: sorry I didn't explain it very well.
I want to be able to have some information come from the database and some information just as standard html for example:
<p><?php echo $username; ?>'s profile </p>
<p>city: <?php echo $city; ?> </p>
During each loop in the while, $row['username'] will have a username.
If you want to be able to get all the usernames later, add the following:
$users[] = $row['username'];
Now, Everywhere in your script $users[0] will have the 1st username, $users[1] will have the second, etc.
If you are beginner than i wil say You should use easy method now it seems okay
like You make Whole page of profile like you want
like
then you can Take your data in Variables in while Loop like that
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
$profile = $row['profile'];
$name = $row['name'];//you can take as many variables as you want
$city = $row['city'];
}
then you can use these variables in html simply
<div class="sixteen columns" id="user-profile">
<h2 class="username"><?php echo $name; ?> </h2>
</div>
start like that next step like above will get easy to u :)
This may do it.
<?php include_once("head.php");
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{ ?>
<div class="sixteen columns" id="user-profile">
<h2 class="username"><?php echo $row['username']; ?></h2>
<p><?php echo $row['city']; ?></p>
<div class="eight columns" id="user-profile-img">
<img src="<?php echo $row['profile']; ?>"/>
</div>
</div>
<? } ?>

Data from database show/hide onclick trouble

<?php
$getNews = $db->prepare("SELECT * FROM news ORDER BY id DESC LIMIT 4");
$getNews->execute();
$news = $getNews->fetchAll();
foreach ($news as $newspost) {
echo $newspost['title'] ; ?> <a style="cursor:pointer;" onclick="return toggleMe('problem')">read/hide</a>
<?php
echo '<br />';
echo 'Posted by '; echo $newspost["user"]; echo ' at '; echo $newspost["created"]; ?>
<div id="<?php echo $newspost['id']; ?>" style="display:none;">
<?php
echo $newspost['message'];
?>
</div>
<?php
echo '<br /> <br />';
}
?>
What I had in mind was that it shows/hides the text from the newspost when you hit the read/hide link next to the title of the newspost.
I can fit the $newspost['id'] in the representing div but because the onclick="return toggleMe('problem')"> has both " and ' in it I need another way to fit it in there, I searched a lot but couldn't find what I was exactly looking for.
Actually, you'll be fine with:
"return toggleMe('<?php echo $newspost['id']; ?>');"
The inner single quotes will never be seen in the output HTML, and the <?php ?> block doesn't care what quotes surround it.

isset within an echo? Or is there a better way?

$sql = "SELECT * from post where forum_id = $_GET[id]";
$result = mysqli_query($conn, $sql) or die('Error querying database.');
while ($row = mysqli_fetch_array($result)) {
echo '' . $row['fourm_id'];
echo '<div id="post3">
<p class="1">
<span class="name">'.'
' .$row['name']. '</span>'.
'<span class="trip">
' .' !'
. $row['title'].''.
' </span>'.
' <span class="time">
' .$row['time']. '' .
' </span>'.
' </p>
<p class="2">
<span class="texts">
' .$row['texts']. '' .
' </span>'.
' </p>'.
if (!isset($_SESSION["user_id"])) {
}
else {
'<a href="delete_post.php?fourm_id=' . $row['id']. '>Delete</a>' . }
' </div>';
}
mysqli_close($conn);
?>
The mistake in the code is obvious, just showing what I am trying to do.
This echo I have here displays the users post, how would I go about sticking an isset in there so only admins can see the delete link? Or is there another way of doing it outside the echo with out it going outside the user post?
<?
$data = array();
$sql = "SELECT * from post where forum_id = ".intval($_GET['id']);
$res = mysqli_query($conn, $sql) or trigger_error(mysqli_error($conn));
while ($row = mysqli_fetch_array($result)) {
$data[] = $row;
}
?>
<?php foreach($data as $row): ?>
<?=$row['fourm_id']?>
<div id="post3">
<p class="1">
<span class="name"><?=$row['name']?></span>
<span class="trip"> !<?=$row['title']?></span>
<span class="time"><?=$row['time']?></span>
</p>
<p class="2">
<span class="texts"><?=$row['texts']?></span>
</p>
<? if (isset($_SESSION["user_id"])): ?>
Delete
<? endif ?>
</div>
<? endforeach ?>
If you want to do it inline, you can either use the ternary operator or something like sprintf.
Ternary operator (best if you only have a couple of insertions):
echo "Foo ".(isset($bar) ? "bar" : "");
(s)printf (best if you have several insertions):
printf("Foo %s", isset($bar) ? "bar" : "");
However this does not scale very much, so when you have large-scale "string construction" it's much saner to split the output into more than one statements:
echo "Foo ";
if (isset($bar)) {
echo "bar";
}
This is best if you have lots of insertions.

Categories