Foreach loop with MySQL query - php

I have an array.
$select_crm=mysql_query("select * from party_details where subcaseid='$under_row[partyid]'");
$select_array=array($select_crm);
if(mysql_num_rows($select_crm)>0)
{
foreach($select_array as $v)
{
$fetch_crm=mysql_fetch_array($v);
echo $fetch_crm['party_name'];
echo $fetch_crm['partyid'];``
}
}
But it can't works properly. $select_crm have two rows but it print only one.

$select_array is an array with just one element: the query result resource. Therefore the foreach loop will only ever run once, printing only the first item.
Your loop should look like every single tutorial out there:
while($fetch_crm = mysql_fetch_assoc($v)) { ... }
Note fetch_assoc, not fetch_array. It is pointless to call fetch_array if you don't intend to use the numeric indices.

As far as I'm concerned, you have to do this:
$select_crm=mysql_query("select * from party_details where subcaseid='{$under_row['partyid']}'");
if(mysql_num_rows($select_crm)>0)
{
while ($select_array = mysql_fetch_assoc($select_crm))
{
echo $select_array['party_name'];
echo $select_array['partyid'];
}
}

$select_crm="select * from party_details where subcaseid='{$under_row[partyid]}'";
$crm = mysql_query($select_crm) or die(mysql_error());
$row_crm = mysql_fetch_assoc($crm);
$totalRows_crm = mysql_num_rows($crm);
if($totalRows_crm > 0) {
do {
/*foreach ($row_crm as $field) {
echo $field;
}*/
echo $row_crm['party_name'];
echo $row_crm['partyid'];
} while ($row_crm = mysql_fetch_assoc($crm));
}

do not use foreach , you should use in this way ,
$select_crm= mysql_query("select * from party_details where subcaseid='$under_row[partyid]'");
while($result = $db->fetchByAssoc($select_crm))
{
echo $result ['party_name'];
echo $result ['partyid'];
}

try this:
<?php
$select_crm =
mysql_query("select * from party_details where subcaseid='$under_row[partyid]'");
while($select_array = mysql_fetch_assoc($select_crm))
{
echo $select_array['party_name'];
echo $select_array['partyid'];
}
?>
hope it will help.
happy coding!

try this
$result = mysql_query("your select query");
while($row = mysql_fetch_assoc($result)){
echo $row['columnNam1'];
echo $row['ColumnName2'];
}

Use this:
$select_crm=mysql_query("select * from party_details where subcaseid='$under_row[partyid]'");
while($row=mysql_fetch_assoc($select_crm)) {
echo $row['party_name'];
echo $row['party_id'];
}

Your code is iterating over an array which only 2 lines above you explicitly created to have exactly one element ;-)
You have misplaced the use of mysql_fetch_assoc. Check out the manual page and the sample code there for your solution. (and while you are there, notice the big red DEPRECATED notice; read on!).

Related

Why is the array is always empty at this point despite the fact that I added data there?

$result = mysqli_query($con, "SELECT * FROM users");
$usersArray=[];
tableArrayPushData($result, $usersArray);
function tableArrayPushData($result, $tableArray){
while ($row = $result->fetch_assoc()) {
$str = '';
foreach ($row as $value) {
$str = $str.$value.'|';
}
$newStr = rtrim($str, "| ");
array_push($tableArray,$newStr);
}
}
for ($i=0; $i<count($usersArray); $i++){//array is always empty at this point
echo "Ok";
echo "<br>";
}
I don't understand why, but usersArray is empty despite the fact that I added data there.
The MySQL table has rows with data, so it can't be empty.
You should use the & operator to allow the function to access the outer variable, like this:
function tableArrayPushData($result, &$tableArray) {}
Or use return.

Removing Last Comma within while loop - PHP

