mysqli_fetch_array reading result as null? - php

Any idea why this is showing a result of null? I'm guessing it has to do with where I put $link before I did the query, but it has to be done that way, correct?
function getcatposts($cat_id) {
$qc = #mysqli_query($link, "SELECT * FROM topics WHERE topic_cat='$cat_id'");
while($row = mysqli_fetch_array($qc)) {
$topic_title=$row['topic_subject'];
$topic_id=$row['topic_id'];
}
$qc2 = #mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2)) {
$cat_name=$row2['cat_name'];
}
Updated code:
function getcatposts($cat_id) {
$link = mysqli_connect("localhost", "lunar_lunar", "", "lunar_users");
$qc = mysqli_query($link, "SELECT * FROM topics WHERE topic_cat='$cat_id'");
while($row = mysqli_fetch_array($qc)) {
$topic_title=$row['topic_subject'];
$topic_id=$row['topic_id'];
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2)) {
$cat_name=$row2['cat_name'];
}
echo $cat_name;
echo '<br />';
echo $topic_title;
echo '<br />';
echo $topic_id;
}
New issue is that its displaying like this:
http://gyazo.com/43e8a91b9e0cf4f5e413536907891dcf.png
When the DB looks like this:
http://gyazo.com/1ead8bd0f150838dae3ee4a476419679.png
It should be displaying all three of them and this is a function meaning it will keep redoing all the code until it can't query anymore data. Any ideas?

The problem here is that you're trying to echo the values outside your loop. The variables inside the loop will get overwritten on each iteration and at the end of looping, the variable will hold the value of the last iteration.
If you want to display all the values, move the echo statement inside your loop, like so:
while($row = mysqli_fetch_array($qc))
{
$topic_title = $row['topic_subject'];
$topic_id = $row['topic_id'];
echo $topic_title.'<br/>';
echo $topic_id.'<br/>';
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2))
{
$cat_name = $row2['cat_name'];
echo $cat_name.'<br/>';
}
If you care about the order, you could store the titles, ids and cat_names in arrays like so:
while($row = mysqli_fetch_array($qc))
{
$topic_title[] =$row['topic_subject'];
$topic_id[] = $row['topic_id'];
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2))
{
$cat_name[] =$row2['cat_name'];
}
And then loop through them:
for ($i=0; $i < count($topic_id); $i++) {
if( isset($topic_id[$i], $topic_title[$i], $cat_name[$i]) )
{
echo $cat_name[$i].'<br/>';
echo $topic_title[$i].'<br/>';
echo $topic_id[$i].'<br/>';
}
}

Your function displays only one result because your echo is outside the while loop...
Put the Echo statements inside the loop, or you will print only the last result!
while($row = mysqli_fetch_array($qc)) {
$topic_title=$row['topic_subject'];
$topic_id=$row['topic_id'];
echo $topic_title;
echo '<br />';
echo $topic_id;
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2)) {
$cat_name=$row2['cat_name'];
echo $cat_name;
echo '<br />';
}

Related

Query dont want to show all related post from table

I try to retrive all rows related to the specific category(continent table) but it only shows one and not all.
<?php
$townid = $_GET['id'];
$query = "SELECT * FROM towns INNER JOIN continents ON towns.catid = continents.id WHERE continents.id = '$townid'";
$row = mysqli_fetch_assoc(mysqli_query($link, $query));
// The category/Continent
echo '<h1>';
echo $row['catname'];
echo '</h1>';
//The post name/Town name
echo $row['title'];
?>
You need to call mysqli_fetch_assoc() in a loop.
$result = mysqli_query($link, $query);
$first = true;
while ($row = mysqli_fetch_assoc($result)) {
if ($first) { // Only show the category header once.
// The category/Continent
echo '<h1>';
echo $row['catname'];
echo '</h1>';
$first = false;
}
//The post name/Town name
echo $row['title'];
}
You can do something like:
<?php
$townid = $_GET['id'];
$query = "SELECT * FROM towns INNER JOIN continents ON towns.catid = continents.id WHERE continents.id = '$townid'";
$rows = mysqli_fetch_all(mysqli_query($link, $query), MYSQLI_ASSOC);
// The category/Continent
foreach ($rows as $row) {
echo '<h1>';
echo $row['catname'];
echo '</h1>';
//The post name/Town name
echo $row['title'];
}
?>
On another note, its better to parameterised your query since you are getting the $townid from a GET params.
This is how to do it in PHP https://www.php.net/manual/en/mysqli-stmt.bind-param.php

