Foreach loop only outputting one value - php

I have a foreach loop that should add a row to the table "notifications"
$infoquery = "SELECT `user_id` FROM reply WHERE `post_id` = '" .$replyid. "'";
$identifier = mysqli_query($dbc, $infoquery);
$rows = mysqli_fetch_array($identifier);
foreach(array_unique($rows) as $row){
$core->addNotification($row['user_id'], $link, $description);
}
however it is only adding one value, when it should add two notifications, one for user 1 and one for user 3

You are fetching only one single row, it should be like this:
$infoquery = "SELECT `user_id` FROM reply WHERE `post_id` = '" .$replyid. "'";
$identifier = mysqli_query($dbc, $infoquery);
while($row = mysqli_fetch_array($identifier)){
$core->addNotification($row['user_id'], $link, $description);
}

Aside from tkausl's correct answer, your other problem is unique visitors: array_unique compares the string values of an the items in the array.
Let's look at this:
var_dump(strval(array("bob")), strval(array("ed")));
Which outputs:
string(5) "Array"
string(5) "Array"
(and a whole load of errors).
So, as their string representation is the same, if you expect an multidimensional array array(array("user"=>"bob"),array("user"=>"ed")), you will remain with only one entry in there. Now, there's a whole lot of ways to work around that in PHP, but your database is better at it, use:
SELECT DISTINCT `user_id` FROM reply WHERE `post_id` = '" .$replyid. "'";
(But do look into prepared statements instead of adding raw parameters / query building).

Alternatively if you have a small result set, you could use that result to get all the data at once and avoid using iteration to fetch the data by using $result->fetch_all according to the manual (see http://php.net/manual/en/mysqli-result.fetch-all.php), as follows:
<?php
$query = "SELECT `user_id` FROM reply WHERE `post_id` = '" .$replyid. "'";
$identifier = mysqli_query( $dbc, $query );
$result = $mysqli->query( $query );
$rows = $result->fetch_all( MYSQLI_ASSOC );
foreach ( $rows as $row ) {
$core->addNotification( $row['user_id'], $link, $description );
}

Related

php foreach loop SQL table name query

I have this php code to do a query foreach loop going through the table name in variable $rowA but I got an "Array to string conversion" error. Does anyone know why? Can we do a query loop this way?
$sql = "SELECT `id`, `first_name` FROM `clients` ORDER BY `id` DESC";
$result = $DB_CON_C->query($sql);
$sql_email = "SELECT `email` FROM `clients` ORDER BY `id` DESC";
$account = $DB_CON_C->query($sql_email);
foreach($result as $row) {
foreach($account as $rowA) {
$stmt = "SELECT SUM(value) AS total_amount FROM `".$rowA."`";
$amount = $DB_CON_C->query($stmt);
$sum = $amount->total_amount;
$data_row .= '<tr>'
. '<td>' .$row['id'].'</td>'
. '<td>' .$row['first_name'].'</td>'
. '<td>' .$sum.'</td>';
}
}
}
$data_row .= '</tbody>'
. '</table>';
echo $data_row;
There seems to be a fundamentally odd issue with the way you are handling your data values.
Take your first query, $result, this will (obviously depending on the exact $DB_CON_C class method) output an array of values for id and first_name
Yet on the second call, $account using the same method you are then calling the values as if they're class variables $amount->total_amount.
I would suspect that one of these syntax is wrong, but without seeing your class I can't say which.
Do you realise that your two SQL calls are both returning the whole database?
Do you realise that you're using the data value (email address) in one table as the column name in another table? This can work, but this really isn't best practise.
You do not need to use the concaenator . for strings over new lines.
$string = "Hello
this string works fine";
as white space is reduced to one character length in HTML so it doesn't matter (much).
Solving your issue:
var_dump($account) once the value has been populated, same with $results, do var_dump($results) and see what is in the value, if these are class variables or arrays of data?
Seeing that both your variables are calling different parts of the same table, I have rewritten your code below:
$sql = "SELECT `id`, `first_name`, `email` FROM `clients` ORDER BY `id` DESC";
$result = $DB_CON_C->query($sql);
/***
* $result is assumed to be an array, within which is a set of values such as:
* $result[0]['id']
* $result[0]['first_name']
* $result[0]['email']
* $result[1]['id'], etc.
***/
foreach($result as $row) {
$stmt = "SELECT SUM(value) AS total_amount FROM `".$row['email']."`";
$amount = $DB_CON_C->query($stmt);
/***
* this is inconsistent, your data structure must be like $result as it
* uses the same methods, therefore you will need to enter the first
* "row" before getting the 'total_amount' value
***/
$sum = $amount[0]['total_amount'];
$data_row .= '<tr>
<td>' .$row['id'].'</td>
<td>' .$row['first_name'].'</td>
<td>' .$sum.'</td>
</tr>'; //you forgot your /tr !!
}
// Always clean up after foreach loops.
unset($row);
$data_row .= '</tbody>
</table>';
echo $data_row;
You're trying to parse a database row to a string, even though it contains only one thing.
Change the following line
$stmt = "SELECT SUM(value) AS total_amount "
. "FROM `".$rowA."`";
to
$stmt = "SELECT SUM(value) AS total_amount "
. "FROM `".$rowA['email']."`";
$rowA is a database row and contains the email field from the database.