I've been building a little tool to manage a dataset, I'm trying create a JSON output in order to serve my front-end the data.
Right now I have an extra comma at the end of every row in the loop. I need to remove it, it would be ideal if I can find a way to do this inside of the while loop.
Here is my code:
$sth = mysql_query("SELECT * FROM mapdata");
$num_rows = mysql_num_rows($sth);
$counter = 0;
echo '[';
while($r = mysql_fetch_assoc($sth)) {
if (++$counter == $num_rows) {
echo json_encode($r) . '';
}
else {
echo json_encode($r) . ',';
}
}
echo "]";
mysql_close($connection);
This is what I'm getting returned now
[
{"col1":"123","col2":"456","col3":"789",},
{"col1":"123","col2":"456","col3":"789",}
]
This is what I need.
[
{"col1":"data1","col2":"data2","col3":"data3"},
{"col1":"data1","col2":"data2","col3":"data3"}
]
Any suggestions would be greatly appreciated.
Your whole approach is wrong, you shouldn't try to create JSON by hand. Put all the rows in an array, and let json_encode() do it all for you.
$result = array();
while ($r = mysql_fetch_assoc($sth)) {
$result[] = $r;
}
echo json_encode($result);
I like to follow best practice whereever possible, but in this particular instance I needed to deviate from best practice due to some environment restrictions I had. I thought I'd share the solution I ended up using, regardless of it being overly complicated.
$sth = mysql_query("SELECT name,address,address2,city,state,postal,phone,lat,lng FROM mapdata");
$num_rows = mysql_num_rows($sth);
$counter = 0;
echo '[';
while($r = mysql_fetch_assoc($sth)) {
if (++$counter == $num_rows) {
echo preg_replace("/^,/",'',str_replace(',}','}',json_encode($r)));
}
else {
echo preg_replace("/^,/",'',str_replace(',}','}',json_encode($r)) . ',');
}
}
echo "]";
mysql_close($connection);

How to make a function for autoset

I'm not sure if it is possible or not but what I am looking for a way making auto "set" for mysql results.
function test(){
$pDatabase = Database::getInstance();
$site = new Template("sites.tpl");
$query = 'SELECT * FROM sites';
$result = $pDatabase->query($query) or die('Query failed: ' . mysql_error());
while ($row = mysql_fetch_array($result)) {
$site->set("id",$row['id']);
$site->set("category",$row['category']);
$site->set("name",$row['name']);
$site->set("html",$row['html']);
$site->set("css",$row['css']);
$site->set("js",$row['js']);
$site->set("php",$row['php']);
$site->set("details",$row['details']);
$site->set("link",$row['link']);
}
mysql_free_result($result);
}
Maybe there is a better way doing all that $site->set ? I mean my code looks way too big and pointless. Any other ways ?
If you want to call $site->set on all key/value pairs in $row
while ($row = mysql_fetch_array($result)) {
foreach($row as $key => $value) {
$site->set($key,$value);
}
}
Change to this...
Assuming your site->set function will always take the exact table column names.
while ($row = mysql_fetch_array($result)) {
foreach($row as $k=>$v){
$site->set($k,$v);
}
}
You could also alter teh $site->set function and do the loop there. And then just do this...
while ($row = mysql_fetch_array($result)) {
$site->set($row);
}
And the function. Just an outline. Not really sure what you have going on in the actual function. But this is just an idea
function set($arrorkey, $value=null){
// If passed value is an array, do this...
if(is_array($arrorkey)){
foreach($arrorkey as $k=>$v){
$_SESSION[$k] = $v;
//Or database binding or whatever you're actually doing inside here
}
} else {
// If passed value, is a column, and value pair...do this.
$_SESSION[$arrorkey]=$value;
//Or database binding or whatever you're actually doing inside here
// This is just an example
}
return;
}

Handling PHP array of unknown size

