I'm looping through some mysql results and need to add <span id=bottom></span> to each of them except the last row. What's the easiest way of doing this?
Will I have to count rows and then use a counter and an if/else statement? Or is there an easier method?
Try something like this:
$result = mysql_query($sql);
$list = array();
while($row = mysql_fetch_assoc($result))
{
$list[] = $row;
}
$lastItem = array_pop($list);
foreach($list as $item) {
echo sprintf('<span id="bottom">%s</span>', $item['value']);
}
// do something with the last item..
Not very short, but that would do the trick. Alternatively you could do what you suggested:
$result = mysql_query($sql);
$num = mysql_num_rows($result);
for($i = 0; $i < $num-1; $i++) {
$element = mysql_fetch_assoc($result);
// echo here..
}
$item = mysql_fetch_assoc($result); // fetch last item..
Best wishes,
Fabian
I'm not a PHP expert, but can you put each row in an array? That way to know the length and you can loop through the array.
$result = mysql_query($sql);
$list = array();
while($row = mysql_fetch_assoc($result))
$list[] = $row;
foreach(array_slice($list, 0, -1) as $item) {
echo sprintf('<span id="bottom">%s</span>', $item['value']);
}
// do something with the last item..
You can avoid copying all the data before processing it if you fetch a record in advance before printing it (or the other way round: process the previously fetched record)
foreach( $pdo->query('SELECT x FROM foo') as $r) {
if ( isset($row) ) {
echo '<span>', $row['x'], '</span>';
}
$row = $r;
}
if ( isset($row) ) {
echo $row['x'];
}
Related
I'm trying to get the following output from mysql for Google Line Chart API:
[["product","diameter","width"],["Product 1","2","4"],["Product 2","4","8"]]
I have set up several input checkboxes to send field names (e.g width,diameter) to the database via $_POST["info"] and retrieve the values from those fields. Here's the part that generates the data from mysql:
$result = $users->fetchAll();
$comma = "";
$data="";
$data[0] = array_merge(array(product),$info);
$i = 1;
foreach ($result as $r)
{
foreach($_POST["info"] as $p)
{
$d .= $comma.$r[$p]; // trying to get "$r["width"],$r["diameter"]"
}
$comma = ",";
$data[$i] = array($r["name"], $d);
$i++;
}
echo json_encode($data);
My desired output should be like this:
[["product","diameter","width"],["Product 1","2","4"],["Product 2","4","8"]]
But that code is generating duplicated results like this
[["product","diameter","width"],["Product 1","24"],["Product 2","24,4,8"]]
I guess I shouldn't be using the nested foreach to loop over $_POST. Can anyone tell me how to fix that?
Full PHP Code:
$info = $_POST["info"]; // It contains an array with values like width,diameter,thickness etc...
$comma = "";
foreach($info as $in)
{
$field .= "".$comma."b.".$in."";
$comma = ",";
}
$sql = "
SELECT {$field},a.user_id,a.name
FROM `product_detail` a INNER JOIN
`attr` b ON a.model = b.model
WHERE a.user_id = ?
GROUP BY a.model
";
$users = $dbh->prepare($sql);
$users->bindValue(1, $_SESSION["user_id"]);
$users->execute();
$result = $users->fetchAll();
$comma = "";
$data="";
$i = 1;
$data[0] = array_merge(array(product),$info);
foreach ($result as $r)
{
foreach($_POST["info"] as $p)
{
$d .= $comma.$r[$p];
}
$comma = ",";
$data[$i] = array($r["name"], $d);
$i++;
}
echo json_encode($data);
$_POST["info"] Content:
Array
(
[0] => diameter
[1] => width
)
try it like this:
$result = $users->fetchAll();
$data="";
$data[0] = array_merge(array(product),$info);
$i = 1;
foreach ($result as $r)
{
$d[]=$r["name"];
foreach($_POST["info"] as $p)
{
$d[]= $r[$p];
}
$data[$i] = $d;
$d=array(); //set $d to empty not to get duplicate results
$i++;
}
echo json_encode($data);
The end result you are looking for, is valid JSON. You should not try to manually generate that.
Instead you should make an array of arrays in php and use json_encode($array) to get the result you are looking for.
Also note that by injecting your POST variables directly in your query, you are vulnerable to sql injection. When accepting fields, you should check them against a white-list of allowed values.
Try the below solution:
$result = $users->fetchAll();
$data="";
$data[0] = array_merge(array(product),$info);
$i = 1;
foreach ($result as $r)
{
$d = array();
foreach($_POST["info"] as $p)
{
$d[] = $r[$p]; // trying to get "$r["width"],$r["diameter"]"
}
$data[$i] = array($r["name"]) +$d;
$i++;
}
echo json_encode($data);
If i echo inside the while loop i get 4,2 values and if i echo outside the while loop then i only get 2. I want to get the data from $row into the values array. is something missing in this code?
$query = oci_parse($con, "SELECT count(*) FROM Counter GROUP BY Blog_name");
oci_execute($query);
while($row = oci_fetch_array($query))
{
$s = $row[0].',';
$values = explode(',', $s);
echo $values[0]; // 4
echo $values[1]; // 2
}
echo $values[0]; // 2
echo $values[1]; // 2
Try this,
$Values = array();
while($row = oci_fetch_array($query))
{
$Values[] = $row[0];
}
echo $Values[0];
First, $values as you're using it is just a string, and is not an array.
Try adding before the while loop.
$values = array();
Second, there's really no need to use explode here, it's an unnecessary step. If you only want the first column in the row, you can simply add that column to $values. (Currently you are overwriting the contents of $values at each iteration of the loop because you are missing the [].)
$values[] = $row[0];
If you're trying to put ALL of the columns in each row into values, try:
$values[] = $row;
If you're trying to individually put the contents of each column into it's own index in $values, try:
while($row = oci_fetch_array($query))
{
foreach($row as $column)
{
$values[] = $column;
}
}
Do like this:
$s = array();
while($row = oci_fetch_array($query)) {
$s[] = $row[0];
}
echo $s[0];
print_r($s);
$query = oci_parse($con, "SELECT count(*) FROM Counter GROUP BY Blog_name");
oci_execute($query);
$values = array();
while($row = oci_fetch_array($query))
{
$values[] = $row[0];
}
print_r($values);
I'm trying to get the value of $row->price for the last iteration in my for loop as below
foreach ($getprices->result() as $row)
{
if ($bb=='on'){
$pric = $row->price+2.50;
$pri = number_format($pric,2);
}else{
$pric = $row->price;
$pri = number_format($pric,2);
}
I did try the following, however it didn't appear to work
$numItems = count($getprices->result());
$i = 0;
foreach($getprices->result() as $row) {
if(++$i === $numItems) {
if ($bb=='on'){
$pric = $row->price+2.50;
$pri = number_format($pric,2);
}else{
$pric = $row->price;
$pri = number_format($pric,2);
}
}
}
Any suggestions?
Use $row->price just after the loop has ended:
foreach ($getprices->result() as $row)
{
// ...
}
$lastprice = $row->price;
This is really just a trick, but it will work. If you are iterating over an array you can also do it like this:
$array = $getprices->result();
foreach ($array as $row)
{
// ...
}
$lastprice = end($array)->price; // this will work independently of any loop
Add a line $lastitem=$row right after the for statement ; it will contain the last value after the loop is finished
You can use php end to get the last value of an array.
eg;
$arr = $getprices->result();
$last = end($arr);
$result = mysql_query($sql_result);
$newArray = array();
$index=0;
while($row = mysql_fetch_assoc($result)){
$newArray[$index] = $row;
$index++;
}
I wanna ignore the value - from my assoc array when display. Help me please.
If you want to remove all columns containing a certain value you could use array_filter:
function removeEmpty($v){
return $v != '-';
}
while($row = mysql_fetch_assoc($result)){
$newArray[$index] = array_filter($row,"removeEmpty");
$index++;
}
I have a little problem I can't figure out how to solve.
I have an SQL result with 3 rows and I want to put the id from each row into a static marker ie.
MARKER_1 = 4
MARKER_2 = 5
MARKER_3 = 6
How can I do that so I get my static markers but with dynamic values?
I can't do it with a normal
while($row = mysql_fetch_array($result)) {
}
$i = 1;
while($row = mysql_fetch_array($result)) {
if($i == 1) {
$marker_1 = $row;
} elseif($i == 2) {
$marker_2 = $row;
} elseif($i == 3) {
$marker_3 = $row;
}
$i++;
}
i would recommend using an array like this
$results = array();
while($row = mysql_fetch_array($result)) {
$results[] = $row;
}
and then access it via:
$results[0] // or $results[1] and so on. you can even loop that :)
hope that helps
Hope this helps
while($row = mysql_fetch_array($result)) {
echo "MARKER_".$row['id'];
echo"=". $row['value'];
}