Echoing php variables with html [duplicate] - php

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
I have the following code, but keep running into a syntax error on line 7, saying "Parse error: syntax error, unexpected 'htmlentities' (T_STRING)." Is this not the correct way to echo php and html at the same time? Any help is appreciated!
<?php
$stmt = $pdo->query("SELECT first_name, last_name, department, website filename FROM Profile");
while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
echo('<div class="col-sm-3">
<img class="img-rounded" src="'.$row['filename'].'"/>
<p class="caption">');
echo(''.($row['first_name']).' '.htmlentities($row['last_name']).'')
echo(', '.htmlentities($row['department']));
echo('</p> </div>');
}
?>

Your echo should be without parenthesis and you're missing . on a few of your echo commmands.

To join an echo string (concatenate) you need to add the strings with a "."
Please use :
<?php
$stmt = $pdo->query("SELECT first_name, last_name, department, website filename FROM Profile");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<div class="col-sm-3">
<img class="img-rounded" src="' . $row['filename'] . '"/>
<p class="caption">';
echo '' . ($row['first_name']) . ' ' . htmlentities($row['last_name']) . '';
echo ', ' . htmlentities($row['department']);
echo '</p> </div>';
}
?>

You should concatenate your strings when you interrupt the string like
echo('<a href="' . htmlentities($row['website']) . '">'.($row['first_name']).' '
At the htmlentities part you are missing the dots for stringconcatenation

You have concatenated the string in wrong way. Try following
<?php
$stmt = $pdo->query("SELECT first_name, last_name, department, website, filename
FROM Profile");
while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) )
{
echo '<div class="col-sm-3">
<img class="img-rounded" src="'.$row['filename'].'"/>
<p class="caption">';
echo ''.$row['first_name'].' '.htmlentities($row['last_name']).'';
echo ', '.htmlentities($row['department']);
echo '</p> </div>';
}
?>
OR
You can also try the following as an alternative way..
<?php
$stmt = $pdo->query("SELECT first_name, last_name, department, website, filename
FROM Profile");
while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) )
{
?>
<div class="col-sm-3">
<img class="img-rounded" src="<?php echo $row['filename'] ?>"/>
<p class="caption">
<a href="<?php echo htmlentities($row['website']) ?>">
<?php echo $row['first_name'].' '.$row['last_name'] ?>
</a>
<?php echo ', '.htmlentities($row['department']); ?>
</p>
</div>
<?php
}
?>

I edit the code you try it. You miss . and ;
echo '<div class="col-sm-3">
<img class="img-rounded" src="'.$row['filename'].'"/>
<p class="caption">';
echo ''.($row['first_name']).' '.htmlentities($row['last_name']).'';
echo ', '.htmlentities($row['department']);
echo '</p> </div>';

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>';
}

