Store data into array variable php - php

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);

Related

getting duplicated results from nested foreach loop

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);

Ignore value from assoc array when display

$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++;
}

Exclude last comma in php array

I have a simple database connection:
$rowdata = mysql_query("SELECT * FROM table_names");
while($row = mysql_fetch_array($rowdata)) {
echo "".$row['name'].",";
}
I would like it to print out:
Adam, Sophia, Tom, Brian
instead of:
Adam, Sophia, Tom, Brian,
How do I exclude the last comma in the best way?
$rowdata = mysql_query("SELECT name FROM table_names");
$names = array();
while($row = mysql_fetch_array($rowdata)) {
$names[] = $row['name'];
}
echo implode(', ', $names);
Instead of echoing it straight out, put it into a variable (named $values perhaps) then do:
$values = rtrim($values,",");
Print the comma before each entry and omit the first one:
$first = TRUE;
while(($row = mysql_fetch_array($rowdata)) !== FALSE) {
if(!$first) echo ',';
echo htmlspecialchars($row['name']);
$first = FALSE;
}
Another way would be to use extract echoing the first line from the loop, that way the if statement does not have to be evaluated each iteration (premature optimization ftw!):
if(($row = mysql_fetch_array($rowdata)) !== FALSE)
echo htmlspecialchars($row['name']);
while(($row = mysql_fetch_array($rowdata)) !== FALSE) {
echo ',', htmlspecialchars($row['name']);
}
And finally you can do it in mysql:
select group_concat(name) from table_names
In full this would become:
$rowdata = mysql_query("SELECT group_concat(name) as names FROM table_names");
while($row = mysql_fetch_array($rowdata)) {
echo $row['names'];
}
$rowdata = mysql_query("SELECT * FROM table_names");
$names = array();
while($row = mysql_fetch_array($rowdata)) {
$names[] = $row['name'];
}
echo implode( $names, ',' );
By the way, if you're only using the 'name' column, it's better to do SELECT name FROM ..
Make it ..
$names = array();
while ( $row = mysql_fetch_array( $rowdata ) ) {
$names[] = $row['name'];
}
$names = implode(', ', $names);
echo $names;

Add string to all looped items except the last one

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'];
}

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