I have the following code that should select all the users in the relevant table in my database:
$hof = mysql_query("SELECT * FROM users");
$name = array();
$website = array();
$i=0;
while($result = mysql_fetch_array($hof)){
$name[$i] = $result['company'];
$website[$i] = $result['website'];
}
$i++;
I want to echo out the names and websites of all in the html section of my script (below the php) which will be a Hall of Frame of sorts. How would i do is? The fact that i do not know the size of the array deters me.
Usually, if i knew the size, i would so something like:
<?php echo $name[1];?>
<?php echo $name[2];?>
//and so on
Many thanks in advance. P.S. I plan to move across to MySQLi when i have the functionality of the website sorted first on localhost. Cheers
Your $i++; statement should be inside while loop
while($result = mysql_fetch_array($hof)){
$name[$i] = $result['company'];
$website[$i] = $result['website'];
$i++;
}
Better You do it like this,
$rows = array();
while($result = mysql_fetch_assoc($hof)){
$rows[] = $result;
}
and you echo them like this,
<?php
$len = count($name);
for($i=0;$i<$len;$i++){
echo $name[1];
}
?>
And for the alternative method use this,
<?php
foreach($rows as $row){
echo $row['name']; // use $row['website'] to echo website.
}
?>
foreach($name as $key=>$value){
echo $name[$key];
echo $website[$key];
}
Also there no need to take $i++, you can use following way
while($result = mysql_fetch_array($hof)){
$name[] = $result['company'];
$website[] = $result['website'];
}
See array in manual
First off the $i++ should be inside the loop.
To output them all, you could use implode(), or maybe foreach.
First, take your data into array
$data = array();
$sql = "SELECT * FROM users";
$res = mysql_query($sql) or trigger_error(mysql_error()."[$sql]");
while($row = mysql_fetch_array($res)){
$data[] = $row;
}
then use it anywhere you wish, say, in the template:
<ul>
<? foreach($data as $row): ?>
<li><?=$row['company']?></li>
<? endforeach ?>
</ul>
How about:
foreach ($name as $val)
{
echo $val;
}
you can use mysql_num_rows() to know the number of results returned by your query
$arrarySize = mysql_num_rows($hof);

Displaying an associative array in PHP

I am trying to build a function that extracts information from a database and inserts it into an associative array in PHP using mysql_fetch_assoc, and return the array so another function can display it. I need a way to display the returned assoc array. This should be a different function from the first one
print_r($array) will give nicely formatted (textually, not html) output.
If you just want information about what is in the array (for debugging purposes), you can use print_r($array) or var_dump($array), or var_export($array) to print it in PHP's array format.
If you want nicely formatted output, you might want to do something like:
<table border="1">
<?php
foreach($array as $name => $value) {
echo "<tr><th>".htmlspecialchars($name).
"</th><td>".htmlspecialchars($value)."</th></tr>";
}
?>
</table>
This will, as you might already see, print a nicely formatted table with the names in the left column and the values in the right column.
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $column => $value) {
//Column name is in $column, value in $value
//do displaying here
}
}
If this is a new program, consider using the mysqli extension instead.
Assuming you've made the call, and got $result back:
$array = new array();
while($row = mysql_fetch_assoc($result)){
$array[] = $row;
}
return $array;
This should get you going:
$rows = mysql_query("select * from whatever");
if ($rows) {
while ($record = mysql_fetch_array($rows)) {
echo $record["column1"];
echo $record["column2"];
// or you could just var_dump($record); to see what came back...
}
}
The following should work:
$rows = mysql_query("select * from whatever");
if ($rows) {
$header = true;
while ($record = mysql_fetch_assoc($rows)) {
if ($header) {
echo '<tr>';
foreach (array_keys($record) AS $col) {
echo '<td>'.htmlspecialchars($col).'</td>';
}
echo '</tr>';
$header = false;
}
echo '<tr>';
foreach (array_values($record) AS $col) {
echo '<td>'.htmlspecialchars($col).'</td>';
}
echo '</tr>';
}
}
(Yes, blatant mod of Fosco's code)
This should print the column headers once, then the contents after that. This would print just whatever columns were retrieved from the DB, regardless of the query.

Categories