How to execute 2 or more SQL queries in PHP without joining tables [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 6 years ago.
To select data from 1 table I'm using following code:
if(isset($UserID)) {
$users = $con->prepare("
SELECT DISTINCT
d.FirstName
,d.LastName
,d.Picture
FROM Details d
WHERE d.UserId = ?
");
$users->bind_param('i', $GetUserId);
$users->execute();
$users->bind_result(
$FirstName,
$LastName,
$Picture
);
} else {
echo "There is no User ID detected, try to refresh browser.";
}
while ($users->fetch()) { ?>
<div class="grid-group">
<span>Personal Details</span>
<div class="grid-column">
<div class="grid-item header">First Name </div>
<div class="grid-item header">Last Name </div>
<div class="grid-item header">Picture </div>
</div>
<div class="grid-column">
<div class="grid-item"><?php echo $FirstName; ?></div>
<div class="grid-item"><?php echo $LastName; ?></div>
<div class="grid-item"><?php echo $Picture; ?></div>
</div>
</div>
<?php } ?>
How can I add 1 more query to select some data from another table? Something like:
SELECT Foo, Bar, FooBar
FROM Bizz
WHERE UserId = ?
Should I use mysqli_multi_query? But how can I use It and bind_result after It? I can't achieve correct syntax. Or there is any other way?
I will need to print data from 2 tables like this:
while ($users->fetch()) { ?>
<div class="grid-group">
<span>Personal Details</span>
<div class="grid-column">
<div class="grid-item header">First Name </div>
<div class="grid-item header">Last Name </div>
<div class="grid-item header">Picture </div>
</div>
<div class="grid-column">
<div class="grid-item"><?php echo $FirstName; ?></div>
<div class="grid-item"><?php echo $LastName; ?></div>
<div class="grid-item"><?php echo $Picture; ?></div>
</div>
</div>
<div class="grid-group">
<span>Foo Bar</span>
<div class="grid-column">
<div class="grid-item header">Foo </div>
<div class="grid-item header">Bar </div>
<div class="grid-item header">FooBar </div>
</div>
<div class="grid-column">
<div class="grid-item"><?php echo $Foo; ?></div>
<div class="grid-item"><?php echo $Bar; ?></div>
<div class="grid-item"><?php echo $FooBar; ?></div>
</div>
</div>
<?php } ?>
For some reasons I can't use JOINS. Have you any ideas?
UPDATE
If I prepare 2 queries in following, I got blank screen:
if(isset($UserID)) {
$users = $con->prepare("
SELECT DISTINCT
d.FirstName
,d.LastName
,d.Picture
FROM Details
WHERE d.UserId = ?
");
$users->bind_param('i', $GetUserId);
$users->execute();
$users->bind_result(
$FirstName,
$LastName,
$Picture
);
$users2 = $con->prepare("
SELECT DISTINCT
Foo
, Bar
, FooBar
FROM Bizz
WHERE UserId = ?
");
$users2->bind_param('i', $GetUserId);
$users2->execute();
$users2->bind_result(
$Foo,
$Bar,
$FooBar
);
} else {
echo "There is no User ID detected, try to refresh browser.";
}
while ($users->fetch()) { ?>
...
Have you any ideas?
to know why you get a blank screen you have to turn on error_reporting, add the following at the start of your php code before anything else:
error_reporting(-1);
Also add some code to show errors that might happen in MySQL:
if(isset($UserID)) {
$users = $con->prepare("
SELECT DISTINCT
d.FirstName
,d.LastName
,d.Picture
FROM Details
WHERE d.UserId = ?
");
if (!$users) {
echo 'MySQL Connect Error in Query: (' . $mysqli->errno . ') ';
}
$binding = $users->bind_param('i', $GetUserId);
if (!$binding) {
echo 'MySQL Connect Error in Query: (' . $mysqli->errno . ') ';
}
if($users->execute() == false) {
echo 'Error: ' . $con->error;
}
$binding_results = $users->bind_result(
$FirstName,
$LastName,
$Picture
);
if (!$binding_results) {
echo 'MySQL Connect Error in Query: (' . $mysqli->errno . ') ';
}
$users2 = $con->prepare("
SELECT DISTINCT
Foo
, Bar
, FooBar
FROM Bizz
WHERE UserId = ?
");
if (!$users2) {
echo 'MySQL Connect Error in Query: (' . $mysqli->errno . ') ';
}
$binding2 = $users2->bind_param('i', $GetUserId);
if (!$binding2) {
echo 'MySQL Connect Error in Query: (' . $mysqli->errno . ') ';
}
if($users2->execute() == false) {
echo 'Error: ' . $con->error;
}
$binding_results2 = $users2->bind_result(
$Foo,
$Bar,
$FooBar
);
if (!$binding_results2) {
echo 'MySQL Connect Error in Query: (' . $mysqli->errno . ') ';
}
I can see one mistake in your first query. you are using d.FirstName where as the table name is Details

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>
<? } ?>

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.

php echo not displaying

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']; ?>

Categories