Help with PHP While function - php

Why is this not working?
<?php
$select = "select * from messages where user='$u'";
$query = mysqli_query($connect,$select) or die(mysqli_error($connect));
$row = mysqli_num_rows($query);
$result = mysqli_fetch_assoc($query);
$title = mysqli_real_escape_string($connect,trim($result['title']));
$message = mysqli_real_escape_string($connect,trim($result['message']));
while(($result = mysqli_fetch_assoc($query))){
echo $title;
echo '<br/>';
echo '<br/>';
echo $message;
}
?>
where as this works -
<?php
echo $title;
?>
SORRY TO SAY, BUT NONE OF THE ANSWERS WORK. ANY OTHER IDEAS?

If your mysqli query is returning zero rows then you will never see anything printed in your while loop. If $title and $message are not set (because you would want reference them by $result['title'] & $result['message'] if that are the field names in the database) then you will only see two <br /> tags in your pages source code.

If the while loop conditional is not true then the contents of the while loop will never execute.
So if there is nothing to fetch from the query, then you won't see any output.

Does you code display anything, or skip the output entirely?
If it skips entirely, then your query has returned 0 rows.
If it outputs the <br /> s, then you need to check your variables. I could be wrong, not knowing te entire code, but generally in this case you would have something like
echo $result['title'] instead of echo $title

If $title and $message come from your mysql query then you have to access them through the $result array returned by mysqli_fetch_assoc.
echo $result['title'];
echo $result['message'];

Also if your using mysqli you'd be doing something like this:
$mysqli = new mysqli("localhost", "user", "password", "db");
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
print $row['title'];
}
$result->close();
}

Try this:
<?php
$result = mysql_query($query);
while($row = mysqli_fetch_assoc($result)){
echo $title.'<br/><br/>'.$message;
}
?>

Does this work;
<?php
$select = "select * from messages where user='$u'";
$query = mysqli_query($connect,$select) or die(mysqli_error($connect));
$row = mysqli_num_rows($query);
while(($result = mysqli_fetch_assoc($query))){
echo $result['title'];
echo '<br/>';
echo '<br/>';
echo $result['message'];
}
?>
Basically I've made sure that it's not picking the first result from the query & then relying on there being more results to loop through in order to print the same message repeatedly.

Related

PHP Script does not echo json encoded array

I have a php script which should echo a bunch of datasets in a json encoded string. Though the page is blank.
<?php
$con = mysqli_connect("SERVER", "USER", "PASSWORD", "DATABASE");
if(!$sql = "SELECT news.title, news.content, login.username, news.id, news.date, news.timestamp, news.importance, news.version FROM news INNER JOIN login ON news.id = login.id ORDER BY timestamp DESC") {
echo "FAIL";
}
mysqli_query($con,$sql);
$res = mysqli_query($con,$sql);
$result = array();
while($row = $res->fetch_array())
{
array_push($result,
array('title'=>$row[0],
'content'=>$row[1],
'author'=>$row[2],
'id'=>$row[3],
'date'=>$row[4],
'timestamp'=>$row[5],
'importance'=>$row[6],
'version'=>$row[7]
));
}
$oldjson = json_encode(["result"=>$result]);
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
What is the problem here? I tried some error detection with if(!..) but it did not help. I think the problem may be the array creation and/or echo, though I cannot figure out how to fix that.
You should check the result of json_encode, since you are encoding data that comes from the database you might have some stuff that requires escaping.
$json = json_encode(...);
if ($json === false) {
echo "Error = " . json_last_error() . " " . json_last_error_msg();
// You may want to var_dump the $result var here to figure out what the problem is
} else {
echo $json; // Should be ok
}

Returning a whole MYSQL table data on PHP