array in foreach loop

I'm taking data from mysql database table. The table have ID and "POST" columns. I've ordered posts by id's from bottom so i always have the newest post on the first place. But when i want to echo specific post (eg. with id 5) i can't echo it with $col = mysqli_fetch_array($result); echo $col;. I've tried with foreach loop but it echo's all posts. So I thought if i could put them into array with foreach loop it would do the job.
$sql = "SELECT * FROM `post` ORDER BY `id` DESC";
$result = mysqli_query($con, $sql);
$col = mysqli_fetch_array($result);
foreach($col as $cols) {
}
I've tried a lot of things and spent a lot of time on research but still don't have idea how to do it.
Thanks for your ideas and help.
$sql = "SELECT * FROM `post` ORDER BY `id` DESC";
$result = mysqli_query($con, $sql);
$col = mysqli_fetch_array($result);
foreach($col as $cols) {
if($col['id'] == 5) {
print_r($col);
}
}
mysqli_fetch_array fetchs a result row as an associative, a numeric array, or both.
You need to specify the name of the column you want to print out.
Because you may have more than one row in your result set, you should use a loop (while) like so:
while ($row = mysqli_fetch_array($result)) {
echo $row['POST']; // 'POST' here is the name of the column you want to print out
}
Hope this helps!
UPDATED:
If you want to get a specific post, you have to change your SQL to something like this:
$sql = "SELECT * FROM `post` WHERE `id` = $wanted_post_id";

Searching for Id in MySql from an array using For Loop

I have an array of tag names which I passed via POST Method and I these tag names has its corresponding tag_id in the database. All I want is to search the id while iterating the array of tag names and I want the result of each query to be stored in an empty array. I think I just misunderstood something or what.
$tags_array = ['shoes','gadgets','fashion','food'];
$tags_array_id = [];
$tags_sql = '';
foreach ($tags_array as &$tag) {
$sql = "SELECT tag_id FROM `tbltag` WHERE tag_name = ".$tag." group by tag_name";
$query = mysqli_query($conn, $sql);
$result = mysqli_fetch_row($query);
$tags_array_id[] = $result[0];
};
Please help guys, suggestions highly appreciated.
Basically something like:
$sql = "SELECT * FROM `tbltag` WHERE tag_name IN('".implode("','", $tags_array)."')";
One last comment: You probably want to search for tag_id's instead of tag names, as you'll probably have those in your input ($_POST/$_GET). And as FuzzyTree has mentioned above, you'll want some type of ID validation and some kind of escaping of data going into the query to avoid SQL injection.
Use this instead
$tags_array = ['shoes','gadgets','fashion','food'];
$tags = implode("','", $tags_array);
$tags = "'".$tags."'";
$sql = "SELECT tag_id FROM tbltag WHERE tag_name IN ({$tags})";
Question: Do you need the & in your foreach loop? You are not directly modifying the tags_array just using the information?
Trying adding the number to the array e.g add $x so you are adding in 1 record into 1 part of the array as you loop though.
$tags_array = ['shoes','gadgets','fashion','food'];
$tags_array_id = [];
$tags_sql = '';
$x = 0;
foreach ($tags_array as &$tag) {
$sql = "SELECT tag_id FROM `tbltag` WHERE tag_name = ".$tag." group by tag_name";
$query = mysqli_query($conn, $sql);
$result = mysqli_fetch_row($query);
$tags_array_id[$x] = $result[0];
$x++;
};