Search multiple row separate by comma from mysql using php

It is a tracking system like DHL. Tracking shipment number from MySQL database using php form.
but I need it Search multiple row separate by comma from mysql using php.
<?php
$ship=$_POST['Consignment'];
$cons = explode(',',$ship);
?>
<?php
$sql = "SELECT * FROM tbl_courier WHERE cons_no = '$cons[]'";
$result = dbQuery($sql);
$no = dbNumRows($result);
if($no == 1){
while($data = dbFetchAssoc($result)) {
extract($data);
?>
Shipment Name: <?php echo $ship_name; ?>
Shipment Phone: <?php echo $phone; ?>
<?php }//while
}//if
else {
echo 'In else....';
?>
Consignment Number not found.Search Again.
<?php
}//else
?>
So I need my search will work with separating by comma(,).
Thanks for helping me.
You can use IN operator in that case.
<?php
$ship=$_POST['Consignment'];
?>
<?php
$sql = "SELECT * FROM tbl_courier WHERE cons_no IN(".$ship.")";
$result = dbQuery($sql);
$no = dbNumRows($result);
if($no == 1){
while($data = dbFetchAssoc($result)) {
extract($data);
?>
Hope it will help to you.
change your sql query you have written '$cons[]' in select query which is wrong . after explode you will get data as 1,2,3 so you just need to write variable in query not array and user IN Operator like this.
`$sql = "SELECT * FROM tbl_courier WHERE cons_no IN(".$ship.")";`
You should always prepare/sanitize the POST data before using it in MySql query (in terms of security):
<?php
if (isset[$_POST['Consignment']] && !empty($_POST['Consignment'])) {
$ship = $_POST['Consignment'];
$cons = explode(',', $ship);
$cons = array_filter($cons, function($v){
return trim(strip_tags($v));
});
$cons = '"' . implode('","', $cons) . '"';
$sql = "SELECT * FROM tbl_courier WHERE cons_no IN ($cons)";
$result = dbQuery($sql);
$no = dbNumRows($result);
if ($no == 1) {
while ($data = dbFetchAssoc($result)) {
extract($data);
....
}
....
}
?>
Please Use Find IN SET
SELECT * FROM tbl_courier WHERE FIND_IN_SET(cons_no,'1,2,3,4,5')
Updated
SELECT * FROM tbl_courier WHERE FIND_IN_SET(cons_no,'$ship')
Note :- $ship Comma Separated Value not an array
I found the Answer:
if(isset($_POST['Consignment'])){
$ship=$_POST['Consignment'];
$shipment= explode(',',$_POST['Consignment']);
$ship = implode("', '",$shipment) ;
$query = "SELECT * FROM `tbl_courier` WHERE `cons_no` IN('$ship')";
$results = $mysqli->query($query);
if($results){
print '<table border="1">';
while($row = $results->fetch_assoc()) {
print '<tr>';
print '<td>'.$row["cons_no"].'</td>';
print '<td>'.$row["customerName"].'</td>';
print '<td>'.$row["customerPhone"].'</td>';
print '</tr>';
}
print '</table>';
// Frees the memory associated with a result
$results->free();
}
else {
echo "Query Not Match";
}
$mysqli->close();
}
Thanks to Answer.

How to access while array outside the loop in PHP

I want to access while array $row2 outside the loop so that I can compare in if else condition, because $row2 array contains many number. Is there any solution make $row array accessible outside the loop or any other method?
<?php
$sql = (" SELECT * FROM result ");
$query = mysqli_query($db, $sql);
while($row = mysqli_fetch_array($query)) {
$row2 $row['id'];
}
for($i=1;$i<=10;$i++) {
if ($i<= $row2) {
echo "<font color='red'><font size='50px'>".$i."</font></font>"."<br>";
continue;
} else {
echo $i.'<br>';
}
}
?>
If you want to loop over two dependent things you need to nest them or else $row2 will always contain the last value in the while loop:
<?php
$sql = (" SELECT * FROM result ");
$query = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($query)) {
$row2 = $row['id']; // I added an = sign here.
for($i=1;$i<=10;$i++) {
if ($i<= $row2) {
echo "<font color='red'><font size='50px'>".$i."</font></font>"."<br>";
continue;
} else {
echo $i.'<br>';
}
}
}
If this isn't what you want please clarify your question.
Pass your variable to a separate function that performs whatever task you want.
<?php
while($row = mysqli_fetch_array($query))
{
MyFunction($row2);
}
function MyFunction($passed_row2_value){
// perform whatever task you want here.
}
?>
This shows with some format the ids retrieved by the query and fills the blanks without format.
<?php
$sql = (" SELECT * FROM result ");
$query = mysqli_query($db, $sql);
$row2 = [];
while($row = mysqli_fetch_array($query)) {
$row2[$row['id']] = true;
}
for($i=1;$i<=10;$i++) {
if ($row2[$i]) {
echo "<font color='red'><font size='50px'>".$i."</font></font>"."<br>";
} else {
echo $i.'<br>';
}
}
?>

php while loop only displays one result for a mysql query across multiple tables

I am having an issue with a while statement only returning one result. this is my first time trying to display product information from several tables and I don't know what I'm doing wrong. here is the code:
<?php
require('./includes/config.inc.php');
require(MYSQL);
$sql = sprintf("SELECT * FROM tea");
$res = mysqli_query($dbc, $sql);
if(!$res){
die('Could not complete query: '.mysqli_error($dbc));
} else {
echo 'Success!<br />';
while($row = mysqli_fetch_array($res)){
$table = $row['category'];
$inum = $row['item_number'];
echo $table.' '.$inum.'<br />';
$fetch = sprintf("SELECT sub_category, item_name, description FROM $table WHERE item_number ='$inum'");
$fetchRes = mysqli_query($dbc, $fetch);
if(!$fetchRes){
die('Could not fetch: '.mysqli_error($dbc));
} else {
while($fetchRow = mysqli_fetch_array($fetchRes)){
$subCat = $fetchRes['sub_category'];
$iNumber = $inum;
$iname = $fetchRes['item_name'];
$desc = $fetchRes['description'];
echo $id.' '.$subCat.' '.$iNumber.' '.$iname.' '.$desc.'<br />';
}
}
}
}
Inside your while loop, you should be using the $fetchRow variable as the array from which to grab columns, such as 'sub_category'.
IS
$subCat = $fetchRes['sub_category'];
$iNumber = $inum;
$iname = $fetchRes['item_name'];
$desc = $fetchRes['description'];
Needs to be: Res to Row
$subCat = $fetchRow['sub_category'];
$iNumber = $inum;
$iname = $fetchRow['item_name'];
$desc = $fetchRow['description'];

Why does this query show only one result?

The query I have below will only show me one result even if there are multiple matching entries (completely or partially matching). How do I fix it so it will return all matching entries:
//$allowed is a variable from database.
$sql = "SELECT `users`.`full_name`, `taglines`.`name`, `users`.`user_id` FROM
`users` LEFT JOIN `taglines` ON `users`.`user_id` = `taglines`.`person_id`
WHERE ( `users`.`user_settings` = '$allowed' ) and ( `users`.`full_name`
LIKE '%$q%' ) LIMIT $startrow, 15";
$result = mysql_query($sql);
$query = mysql_query($sql) or die ("Error: ".mysql_error());
$num_rows1 = mysql_num_rows($result);
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
$person = htmlspecialchars($row['full_name']);
}
}
}
print $person;
Because your overwriting $person on each iteration.
Hold it in a $person[] array if your expecting more then one. Then loop through it with a foreach loop when you intend to output.
Not related but your also querying twice, you only need 1 $result = mysql_query($sql);
Update (Simple Outputting Example):
<?php
$person=array();
while($row = mysql_fetch_array($query)){
$person[] = array('full_name'=>$row['full_name'],
'email'=>$row['email'],
'somthing_else1'=>$row['some_other_column']);
}
//Then when you want to output:
foreach($person as $value){
echo '<p>Name:'.htmlentities($value['full_name']).'</p>';
echo '<p>Eamil:'.htmlentities($value['email']).'</p>';
echo '<p>FooBar:'.htmlentities($value['somthing_else1']).'</p>';
}
?>
Or an alternative way to is to build your output within the loop using concatenation.
<?php
$person='';
while($row = mysql_fetch_array($query)){
$person .= '<p>Name:'.$row['full_name'].'</p>';
$person .= '<p>Email:'.$row['email'].'</p>';
}
echo $person;
?>
Or just echo it.
<?php
while($row = mysql_fetch_array($query)){
echo '<p>Name:'.$row['full_name'].'</p>';
echo '<p>Email:'.$row['email'].'</p>';
}
?>

Categories