I found this code once...
$sql_select = "SELECT * FROM users";
$rs_stuff = select($sql_select);
while ($res = mysql_fetch_assoc($rs_stuff)) {
echo ($res("Name")."<br />");
}
It works well, it returns all names found in "Name" col, the problem is I want it to make to return all data in that table, like if I just typed "SELECT * FROM users" on mysql, I don't understand much of PHP, I tried to do this:
echo("<br />\n".$res);
But when trying to run this on the page, I just got a empty blank with "Array" written on it...
Is it possible to do this without putting the col names in the php?
(Sorry about my English, it is not my main language.)
This happens because $res is a Array
use:
print_r($res);
or if you want a better view of it:
echo '<pre>';
print_r($res);
echo '</pre>';
OR
you can use:
echo ($res["Name"]."<br />");
also, on this second option, watch out for multidimensional arrays. Your $res might be one. In which case it will be:
echo ($res[0]["Name"]."<br />");
if you have only one result. I suggest you go with the first choice and see how your $res looks like before echoing strings ;)
Either way, please find a good PHP tutorial as it is CLEAR that you lack basic knowledge of how to use and manipulate PHP code.
Hope it helps! :D
$sql_select = "SELECT * FROM users";
$rs_stuff = select($sql_select);
echo '<table>';//create the table
while ($res = mysql_fetch_assoc($rs_stuff)) {
echo '<tr><td>'.$res['name'].'</td></tr>';
}
If you learning learn mysqli_ or PDO their is no point in learning mysql as they are depriciated.
Try this
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
print_r($row)
}
} else {
echo "0 results";
}
$conn->close();
?>
please put all your rows in an array and then print.
$sql_select = "SELECT * FROM users";
$rs_stuff = select($sql_select);
$arr = array();
while ($res = mysql_fetch_assoc($rs_stuff)) {
$arr[] = $res["Name"];
}
echo '<pre>';
print_r($arr);
echo '<pre>';
Try with this :
foreach($res as $key => $value) {
print $res[$key] . ' => ' . $value;
}
hope that helps :)
It hink this will help:
$sql_select = "SELECT * FROM users";
$rs_stuff = mysql_query($sql_select);
while ($res = mysql_fetch_assoc($rs_stuff)) {
foreach($res as $key => $value) {
echo $key.': '.$value."<br />\n";
}
echo "<br />\n";
}
Loop trough the array of values in the columns and echo out the cells value in the column.
I think this will look like this:
Name: John<br />
Usernmae: johndoe<br />
Age: 36<br />
<br />
Name: Christian<br />
Username: admin<br />
Age: 46<br />
<br />
Don't use echo to print out an array. When you use echo PHP wants to convert an array to a string. If you only want to get the arrays values use print_r. Or use this function:
function convertArraytoString($array) {
foreach($array as $key => $value) {
$return .= $key.': '.$value."<br />\n";
}
return $return;
}
Than you can convert to the array via echo convertArraytoString($res);

mysqli statement not displaying else for no result

I have a statement, quite basic that pulls in from a database and displays the information. It works. However if I delete the entry in the database, the else statement should kick in a say that there are no results. However it does not. Can anyone see the problem?
This is the code, the bit I'm taking about is the if($result) {
$con=mysqli_connect("localhost","user","pass","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else {
$result = mysqli_query($con,"SELECT * FROM vacancies WHERE status ='0'");
if($result) {
while($row = mysqli_fetch_array($result)) {
echo "<li>". $row['title'] ." <img src=\"rightarrow.png\" alt=\"next\"></li>";
}
} else {
// execute for 0 rows returned.
echo "There are currently no vacancies available";
}
}
If the SELECT operation was successful then mysqli_query() will always return an object. Whether this object holds 0 or more records it will always be true. What you should rather have done instead is fetch all the records from the result.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli("localhost", "user", "pass", "db");
$con->set_charset('utf8mb4'); // always set the charset
$result = $con->query("SELECT * FROM vacancies WHERE status ='0'");
$data = $result->fetch_all(MYSQLI_BOTH);
if ($data) {
foreach ($data as $row) {
echo "<li>". $row['title'] ." <img src=\"rightarrow.png\" alt=\"next\"></li>";
}
} else {
// execute for 0 rows returned.
echo "There are currently no vacancies available";
}
To implementing no result, you need to check number of rows you fetch by query with mysqli_num_rows().
In your case you checked for the $result variable this will store the status of the query execution, therefore it will always be true, since query will always execute even if it returns no rows.
To make it more natural way
$data = [];
$result = $con->query("SELECT * FROM vacancies WHERE status ='0'");
while($row = mysqli_fetch_array($result)) {
$data[] = $row;
}
?>
and now you may use $data the way you tried to use $result:
<?php foreach ($data as $row): ?>
<li>
<a href="current_vacancy?id=<?=$row['id']?>">
<?=$row['title']?>
</a>
<img src="/images/rightarrow.png" alt="next">
</li>
<?php endforeach ?>
<?php if(!$data): ?>
There are currently no vacancies available
<? endif ?>
The result returned from mysqli_query is an object, not a row count. Use mysqli_num_rows($result) to get the row count.
By the way, be sure to call mysqli_free_result($result) at the end. Suggested outline:
$result = mysqli_query(…);
if (!$result) {
# Handle failure
} else {
if (mysqli_num_rows($result) == 0) {
# Handle no vacancies
} else {
# Normal case
}
mysqli_free_result($result);
}

