Show query result in PHP - php

I have a query:
$string = "SELECT COUNT(id) as sponsered FROM `$database`.`$mem` where parent_id = 2 group by plan";
Which result in:
sponsored plan
2 gold
1 silver
1 mitra
This result is shown when I run this query in MySQL.
Now I want this result in PHP in an array data[] where
data[0] contains 2
data[1] contains 1
data[2] contains 1
I have tried this
$string = "SELECT COUNT(id) as sponsered FROM $database.$mem where parent_id = 2 group by plan";
$res = mysqli_query($con, $string);
while($data = mysqli_fetch_assoc($res)) {
echo $data['sponsered'];
}
But it results in data['sponsered'] containing 211
It would be better if this can be done without using any loop.

Inside the while loop assign the values to array.
$string = "SELECT COUNT(id) as sponsered FROM $database.$mem where parent_id = 2 group by plan";
$res = mysqli_query($con, $string);
$data = array();
while($result = mysqli_fetch_assoc($res)) {
$data[] = $result['sponsered'];
}
print_r($data);
Output:
data[0] contains 2
data[1] contains 1
data[2] contains 1

Your display is correct you just need a separator so the data isn't all clumped. In a browser:
echo $data['sponsered'] . "<br>";
in your loop should do it, or command line,
echo $data['sponsered'] . PHP_EOL;
should do it.
As is it throws 2, then 1, then 1 which views as 211.

Try this:
Please refrain from passing data directly into query in a prepare statement, use ? or : as deemed necessary.
Below is a sample code:
<?php
$table_name = $table; //not recommended to pass table_name as variable, unless necessary.
$parent_id = 2;
$p = $plan;
$string = "SELECT COUNT(id) as sponsered FROM $table_name where parent_id = ? group by ?";
if ($stmt = $db->prepare($string))
{
$stmt->bind_param('is', $parent_id, $p);
$stmt->execute();
$stmt->bind_result($sponsored, $plan);
$stnt->store_result();
$html ='';
while ($stmt->fetch() !== FALSE)
{
// Do what you like with the variables here, i.e. $sponsored, $plan
$html .= "<table>
<th> Sponsored </th>
<th> Plan</th>
<tr>
<td>$sponsored</td>
<td>$plan</td>
</tr>
</table>";
}
else {
die("Query failed");
}
var_dump($html);
}
?>
NOTE: If your result from your question is just an HTML (table/column), you don't need to do bind, you can just output the HTML formatted.

Use mysqli_fetch_array($result, MYSQLI_NUM) to retreive the data as numeric array

Related

Pass id's to url on a count being diplayed in table

I have a function in which I am returning a count which when displayed is clickable. When clicked on this count the page redirects to listing of the of users with their details. The count displayed has link to the information page with id's of the users passed in URL. I am not getting the result as the link shows only one user id instead of two(as per database) or some irrelevant id's. Where I am missing the thing, any help will be highly appreciated.
function for displaying count,
function clearedmodule()
{
$id= '';
$res = mysql_query("SELECT id from tbl_users WHERE status= 1 AND type = 3 ");
while($row = mysql_fetch_array($res))
{
$query = mysql_query("SELECT DISTINCT user_id FROM tbl_user_quiz GROUP BY user_id HAVING COUNT(DISTINCT module_id) = '".$this->userQuestionModules()."' AND SUM(cleared) = 0 ");
while($row1 = mysql_fetch_assoc($query))
{
foreach($row1 as $cname => $id)
{
$id .= $row['id'].',';
}
}
}
return substr($id, 0, -1);
}
Now the <td> where the count is being displayed,
<td>Not Cleared</td>
<td>
<?php
$ids = $rep->clearedmodule();
$ids = explode(",",$ids) ;
$linkId = $rep->clearedmodule();
if($linkId)
{ ?>
<?php echo count($ids); ?>
<?php
}
else{
echo "0";
}
?> </a></td>
Using above, the URL I am getting is
reportNotCleared.php?Userid=10131183 where 1013 is right id , 1183 is not at all correct and I want them to be comma separated.
Your second query is the only query you needed. Just remove all the loops except the middle one and you should be good to go!
function clearedmodule() {
$query = mysql_query("SELECT DISTINCT user_id FROM tbl_user_quiz GROUP BY user_id HAVING COUNT(DISTINCT module_id) = '".$this->userQuestionModules()."' AND SUM(cleared) = 0 ");
while($row1 = mysql_fetch_assoc($query)){
$id .= $row1['user_id'] . ',';
}
return substr($id, 0, -1);
}

