issue with variable scope in foreach condition - php

let have a look in my script. below i am getting no values in while i am assigning the value to variable $specdata
$result = mysqli_query($connection, "select * from productrates");
if (mysqli_num_rows($result) > 0)
{
echo "<div class='box-body'>";
$header='';
$rowdata='';
$header='<tr>';
$field= mysqli_fetch_fields($result);
foreach ($field as $val) {
if($val->name !="specs")
{
$header.= "<th style='background:#E1E1E1'>".$val->name."</th>";
}
}
$header.='</tr>';
while ($row = mysqli_fetch_array($result))
{
$field= mysqli_fetch_fields($result);
$rowdata.="<tr class='linehover'>";
// in this section i want to show $specdata values in div id="specs"
foreach ($field as $val)
{
$specdata ='';
if($val->name =="specs")
{
$specdata = $row[1];
echo $specdata;echo "<hr>";
}
if($val->name !="specs")
{
if($val->name == "Product")
{
$rowdata.= "<td class='nohover'>".$row[$val->name]."<div id='specs'>".$specdata."</div></td>";
}
else
{
$rowdata.= "<td>".$row[$val->name]."</td>";
}
}
}
$rowdata.='</tr>';
}
}
mysqli_free_result($result);
echo '<table class="table table-bordered" id="pricelist">'.$header.$rowdata.'</table></div>';
// but every i am getting null value in that div

Let's chop the unimportant bits out and look at this
foreach ($field as $val)
{
$specdata ='';
if($val->name =="specs")
{
$specdata = $row[1]; // no clue what $row[1] holds
echo $specdata; echo "<hr>";
}
if($val->name !="specs")
{
echo $specdata; // $specdata = '';
}
}
Remember, $specdata is being set to an empty string every time the loop starts over. So even if you set it to $row[1] this time, it will be an empty string on the next iteration. So if($val->name !="specs") will always give you an empty string.