For Each loop not echoing data (mysql_fetch_assoc problem?)

Hello and Good Morning,
I am still learning PHP and for some reason my script will not post any data in my foreach loop. Any Idea why? The emailRow Echos out fine but I am going to remove My code is below:
<?php
include 'includes/header.php';
$accountUser = array();
$upgradeEmail = $_GET['currEmail'];
$emailQuery = "SELECT fbID, firstName, lastName FROM users WHERE emailOne='".$upgradeEmail."' AND authLevel=0";
<?php echo $emailRow['fbID']; ?>
<?php echo $emailRow['firstName']; ?>
<?php echo $emailRow['lastName']; ?>
while($emailRow = mysql_fetch_assoc($emailQuery, $conn))
{
$accountUser[]=$emailRow;
}
?>
<table>
<?php foreach($accountUser as $emailData) { ?>
<tr><td> <?php emailData['fbID']; ?> </td><td><?php emailData['firstName']; ?></td><td><?php emailData['lastName']; ?></td></tr>
<?php } ?>
</table>
You have constructed your SQL query in $emailQuery, but never executed it. Call mysql_query(), and pass its result resource to mysql_fetch_assoc().
$emailQuery = "SELECT fbID, firstName, lastName FROM users WHERE emailOne='".$upgradeEmail."' AND authLevel=0";
$result = mysql_query($emailQuery);
if ($result)
{
while($emailRow = mysql_fetch_assoc($result, $conn))
{
$accountUser[]=$emailRow;
}
}
else // your query failed
{
// handle the failure
}
Please also be sure to protect your database from SQL injection by calling mysql_real_escape_string() on $upgradeEmail since you're receiving it from $_GET.
$upgradeEmail = mysql_real_escape_string($_GET['currEmail']);
You don't actually echo anything.
as well as not running the query.
and there are some other methods to do things, much cleaner than usual uglyPHP.
a function
function sqlArr($sql){
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if ($res) {
while($row = mysql_fetch_array($res)){
$ret[] = $row;
}
}
return $ret;
}
a code
$email = mysql_real_escape_string($_GET['currEmail']);
$data = sqlArr("SELECT * FROM users WHERE emailOne='$email' AND authLevel=0");
include 'template.php';
a template
<? include 'includes/header.php' ?>
<table>
<? foreach($data as $row) { ?>
<tr>
<td><?=$row['fbID']?></td>
<td><?=$row['firstName']?></td>
<td><?=$row['lastName']?></td>
</tr>
<? } ?>
</table>
YOU HAVE A SYNTAX ERROR. You can't open a new php tag within an existing php tag. You have to close the already open tag first.
As far as getting the query to work,
First you have to fetch data before printing it or echoing it...
while($emailRow = mysql_fetch_assoc($emailQuery, $conn))
{
$accountUser[]=$emailRow;
}
then you may write statements..
echo $emailRow['fbID']; etc. code.
Secondly you have not fired a query, just written the query statement. Use mysql_query to fire it.
Your code would be something like this..
<?php include 'includes/header.php';
$accountUser = array();
$upgradeEmail = $_GET['currEmail'];
$emailQuery = mysql_query("SELECT fbID, firstName, lastName FROM users WHERE emailOne='".$upgradeEmail."' AND authLevel=0") or die (mysql_error());
while($emailRow = mysql_fetch_assoc($emailQuery, $conn))
{
$accountUser[]=$emailRow;
}
echo $emailRow['fbID'];
echo $emailRow['firstName'];
echo $emailRow['lastName'];
print '<table>';
foreach($accountUser as $emailData) {
print '<tr><td>'$.emailData['fbID'].'</td><td>'.$emailData['firstName'].'</td><td>'.$emailData['lastName'].'</td></tr>';
}
print '</table';
?>
Feel free to use this code, modifying it to fit your needs.