Display count of values in PHP array

I can not seem to come over this easy problem.
I have the following code, where I select the column "status" from a table. There's three different values of "status", 0, 1 and 3.
I would like to count how many 0's there are, 1's and 2's, so that I can display them via <?php echo $accepted; ?> etc.
<?php
$sql = "SELECT status FROM applications";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
$array = array_count_values($row);
$pending = $array[0];
$accepted = $array[1];
$denied = $array[2];
?>
MYSQL_NUM changed to MYSQLI_NUM accordingly to comment, thank you.
A simple way is get these count using SQL
$sql = "SELECT `status`, COUNT(*) as cnt FROM applications GROUP BY `status`";
you have an array of so you should
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo "status = " . $array['status'] . ' = ' . $array['cnt'] .'<br />';
}

echo all and entire MySQL Query rows in php without specifically naming each column

I have
$result = "";
if(someCondition)
$result = mysql_query("SELECT * FROM table1 WHERE column = '$value' ");
else
$result = mysql_query("SELECT * FROM table2 WHERE column = '$value' ");
$result could have 0 -> infinity rows returned
Table 1 and Table 2 have different amounts of columns with different names
I want to write 1 generic loop after the above else that will just print out all of the rows. Preferably 1 per line or deliminated.
To clarify, one of the two query calls will fill the $results variable with rows.
I wont know which one fills it at run time so I want to just do a print all contents to screen. Is there a method that does this? is there a fast loop that iterates through all of the rows without explicitly saying the column names?
bored enough to answer:
$result = "";
if(someCondition){
$result = mysql_query("SELECT * FROM table1 WHERE column = '$value' ");
}else{
$result = mysql_query("SELECT * FROM table2 WHERE column = '$value' ");
}
while ($row = mysql_fetch_array($result)) ) {
foreach($row as $key => $var)
{
echo $key . ' = ' . $var . '<br />';
}
}

MySQL contains variable

