Variables inside while loop - php

I have following code, I try to style output with CSS, but I have small problem, my code show all database entries, which is OK, but when I remove comment from WHILE loop, and comment echo, its showing only first row of entries from database.how can I do same thing and show multiple results from database by use variables in While Loop?:
<?php
error_reporting(0);
require 'connect.php';
$search = $_POST['search'];
//$checkout = $_POST['checkout'];
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM area where destination='{$search}'";
$result = mysqli_query($conn, $sql);
if($count = $result->num_rows) {
echo '<p>', $count, '</p><br><br>';
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row['destination'],' ',$row['place'], $row['tosee'], '<br>';
/$destination =$row["destination"];
//$place =$row["place"];
/$destination =$row["destination"];
//$place =$row["place"];
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
and inside my HTML file:
location: <?php echo $destination; ?>
places: <?php echo $place ; ?>
views: <?php echo $tosee; ?>

Do this...
$out .= $row['destination'].' '.$row['place'].' '.$row['tosee']. '<br>';
Then you can use the $out variable anywhere else...
Even for these...
$destination .= $row["destination"];
$place .= $row["place"];
Since well....are in the while loop

I found a few small errors, you had a ',' instead of a '.' to concatenate a variable.
if($count = $result->num_rows) {
echo '<p>' . $count . '</p><br><br>';
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row['destination'].' '.$row['place'].' '.$row['tosee']. '<br>';
//$destination =$row["destination"];
//$place =$row["place"];
//$destination =$row["destination"];
//$place =$row["place"];
}
}
and for php comments it is: //

Related

Individually displaying stored items in an array

I've been having issues displaying items that i saved from my database in an array. My table has two columns for 'name' and 'details'. I successfully retrieved them using mySQLi and stored in an array but instead of displaying all the columns at once, I want to place them at different places on my webpage. eg
<p>$Name1: $Details1</p>. then on another section of the same page
<p>$Name2: $Details2</p>. This is my code:
<?php
include ("config/database.php");
$mysqli = new mysqli($host, $user, $passwd, $database);
if ($mysqli-> connect_errno){
printf("Connect failed: %s\n",$mysqli-> connect_error);
exit();
}
$query = "SELECT name, details FROM recent_properties LIMIT 3";
if($result = $mysqli->query($query)){
printf("%s: %s<br>", $row["name"], $row["details"]);
$result->free();
}
$mysqli->close();
?>
Did you try like this.Make use of loop. To display all the records.
$query = "SELECT name, details FROM recent_properties LIMIT 3";
$result = $mysqli->query($query);
if($result->num_rows()>0)
{
while($row = $result->fetch_assoc())
{
printf("%s: %s<br>", $row["name"], $row["details"]);
}
}
$mysqli->close();
$query = "SELECT name, details FROM recent_properties";
$result = $mysqli->query($query);
if($result->num_rows()>0)
{
$html = "<table>";
$html .= '<tr><th>Name</th><th>Details</th></tr>';
while ($row = $result->fetch_assoc()) {
$html .= '<tr>';
$html .= '<td>' . $row["name"] . '<td>';
$html .= '<td>' . $row["details"] . '<td>';
$html .= '</tr>';
}
$html .= "</table>";
echo $html;
}
$mysqli->close();
this is the simplest way to create HTML content from data
in your case you can do some thing like this
if ($result->num_rows() > 0) {
$dataArray = [];
while ($row = $result->fetch_assoc()) {
$dataArray[$row["name"]] = $row["details"];
}
}
and then use the array in your HTML
<body>
<p><?php echo 'a: ' . $arrayData['a'] ?></p>
<p><?php echo 'b: ' . $arrayData['b'] ?></p>
<p><?php echo 'c: ' . $arrayData['c'] ?></p>
</body>
You need to loop through your $result and fetch an associative array:
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["name"], $row["details"]);
}
EDIT:
while ($row = $result->fetch_assoc()) {
echo '<p>'.$Name1.': '.$Details1.'</p>';
// Whatever else in this section
// You can even break out of PHP and then
// get back into PHP again if you have a lot of HTML.
}

PHP and mysqli to modify CSS