PHP is generating a numeral "1" on output of a function. I've never seen it do this before

function holiday_hitlist($tablename, $hit_user){
global $host, $user, $pass, $dbname;
$link = mysql_connect($host, $user, $pass, $dbname);
print "<div class=\"hit_list\">
<h3>My Holiday Hitlist</h3>
<p>Five things I want the most, based on my desirability ratings.<br/>You can't go wrong with this stuff!</p>
<ol>";
$sql = "SELECT title, URL, price FROM $dbname.$tablename WHERE user='$hit_user' AND rank >= 3 ORDER BY date DESC LIMIT 5";
$result = mysql_query($sql) or die ("Couldn't retrieve holiday hit list for this user. " . mysql_error());
while($row = mysql_fetch_array($result)) {
$title = $row['title'];
$url = $row['URL'];
$price = "$" . $row['price'];
$output = print "<li>$title $price</li>";
}
print "</ol></div>";
return $output;
}
On an HTML page, it puts the "1" immediately following the closing div tag. Why?
See the line
$output = print "<li>$title $price</li>";
you should probably remove the print after the $output =
Or maybe you just need to remove the $output =
I am not quite sure what you intend.
To explain, $output is getting the return value of print "..."
From php.net Reference:
"Return Values
Returns 1, always."
http://ca.php.net/manual/en/function.print.php
You should assign $output to be the output that you would like, then use print to display that output.
From what you've written i think you are doing something like:
function holiday_hitlist($tablename, $hit_user){
/* connections etc
*/
while($row = mysql_fetch_array($result)) {
$title = $row['title'];
$url = $row['URL'];
$price = "$" . $row['price'];
$output = print "<li>$title$price</li>";
}
print "</ol></div>";
return $output;
}
print holiday_hitlist("mytab","myuser");
or maybe
$somevar = holiday_hitlist("mytab","myuser");
print $somevar;
It's really a problem with the fact that you are "printing" the returned value. In your above example why return anything? You could either;
a) set up the function as a routine that just does something and returns nothing. (ie: just remove the return $output and the print in print holiday_hitlist())
or
b) create a function that returns the data you want and then do something with it.
An example of b) is;
function holiday_hitlist($tablename, $hit_user){
/* connections etc
*/
while($row = mysql_fetch_array($result)) {
$title = $row['title'];
$url = $row['URL'];
$price = "$" . $row['price'];
$output .= "<li>$title$price</li>";
}
return $output;
}
$somevar = holiday_hitlist("mytab","myuser");
print "<div class=\'hit_list\'>
<h3>My Holiday Hitlist</h3>
<p>Five things I want the most, based on my desirability ratings.<br/>You can't go wrong with this stuff!</p>
<ol>
$somevar
</ol></div>";
The function above helps to separate the presentation (ie: the HTML) from your data. While not perfect in this example you will be able to see all your html in one block and debug it a lot easier.

Categories