I have an array in PHP that is looping through a set of names (and a corresponding quantity). I would like to print the ones found in a MYSQL database table (to which I've succesfully connected). I'm currently using the code:
foreach ($arr as $name => $quan) {
$query = "SELECT * FROM table WHERE name='$name'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
echo $quan." ".$row['name']. "\n";
}
}
For some reason, this only prints the last quantity and name in the array. Help?
For example, if the array has key-value pairs of {A-4, B-2, C-3}, and table contains {A, B, D} as names ... it'll only print "2 B".
Change the code to the following:
foreach ($arr as $name => $quan) {
$query = "SELECT * FROM table WHERE name='$name'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_array($result)) {
echo $quan." ".$row['name']. "\n";
}
}
}
You have to loop through the result. By the way, stop using mysql_query()! use MySQLi or PDO instead ( and be careful of SQL Injection ; you can use mysqli_real_escape_string() to handle input parameters ). For MySQLi implementation , here it is :
foreach ($arr as $name => $quan) {
$query = "SELECT * FROM table WHERE name='$name'";
$result = mysqli_query($query) or die(mysqli_error());
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
echo $quan." ".$row['name']. PHP_EOL;
}
}
}
And rather "\n", I prefer using PHP_EOL ( as shown above )
And as the comment suggests, the SQL statement can be executed once, as follow:
$flipped_array = array_flip($arr); // flip the array to make "name" as values"
for($i = 0; $i < count($flipped_array); $i++) {
$flipped_array[$i] = '\'' . $flipped_array[$i] . '\''; // add surrounding single quotes
}
$name_list = implode(',', $arr);
$query = "SELECT * FROM table WHERE name IN ($name_list)";
// ... omit the followings
e.g. in $arr contains "peter", "mary", "ken", the Query will be:
SELECT * FROM table WHERE name IN ('peter','mary','ken')
sidenote: but I don't understand your query. You only obtain the name back from the query? You can check number of rows, or you can even group by name, such as:
SELECT name, COUNT(*) AS cnt FROM table GROUP BY name ORDER BY name
to get what you want.
UPDATE (again): based on the comment of OP, here is the solution :
$flipped_array = array_flip($arr); // flip the array to make "name" as values"
for($i = 0; $i < count($flipped_array); $i++) {
$flipped_array[$i] = '\'' . $flipped_array[$i] . '\''; // add surrounding single quotes
}
$name_list = implode(',', $arr);
$query = "SELECT name, COUNT(*) AS cnt FROM table WHERE name IN ($name_list) GROUP BY name HAVING COUNT(*) > 0 ORDER BY name";
$result = mysqli_query($query) or die(mysqli_error());
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
echo $quan." ".$row['name']. ": " . $row['cnt'] . PHP_EOL;
}
}
The above query will show the name appearing in the table only. Names not in table will not be shown. Now full codes ( be cautious of SQL Injection , again )

how can i controll while loop into another while loop

Suppose I have a while loop like:
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
}
then if first query return 5 results i.e 1-5 and second query returns 3 results than if i want to echo out second query it gives me like this..........
111112222233333
than how can i fix to 123 so that the second while loop should execute according to number of times allowed by me........!! how can i do that.........!!
I'm not sure I 100% understand your question - it's a little unclear.
It's possible you could solve this in the query with a GROUP BY clause
$sql_2 = mysql_query("SELECT id FROM secondtable WHERE id != $id GROUP BY id");
But that would only work if you need just secondtable.id and not any of the other columns.
When you say "number of time allowed by me" do you mean some sort of arbitrary value? If so, then you need to use a different loop mechanism, such as Greg B's solution.
Do you want to explicitly limit the number of iterations of the inner loop?
Have you considered using a for loop?
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
for($i=0; $i<3; $i++){
$ro = mysql_fetch_array($sql_2);
$id2 = $ro["id2"];
echo $id2;
}
}
Your first while loop is iterating over all 5 results, one at a time.
Your second while loop is iterating over each of the 5 results, producing it's own set of results (i.e. 3 results for each of the 5 iterations, totaling 15 results).
I believe what you are trying to do is exclude all IDs found in your first loop from your second query. You could do that as follows:
$sql = mysql_query("SELECT * FROM tablename");
$exclude = array();
while($row = mysql_fetch_array($sql)) {
array_push($exclude, $row['id']);
}
// simplify query if no results found
$where = '';
if (!empty($exclude)) {
$where = sprintf(' WHERE id NOT IN (%s)', implode(',', $exclude));
}
$sql = sprintf('SELECT * FROM secondtable%s', $where);
while($row = mysql_fetch_array($sql_2)) {
$id2 = $row["id2"];
echo $id2;
}
$sql = mysql_query("SELECT * FROM tablename");
$tmp = array();
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
if(!in_array($id, $tmp)) {
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
$tmp[] = $id;
}
}
Saving all queried $id's in an array to check on the next iteration if it has already been queried. I also think that GROUPing the first query result would be a better way.
I agree with Leonardo Herrera that it's really not clear what you're trying to ask here. It would help if you could rewrite your question. It sounds a bit like you're trying to query one table and not include id's found in another table. You might try something like:
SELECT * FROM secondtable t2
WHERE NOT EXISTS (SELECT 1 FROM tablename t1 WHERE t1.id = t2.id);

Categories