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);
Related
I want to pull rows from the database, attach a value to those rows, then order those rows based on a value. The problem is that in trying to do this via the while loop I get an error:
"Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW) in
C:\xampp\htdocs\productivitysuite\index.php on line 98"
My goal is to retrieve rows from a database and organize those rows based on a value I calculate in PHP php ($priority), then display certain values of those rows based on their priority. The problem is that I get this darn error and I don't know why, nor do I know where to look for help to resolve it! Hopefully SO can help diagnose this.
code:
<?php
$mysqli = mysqli_connect('127.0.0.1','root','', 'taskdb'); //open connection
//retrieve variables
$sql = "SELECT * FROM tasklist WHERE completion_flag = FALSE";
$sqldata = mysqli_query($mysqli,$sql) or die('error retrieving data');
//Display results
echo "<table>";
echo "<tr><th>Task</th><th>Type</th><th>Due Date</th>";
$counter = 0; //may need to make global, not sure
$results = array();
while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)){
//store each row as variables
if ($row['externalFlag'] == 1) {
$E = 1;
} else{
$E = 0.5;
}
//days until completion
$nowDate = date("m/d/Y");
$D = 1 / (date_diff($row['dueDate']- $nowDate));
//Activity category multiplier
if($row['taskType'] == "Daily"){
$C = 0.5;
} elseif($row['taskType'] == "Maintenance"){
$C = 0.2;
} elseif ($row['taskType'] == "School_Study") {
$C = 0.75;
} elseif ($row['taskType'] == "Personal_Project") {
$C = 0.80;
} elseif ($row['taskType'] == "Work_Project") {
$C = 0.65;
}
$U = ($C - (1 / $D))* $E; //urgency rating; SET PER ROW!
$I = $row['importance']; //Importance rating
$priority = $U + $I;
$results[] = ($row => $priority);
//The array
$priorityOutput = $priorityRow.$counter;
++$counter;
echo "<tr><td>";
echo $row['taskName'];
echo "</td><td>";
echo $row['taskType'];
echo "</td><td>";
echo $row['dueDate'];
echo "</td></tr>";
//Make the below its own loop where I output in order of decreasing UI value
}
//now we have an array of key => value pairs with rows tied to a priority.
//We need to organize the rows by the priority
arsort($results);
echo "</table>"
$mysqli->close(); //close connection
?>
This is a syntax error with your subarray declaration.
Change
$results[] = ($row => $priority);
To
$results[] = array($row => $priority);
Correction: $row is an array, that cannot be used as a key.
I think you might mean:
$results[]=array($row['taskName']=>$priority);
Or maybe:
$results[]=array($priority=>$row);
Depending on your preferred structure.
As an aside, I would replace your taskType conditional block with a lookup array as a matter of clean / more compact code which I believe is easier to maintain and read.
I have gone to the db and created an array of url's.
Then I go through the array and use xpath to tell me how many links there are per url.
This is where my head hurts.
I have a count for each url of the no of objects in each url. So I'm now trying to collect each of the nodevalues from part 2.
I'm obviously doing something wrong but need some guidence please
$items = array();
$query = "SELECT * FROM `urls`";
if( $result = mysqli_query($sql,$query));
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
while ($row = $result->fetch_assoc()) {
$items[] = $row;
}
}
echo '<pre>';
print_r($items);
// $product = array();
echo $rowcount;
for ($x=0; $x<$rowcount; $x++){
$scrapeurl[$x] = $items[$x][url];
echo $scrapeurl[$x];
$xpath[$x] = new XPATH($scrapeurl[$x]);
$urls[$x] = $xpath[$x]->query("//div[#class='infodata']/strong/a[contains(#id,'test_title')]/#href");
$count[$x] = $urls[$x]->length;
$data = array();
for ($i=0; $i<$count[$x]; $i++){
$data[$i]['url'] = $urls[$x]->item($i)->nodeValue;
$data[] = $data[$i]['url'];
}
echo '<pre>';
print_r($data);
A bit late apologies but resolved the issue. Maybe too tired but came down to a couple of issues.
Don't always believe what the browser renders in the HTML. Look at the source! I found that tbody as an example is filled into HTML by Firefox at least in reality the source was different so I was never going to hit the right node.
looping within loops - to remember when in a loop sometimes you have to loop again to drill down to the right result......
$data = array();
foreach($urls as $node){
foreach($node->childNodes as $child) {
$data[] = array($child->nodeName => $child->nodeValue);
}
}
$data = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
$data = iterator_to_array($data,false);
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);
I'm working on the following code:
function form_Subcat_Picker() {
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
if (!$mysqli) {
die('There was a problem connecting to the database.');
}
$catPicker = "SELECT Subcatid, Subcatname, Parentid
FROM ProductSubCats
ORDER BY Subcatid";
if ($Result = $mysqli->query($catPicker)){
if (!$Result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
while ($row = $Result->fetch_assoc()) {
echo '<div class="parentid'.$row['Parentid'].'">';
echo '<select name="Subcatid">';
echo '<option value="'.$row["Subcatid"].'">'.$row["Subcatname"]."</option>";
echo '</select>';
echo '</div>';
}
}
$mysqli->close();
}
What I want to do, is in the line:
while ($row = $Result->fetch_assoc()) {
echo '<div class="parentid'.$row['Parentid'].'">';
If the $row['Parentid'] part is the same as the previous iteration, I want to ignore that particular line (adding the div class)
So that if for example in the first run $row['Parentid'] is 1, and in the next loop it is 1 again, I want to not create a new div, just echo everything else and thus keep it in the same div.
Is this possible? Alternatively, how could I make multiple sub category id's and names appear in the one div, if they share a common parentid (there are multiple parent ids)
For the line:
echo '<option value="'.$row["Subcatid"].'">'.$row["Subcatname"]."</option>";
Maybe this would work:
$last_id = 0;
while ($row = $Result->fetch_assoc()) {
if ($last_id != $row['Parentid']) {
echo '<div class="parentid'.$row['Parentid'].'">';
echo '<select name="Subcatid">';
echo '<option value="'.$row["Subcatid"].'">'.$row["Subcatname"]."</option>";
echo '</select>';
echo '</div>';
$last_id = $row['Parentid'];
}
}
However, I think the best solution is to filter them out in the SQL statement, maybe the GROUP BY clause, but I'm not 100% sure how to do it :).
Regards,
That is just something basic for looping. Let's see your current loop:
while ($row = $Result->fetch_assoc()) {
...
}
As you want to skip with a specific condition, let's just introduce this skipping (not taking much care about the condition first):
while ($row = $Result->fetch_assoc()) {
if ($condition) continue;
...
}
Now let's formulate the condition. As we want to look into the last $row we need to keep a copy:
$last = null;
while ($row = $Result->fetch_assoc()) {
if ($condition) continue;
...
$last = $row;
}
Now we've got the data we need to have to create the condition, $last can contain the last row (if there was one) and therefore the comparison can be done:
$last = null;
while ($row = $Result->fetch_assoc()) {
$condition = $last && $row['Parentid'] === $last['Parentid'];
if ($condition) continue;
...
$last = $row;
}
And that is it basically. Depending on the logic, you might want to switch to a for loop:
for ($last = null; $row = $Result->fetch_assoc(); $last = $row) {
$condition = $last && $row['Parentid'] === $last['Parentid'];
if ($condition) continue;
...
}
This for example does ensure that for each iteration (even the skipped ones), the $last is set to the $row at the end of the loop.
Instead of continue you can naturally do different things, like not outputting the <div> or similar.
Hope this helps.
This is the way I'd write it.
// add a variable to hold the previous value
$previous_parent_id = "";
while ($row = $Result->fetch_assoc()) {
// then add an if statement to see if it's the previous statement
if ($row['parent_id'] != $previous_parent_id){
echo '<div class="parent_id'.$row['parent_id'].'">';
$previous_parent_id = $row['parent_id'];
}
}
So going in a loop on these records
ID ParentID
1 0
2 0
3 1
4 1
4 2
4 2
the output would be:
<div class="parent_id0">
<div class="parent_id1">
<div class="parent_id2">
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!).