I was experimenting if I could use a mySQL database to store CSS settings. I set up a simple database "colors" with one table "color" that had simple structure tag and color columns. In that, one row is h1 => red.
<?php
//function to dynamically change CSS
$tag = 'h1';
$q = "SELECT * FROM `colors` WHERE `tag`='" . $tag . "'" ;
echo $q . "<br>";
$query = mysqli_query($link, $q);
if ($row = mysqli_fetch_assoc($query))
{
echo $row['color'];
} else
{
echo "error - no such tag";
}
?>
When I tried to convert to a function, the code does not work at all.
<?php
//function to dynamically change CSS
function getCSS($tag)
{
$tag = 'h1';
$q = "SELECT * FROM `colors` WHERE `tag`='" . $tag . "'" ;
echo $q . "<br>";
$query = mysqli_query($link, $q);
if ($row = mysqli_fetch_assoc($query))
{
echo $row['color'];
} else
{
echo "error - no such tag";
}
}
getCSS('h1');
?>
Help please?
My guess is that in
$query = mysqli_query($link, $q);
$link goes out of scope and is empty. You should pass it to the function as well.
For the record: using $tag without escaping could be an sql injection attack possibility.
in function, there is no $link, you shoud define it as a global variable.
At the start of your function add a reference to your global DB link:
function getCSS($tag) {
global $link;
...
This should work:
<?php
$link = mysqli_connect('server_host', 'user', 'password', 'database') OR die('Could not connect because: '.mysqli_connect_error());
//function to dynamically change CSS
function getCSS($link, $tag){
$q = 'SELECT * FROM colors WHERE tag = "' . $tag . '"' ;
$r = mysqli_query($link, $q);
if(mysqli_num_rows($r)>0){ // check if there are results
while($row = mysqli_fetch_assoc($r)){
//echo '<pre>';
//print_r($row); // print the result array for debugging
//echo '</pre>';
echo $row['color'] . '<br />';
}
return $row;
} else { // if no result is found
echo 'No such tag';
}
}
// test it:
echo '<br />if tag is h1<br />';
getCSS($link, 'h1');
echo '<br />if tag is h2<br />';
getCSS($link, 'h2');
?>

Showing one row. Need to show it in a loop

I am trying to figure out how to use this in a loop. Any help will be appreciated.
$conn = mysql_connect("localhost", "some_user", "password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("some_db")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT favid FROM ajaxfavourites";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row["favid"];
}
mysql_free_result($result);
Currently it displays results as:
116677889922
I need them to show them as (the way they are displayed in DB):
1166
7788
9922
PS I am aware that this function is deprecated, I am just trying to fix one of my older sites.
choose One of these ways:
echo $row["favid"]."<br>";
echo $row["favid"]."\n";
echo $row["favid"].PHP_EOL;
while ($row = mysql_fetch_assoc($result)) {
echo $row["favid"];
echo "\r\n";
}
You can simply echo the value with '<br/>' or '<p>' like following:
while ($row = mysql_fetch_assoc($result)) {
echo $row["favid"] . '<br/>';
}
OR
while ($row = mysql_fetch_assoc($result)) {
echo '<p>' . $row["favid"] . '</p>';
}
Also you can just put all favid into array and then in another loop, can customize how to show them, like following:
while ($row = mysql_fetch_assoc($result)) {
$ids[] = $row["favid"];
}
foreach($ids AS $idv) {
echo '<p>' . $idv . '</p>';
}

Issues getting PHP shuffle to output results

I'm attempting to shuffle the users that I have in my database and then output the first and last name of those results. I have PHP error coding in this file and it is not throwing any errors. Just nothing is outputting not even..
if ($shuffle_firstname == true) {
echo $shuffle_firstname . $shuffle_lastname;
} else {
echo "No users have been registered yet.";
}
Does anyone see what I'm doing wrong?
$con = mysqli_connect("localhost", "root", "", "db");
$shuffle_run = mysqli_query($con,"SELECT * FROM users WHERE `group`= 3");
$shuffle_numrows = mysqli_num_rows($shuffle_run);
if( $shuffle_numrows > 0) {
while($shuffle_row = mysqli_fetch_assoc($shuffle_run)){
$shuffle_id = $shuffle_row['id'];
$shuffle_firstname = $suffle_row['firstname'];
$shuffle_lastname = $shuffle_row['lastname'];
$shuffle_username = $shuffle_row['username'];
$shuffle_email = $shuffle_row['email'];
if ($shuffle_firstname == true) {
echo $shuffle_firstname . $shuffle_lastname;
} else {
echo "No users have been registered yet.";
}
}
}
if(isset($_POST['shuffle'])) {
$shuffle_row = array();
shuffle($shuffle_row);
foreach ($shuffle_row as $shuffle) {
echo $shuffle_firstname . " " . $shuffle_lastname;
}
}
?>
<input type="submit" value="Shuffle" name="shuffle">
You are overwriting your results with an empty array, then you use shuffle on an empty array, then you're looping the empty array using foreach. I've cleaned up the code, could you try this?
<?php
$con = mysqli_connect("localhost", "root", "", "db");
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` = 3");
echo 'Normal results: <br>';
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
$array[] = $row;
echo $row['firstname'] . ' ' . $row['lastname'] . '<br>';
}
if (isset($_POST['shuffle'])) {
shuffle($array);
echo 'Shuffled results: <br>';
foreach ($array as $result) {
echo $result['firstname'] . ' ' . $result['lastname'] . '<br>';
}
// echo $results[0]['firstname'] . ' ' . $results[0]['lastname']; // To display one random result
}
?>
<form method="post">
<input type="submit" value="Shuffle" name="shuffle">
</form>

Replacing PHP "undefined variable" error?

so basically I want to make an online dictionary, the word to be searched for is introduced by an input, and I want to make so that if it can't find the word+definition in db to say a message like "We couldn't find any definition" or something like that, in my code because it can't find it , it ways "undefined variable"
<?php
include ("header.php");
$search = $_POST['se'];
include ("connect.php");
$dictionary=mysqli_query($con,"SELECT * FROM `dictionary` WHERE word = '$search'");
while($row = mysqli_fetch_array( $dictionary )) {
$word=$row['word'];
$description=$row['definition'];
}
echo "<div class=\"webResult\">
<h2>$word</h2>
<p>$description</p>
</div>";
include ("footer.php");
?>
P.S.: I know my code is vulnerable to SQLi , but I'll fix that later.
try wrapping the undefined vars in isset
if (isset($word) && isset($description)) {
echo "<div class=\"webResult\">
<h2>$word</h2>
<p>$description</p>
</div>";
}
else {
echo "Nothing found";
}
Same goes for $search = $_POST['se'];
if(!isset($_POST['se'])) {
echo "Nothing found";
exit;
}
if($row = mysqli_fetch_array( $dictionary )) {
$word=$row['word'];
$description=$row['definition'];
echo "<div class=\"webResult\">
<h2>$word</h2>
<p>$description</p>
</div>";
} else {
echo "$search not found";
}
while($row = mysqli_fetch_array( $dictionary )) {
$word=$row['word'];
$description=$row['definition'];
}
if(!empty($word) && !empty($description)){
echo '<div class=\"webResult\">';
echo '<h2>$word</h2>';
echo '<p>$description</p>';
echo '</div>";
}else{
echo 'could not find your word';
}
include ("footer.php");
?>
You have to validate your variables if its have value or not
The variables $word and $description are first created inside the while loop. This means that they do not have any scope outside it. This should be the most probable cause, since you are getting a variable not defined error.
There are a couple of options here.
One, you could create these variables outside the while loop, and then assign them new values as you are doing now. Here is what your code might look like, if you choose to do it this way:
$search = $con->escape_string($_POST['se']);
$dictionary = $con->query("SELECT * FROM `dictionary` WHERE word = '$search'");
$word = "";
$description = "";
while($row = $dictionary->fetch_assoc())
{
$word = $row['word'];
$description = $row['definition'];
}
if (!empty($word) && !empty($description))
{
echo '<div class="webResult"><h2>' . $word . '</h2><p>' . $description . '</p></div>';
}
else
{
echo "We couldn't find any definition";
}
This will work for you if you have multiple results in the returned mysqli_resource, and want to use the last in the list.
Two, if you are likely to get only one result returned, or if you just want to use the first result in the list, you can have the echo statement inside an if statement that checks if a valid result is returned. For example:
$search = $con->escape_string($_POST['se']);
$dictionary = $con->query("SELECT * FROM `dictionary` WHERE word = '$search'");
$word = "";
$description = "";
$row = $dictionary->fetch_assoc();
if($row)
{
$word = $row['word'];
$description = $row['definition'];
if (!empty($word) && !empty($description))
{
echo '<div class="webResult"><h2>' . $word . '</h2><p>' . $description . '</p></div>';
}
else
{
echo "We couldn't find any definition";
}
}
Note:
In the above examples, we use !empty() to check the variables. This is because isset() is pointless here, since we have already created (set) the variables ourselves.
Things to read up:
Scope of variables - http://php.net/manual/en/language.variables.scope.php
empty() function - http://php.net/manual/en/function.empty.php
Object oriented mysqli - http://php.net/manual/en/mysqli.quickstart.dual-interface.php
Try this:
include ("header.php");
$search = $_POST['se'];
include ("connect.php");
$dictionary=mysqli_query($con,"SELECT * FROM `dictionary` WHERE word = '$search'");
while($row = mysqli_fetch_array( $dictionary )) {
$word=$row['word'];
$description=$row['definition'];
}
if(isset($word)){
echo "<div class=\"webResult\">
<h2>$word</h2>
<p>$description</p>
</div>";
}
else{
echo "We couldn't find any definition";
}
include ("footer.php");

Categories