Have you checked that the value of '$val->name'? because if it is different from "specs"
it will not pass on your first condition:
if($val->name =="specs")
just will not fill the variable $specdata
just to give you a hint it might be better to build this code to switch case like:
foreach ($field as $val)
{
$specdata = '';
switch ($val->name) {
case "specs":
$specdata = $row[1];
echo $specdata;echo "<hr>";
break;
case "Product":
$rowdata.= "<td class='nohover'>".$row[$val->name]."<div id='specs'>".$specdata."</div></td>";
break;
default:
$rowdata.= "<td>".$row[$val->name]."</td>";
}

Related

How do I get column name by row in MysQLI?

How do I return the column name in mysqli by row?
...
$result = $mysqli->query("SELECT * FROM `xtdf` WHERE posterid='bike'");
$rows=mysqli_fetch_array($result);
foreach($rows as $column => $value) {
echo $column . " " . $value;
}
...
This code above will return all columns name and values, but I want only the column name by the value. I have tried this code below but returns nothing.
...
$result = $mysqli->query("SELECT * FROM `xtdf` WHERE posterid='bike'");
$rows=mysqli_fetch_array($result);
foreach($rows as $column => $value) {
if ($value == "bike") {
echo $column;
}
}
Edit: I don't want put the result in array, or bring all results. Only return one value.
PHP version: 5.5.15
What should I do?
This should do the trick
while($row=mysqli_fetch_array($result)) {
foreach($row as $column => $value) {
if ($value == "bike") {
echo $column;
}
}
}
You need to iterate through all values that you fetch from database.
Try This:
while($rows=mysqli_fetch_assoc($result)){
foreach($rows as $column => $value) {
if ($value == "bike") {
echo $column;
}
}
}
good luck

Echo array values of column not working

I want to display the values of my array. but instead of displaying:
1509 1510 1511 it display ArrayArrayArray. What does it mean?
include("db_PSIS.php");
$sql_dc = "SELECT Child, Datecode
FROM traveller_merging15
WHERE Parent='" . $_REQUEST["txt_traveller_no"] . "'
ORDER BY Merge_ID ASC";
$res_dc = mysql_query($sql_dc);
$dcode1 = $row_dc['Datecode'];
$storeArray = array();
if (!$res_dc) {
echo "No data fetched!";
} else {
while ($row_dc = mysql_fetch_array($res_dc, MYSQL_ASSOC)) {
$storeArray[] = $dcode1;
echo "{$storeArray} <br>";
}
//$str_dc=implode(",",$storeArray);
//echo $str_dc;
}
You are assign the value of $row_dc['Datecode']; before fetch data from database. You need to do fetch data inside while loop and echo it
$res_dc = mysql_query($sql_dc);
if (!$res_dc) {
echo "No data fetched!";
} else {
while ($row_dc = mysql_fetch_array($res_dc, MYSQL_ASSOC)) {
echo $row_dc['Datecode'];
}
}
Note:- mysql is deprecated instead use mysqli or PDO
else {
while ($row_dc = mysql_fetch_array($res_dc, MYSQL_ASSOC)) {
$storeArray[] = $dcode1;
echo "{$storeArray} <br>";
}
instead try
else {
while ($row_dc = mysql_fetch_array($res_dc, MYSQL_ASSOC)) {
$storeArray[] = $dcode1;
echo "{$storeArray[0]} <br>";
}
Try this,
else {
while ($row_dc = mysql_fetch_array($res_dc, MYSQL_ASSOC)) {
$child = $row_dc['Child'];
$Datecode = $row_dc['Datecode'];
echo "$child <br> $Datecode";
}
if you are getting more that 1 row, use for() loop
else {
while ($row_dc = mysql_fetch_array($res_dc, MYSQL_ASSOC)) {
$count = count($row_dc);
for($i = 0; $i < $count; $i ++){
$child = $row_dc[$i]['Child'];
$Datecode = $row_dc[$i]['Datecode'];
echo "$child <br> $Datecode";
}
}
-first array don't print value using echo
-use print_r($array) to print key value pair(print a array)
your solution is
$i = 0;
while ($row_dc = mysql_fetch_array($res_dc, MYSQL_ASSOC)) {
$storeArray[$i] = $dcode1;
echo $storeArray[$i].'<br>';
$i++;
}
NOTE::-- Use single Quote instead of double Quote and mysql is deprecated instead use mysqli or PDO

PHP better solution than for each loop

I have this timetable where a first loop a bunch of members from the database with and while-loop. Inside the while-loop I have an foreach-loop. How ever, the foreach-loops makes the whole timetable very slow, and I need an different approach to this problem.
What it looks like now.
$sql = mysql_query("SELECT * FROM tblstaff ORDER BY strName ASC");
while($row = mysql_fetch_array($sql))
{
$user_id = $row['intId'];
$arr = array($one, $two, $three, $four, $five, $six, $seven);
foreach ($arr as $w) {
$week = $w;
$sql_offtime = mysql_query("SELECT tbloffwork.intId, tbloffwork.intWhoId, tbloffwork.strWeek
FROM tblstaff, tbloffwork
WHERE tbloffwork.intWhoId = '$user_id' AND tbloffwork.strWeek = '$week'");
$rwOff = mysql_fetch_array($sql_offtime);
$sql_work = mysql_query("SELECT DISTINCT tblstaff.intId as staffId, tblstaff.strName, tblworktable.intId, tblworktable.intWhoId, tblworktable.strElapsed, tblworktable.strNotes
FROM tblstaff, tblworktable
WHERE tblworktable.intWhoId = '$user_id' AND tblworktable.strElapsed = '$week'");
$rw_work = mysql_fetch_array($sql_work);
if($rwOff['strWeek'] == $week) {
$td_stat = "timetable-td-background-yellow";
} elseif($rw_work['strElapsed'] != "") {
$td_stat = "timetable-td-background-green";
} else {
$td_week = "timetable-td-background-red";
}
if($rw_work['strNotes'] != ""){
$notes = "<i class='fa fa-pencil-square-o mediumsmall'></i>";
} else { $notes = $null; }
echo "<td align='right' valign='top' id='timetable-td-small-square' class='". $td_week ."''>". $notes ."</td>";
}
}
Is there a better way to approach this instead of going with the foreach method?
foreach makes a copy of the set, you can use while instead
while (list($key, $value) = each($arr)) {
echo "Key: $key; Value: $value<br />\n";
}
http://php.net/manual/en/control-structures.foreach.php

PHP duplicate output

I have a while loop fetching a row and I'm trying to create a structure so that each row will create 2 links. The first is a German word and the second being an English one. The output I'm getting is repeated as if the row isn't being incremented. I've narrowed it down to this:
PHP:
while ($row = $database->row()->fetch()) {
foreach ($row as $value) {
$this->data .= $value . "!";
}
list($this->pid, $this->german, $this->english) = explode("!", $this->data);
$this->links .= "$this->german<br/>$this->english<br/>";
}
Output:
die Männer
men
die Männer
men
$row = array();
while ($row = $database->row()->fetch()) {
$row[] = $row;
}
foreach ($row as $value)
{
$this->data .= $value . "!";
list($this->pid, $this->german, $this->english) = explode("!", $this->data);
$this->links .= "$this->german<br/>$this->english<br/>";
}
I've solved the problem by looking at the keys and creating variables based on a simple matched string test. If anyone can improve my answer I would like to hear it. Thanks.
PHP:
while ($row = $database->row()->fetch()) {
while(list($key, $value) = each($row)) {
if ($key == "PID") {
$this->pid = $value;
}
if ($key == "german") {
$this->german = $value;
}
if ($key == "english") {
$this->english = $value;
}
}
$this->links .= "$this->german<br/>$this->english<br/>";
}

php function to return SQL results

This is what i have
function GetEventsList(){
$result = mysql_query("SELECT * FROM `events`") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
$en = $row['name'];
$endt = $row['date'];
$push = "<option value=$id>$en - $endt</option>";
return $push;
}
}
Its only returning 1 result, when there are 3 in the table
That's because you're returning from the function at the end of the first iteration. Try:
function GetEventsList() {
$result = mysql_query("SELECT * FROM `events`") or trigger_error(mysql_error());
$push = '';
while ($row = mysql_fetch_array($result)) {
foreach($row AS $key => $value) {
$row[$key] = stripslashes($value);
}
$id = $row['id'];
$en = $row['name'];
$endt = $row['date'];
$push .= "<option value=$id>$en - $endt</option>";
}
return $push;
}
On a side note: if you used good formatting/indenting that would've been far easier for you to spot.
Also, are you sure you need to use stripslashes()?
If I'm reading the code correctly, return $push; is exiting the while loop prematurely. You want to return only after all results are gathered and stored in something.
Either use echo $push in your foreach loop; or put each iteration of the option element into an array, then insert the array as needed.

Categories