mysql queries which is the best

i want to know which way is better (faster) from those sql methods;
1st method:
public static function getlistusers($limit=88888888888888 ) {
$sql = "SELECT id,name FROM users order by id desc limit 0,$limit";
$st = mysql_query( $sql ) or die(mysql_error());
$list = array();
while ( $row = mysql_fetch_assoc($st) ) {
$picss = new users( $row );
$list[] = $picss;
}
return ( array ( "users" => $list) );
#mysql_free_result($st);
for print output i use
foreach() the array $users ;
2nd method
$sql = "SELECT id,name FROM users order by id desc limit 0,$limit";
$st = mysql_query( $sql ) or die(mysql_error());
while ( $row = mysql_fetch_assoc($st) ) {
extract($row);
return "Id: $id and The Name is : $name";
}
#mysql_free_result($st);
}
===========
i want to know which is faster and safty for sql load.
Regards
Al3in
$sql = "SELECT id,name FROM users order by id desc limit 0,$limit";
$st = mysql_query( $sql ) or die(mysql_error());
while ( $row = mysql_fetch_assoc($st) ) {
extract($row);
return "Id: $id and The Name is : $name";
}
#mysql_free_result($st);
I doubt this approach will even work. Because, even though you limit it to 1 or a million, the loop will only run once because of return "Id: $id and The Name is : $name"; . So if you're comparing this and the other method, the other method would obviously work better.
Unless you're assigning to an array instead of returning. In which case the second method has an unnecessary function call extract which puts two variables into the heap.
Both are essentially the same. They execute the same query and retreive the results in the same way. The advantage of the first method is that it returns a list of data arrays that each represent a records in the database. All individual can be used any way you want. The second approach returns only a single string. The entire while loop is useless there.
So the second may be faster, because it only retrieves a single row, but from here that looks more like an error than like an actual implementation decision.

Created a new variable by pulling a value from a MySQL table

I am using a page where a variable $submissionid is being posted to it. I would like to use this variable and pull the field subcheck from a MySQL table called submission. I would like the value of the field subcheck to simply be a new variable $subcheck. I'm not sure how to do this. I have a query below, but how to I convert the result of the query below into a variable called $subcheck? (For any given submissionid, there will only be one $subcheck.)
Thanks in advance,
John
$querysub = mysql_query("SELECT subcheck FROM submission WHERE submissionid = '$submissionid' ");
mysql_query($querysub) or die(mysql_error());
You can try:
$querysub = mysql_query("SELECT subcheck FROM submission WHERE submissionid = ".
mysql_real_escape_string($submissionid));
$result = mysql_query($querysub);
if (!$result) {
die 'Could not run query: ' . mysql_error();
}
$subcheck = mysql_result($result, 0);
This is more of a 'php' question, than it is for mysql.
Look up the 'extract' keyword for PHP Link. Effectively 'extract' takes the contents of an associative array and creates php variables (symbol table entries) using the names of keys. Each php variable will then contain the associated value.
You should be able to just:
$result = mysql_query("SELECT * FROM table");
$row = mysql_fetch_array( $result, MYSQL_ASSOC );
extract( $row ); // Create php variables, named after each column in the table.
$row["field"] == $field; // Will be a true statement after 'extract()'
Enjoy, you now have the ability to have your code dynamic adjust to a DB schema that could be changed.
-- J Jorgenson --
This should work:
$querysub = mysql_query("SELECT subcheck FROM submission WHERE submissionid = '" . $submissionid ."' ");
$result = mysql_query($querysub) or die(mysql_error());
$row = mysql_fetch_assoc( $result );
if ($row ) {
$subcheck = $row['subcheck'];
} else {
echo "Subcheck not found";
}
Be careful with the escape characters around $submissionid in your query string. In your sample, they are probably letting the name of the variable go into the string you send to the mysql server.

Categories