mysql query array counter - php

Apologies if I have the terminology wrong.
I have a for loop in php which operates a mysql query...
for ($i = 0; $i <count($user_id_pc); $i++)
{
$query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '$user_id_pc[$i]'";
$job_data = mysqli_query($dbc, $query2);
$job_results = array();
while ($row = mysqli_fetch_array($job_data))
{
array_push($job_results, $row);
}
}
The results that are given when I insert a...
print_r ($job_results);
On screen -> Array()
If I change the query from $user_id_pc[$i] to $user_id_pc[14] for example I receive one set of results.
If I include this code after the query and inside the for loop
echo $i;
echo $user_id_pc[$i] . "<br>";
I receive the number the counter $i is on followed by the data inside the array for that counter position.
I am not sure why the array $job_results is empty from the query using the counter $i but not if I enter the number manually?
Is it a special character I need to escape?
The full code
<?php
print_r ($user_id_pc);
//Select all columns to see if user has a profile
$query = "SELECT * FROM user_profile WHERE user_id = '" . $_SESSION['user_id'] . "'";
//If the user has an empty profile direct them to the home page
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) == 0)
{
echo '<br><div class="alert alert-warning" role="alert"><h3>Your appear not to be logged on please visit the home page to log on or register. <em>Thank you.</em></h3></div>';
}
//Select data from user and asign them to variables
else
{
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) == 1)
{
$row = mysqli_fetch_array($data);
$cw_job_name = $row['job_description'];
$cw_rate = $row['hourly_rate'];
$job_mileage = $row['mileage'];
$job_postcode = $row['postcode'];
$response_id = $row['user_profile_id'];
}
}
for ($i = 0; $i <count($user_id_pc); $i++)
{
$query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '{$user_id_pc[$i]}'";
$job_data = mysqli_query($dbc, $query2);
$job_results = array();
while ($row = mysqli_fetch_array($job_data))
{
array_push($job_results, $row);
}
echo $i;
?>
<br>
<?php
}
print ($query2);
print $user_id_pc[$i];
?>

This is primarily a syntax error, the correct syntax should be:
$query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '{$user_id_pc[$i]}'";
Note that this is correct syntax but still wrong!! For two reasons the first is that it's almost always better (faster, more efficient, takes less resources) to do a join or a subquery or a simple IN(array) type query rather than to loop and query multiple times.
The second issue is that passing parameters in this manner leave your vulnerable to sql injection. You should use prepared statements.
The correct way
if(count($user_id_pc)) {
$stmt = mysqli_stmt_prepare(" SELECT job_title, job_info FROM job_description WHERE postcode_ss = ?");
mysqli_stmt_bind_param($stmt, "s", "'" . implode("','",$user_id_pc) . "'");
mysqli_stmt_execute($stmt);
}
Note that the for loop has been replaced by a simple if

You have to check the query variable, instead of:
$query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '$user_id_pc[$i]'"
have you tried this:
$query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '" . $user_id_pc[$i] . "' ";
And another thing, try something different like this:
while ($row = mysqli_fetch_array($job_data))
{
$job_results[] = array("job_title" => $row["job_title"], "job_info" => $row["job_info");
}
Then try to print the values.

Sorry but I like foreach(), so your working code is:
<?php
// To store the result
$job_results = [];
foreach($user_id_pc as $id ){
// selecting matching rows
$query2 ="SELECT job_title, job_info FROM job_description WHERE postcode_ss = '".$id."'";
$job_data = mysqli_query($dbc, $query2);
// checking if query fetch any result
if(mysqli_num_rows($job_data)){
// fetching the result
while ($row = mysqli_fetch_array($job_data)){
// storing resulting row
$job_results[] = $row;
}
}
}
// to print the result
var_dump($job_results);

Related

How to combine multiple query's into one?

I am running a line graph on RGraph framework, and I am using a SELECT COUNT statement for rejected, accepted, approved etc.....counting how many items was rejected or accepted etc and then dumping the query data into an array, However I am looking for an easier way to implement this query, instead of running a query on each unique row value, also thinking in the way if I have to encounter other column data besides rejected, accepted or etc....I wouldnt, my code doesnt seem very scalable then. Please help
So far, I am running a query for each keyword, hope my code explains this.
The final variable is what i am feeding to RGRAPH, This works fine as it is, however it isn't the right way, and not very scalable, should my row data change.
<?php
$cxn = mysqli_connect("localhost","root","", "csvimport");
$query = "SELECT COUNT(*) FROM table_1 WHERE conclusion = 'rejected'";
$result = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$display = mysqli_fetch_array($result);
$rejected = $display[0];
//echo $rejected;
$query = "SELECT COUNT(*) FROM table_1 WHERE conclusion =
'accepted'";
$result = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$display = mysqli_fetch_array($result);
$accepted = $display[0];
//echo $accepted;
$query = "SELECT COUNT(*) FROM table_1 WHERE conclusion = '-'";
$result = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$display = mysqli_fetch_array($result);
$dash = $display[0];
//echo $dash;
$query = "SELECT COUNT(*) FROM table_1 WHERE conclusion =
'approved'";
$result = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$display = mysqli_fetch_array($result);
$approved = $display[0];
//echo $approved;
$datarray = [$rejected, $accepted, $dash, $approved];
print_r($datarray);
$data_string = "[" . join(", ", $datarray) . "]";
echo "<br>";
print_r($data_string);
?>
You can just use GROUP BY and add the conclusion column to the result set, so
SELECT conclusion, COUNT(*) as total
FROM table_1
WHERE conclusion in ('rejected', 'accepted', '-', 'approved')
GROUP BY conclusion
Then retrieve each row of the result set
$totals = [];
while($row = mysqli_fetch_array($result)) {
$totals [$row[0]] = [$row[1]];
}
and $totals will be an array something like
array( 'accepted' => 12,
'approved' => 20...)
If you want all of the conclusions, then just remove the WHERE conclusion in line and it will return all of the possibilities along with the count.

Display group by table from mysql in php

I have a query in mysql which will return a table grouped by some fields. How can I echo these results?
Here is piece of my code.
$stmt = $con->prepare("
SELECT classSubject
, COUNT(*) cnt
from Class
where grade=?
and department=?
and classGroup IN(?,3)
GROUP
BY classSubject;
");
$stmt->bind_param("isi", $grade, $department, $classGroup);
//executing the query
$stmt->execute();
What should I do after this so that I can echo all the result?
I recommend reviewing a good site which can serve as an example of what syntax to use, such as this one.
$sql = "SELECT classSubject, COUNT(*) cnt FROM Class ";
$sql .= "WHERE grade = ? AND department = ? AND (classGroup = ? OR classGroup = 3) ";
$sql .= "GROUP BY classSubject";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("isi", $grade, $department, $classGroup);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "(classSubject, count) = (" . $row['classSubject'] . ", " . $row['cnt'] . ")";
}
}
Note that I add an alias to the COUNT(*) term in the select so that we can easily refer to it by name in PHP. You could also just refer to columns using their numeric indices, but going by name is an easier and safer way to do it.
After reading Tim Biegeleisen's answer and doing a bit of surfing, I came up with this solution. After executing the query:
$response = array();
$response['success']=true;
$stmt->bind_result($classSubject,$cnt);
while ($stmt->fetch())
{
$response[$classSubject]=$cnt;
}
echo json_encode($response);
Hope this helps someone.

Dynamic SQL statement based on foreach

How would I get this to work, because I am just getting errors right now.
$_GET['providers'] is an array of DB column names, which I am checking if = 1 in the below query.
foreach ($_GET['providers'] as $providers) {
$statement = "AND ".$providers."= '1' ";
}
$sql = "select * from users where user_id ='1' ".$statement." ";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if(isset($row['user_id'])){
echo "It worked";
}
You should use a whitelist to check if the $providers are known column names. You then should concatenate the $statement, otherwise you overwrite that variable on every iteration.
$statement = '';
$columns = array('known', 'columns', 'go', 'here');
foreach ($_GET['providers'] as $providers) {
if(in_array($providers, $columns)) {
$statement .= " AND $providers = 1 ";
}
}
$sql = "select user_id from users where user_id =1 $statement limit 1";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if(isset($row['user_id'])){
echo "It worked";
}
You also shouldn't use * unless you really want every column. If you just want to see if a row is returned you also can use limit 1 because you don't care about other rows.
You are overwriting $statement every time the loop is running.
$statement = "";
foreach ($_GET['providers'] as $providers) {
$statement .= "AND ".$providers."= '1' "; // note the ".=" to append
}
$sql = "select * from users where user_id ='1' ".$statement." ";
// to debug: echo "Query :: $sql";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if(isset($row['user_id'])){
echo "It worked";
}

PHP Mysqli trigger a query one after other

I am trying to fetch first id from one table and later after all the ids are fetched i am trying to fetch number of all that id's.
My Problem is
As i want to select the value of first query completion result
I am unable to trigger second query after the first query is completed both are triggerid at a time
First Query
$query ="SELECT * FROM abc WHERE xyz='xyz' And Standard='xyz' ";
$data=mysqli_query($mysqli,$query)or die(mysqli_error());
$ID = array();
while($row=mysqli_fetch_array($data)){
$ID[] = $row['ID'];
}
$IDall = "'" . implode("','", $ID) . "'";
Second Query
$query="SELECT mobno FROM euser WHERE UserId IN ($IDall)" ;
$data=mysqli_query($mysqli,$query)or die(mysqli_error());
$mobiles = array();
while($row=mysqli_fetch_array($data)){
$mobiles[] = $row['MobileNum'];
}
$mobilesStr = implode(',', $mobiles);
echo $mobilesStr;
}
Try this
SELECT mobno FROM euser WHERE UserId IN (SELECT ID FROM abc WHERE xyz='xyz' And Standard='xyz');
You don't need 2 queries. Only 1 is enough
SELECT mobno FROM euser WHERE UserId IN (
SELECT ID FROM abc ...
)
Try this
$query ="SELECT * FROM abc WHERE xyz='xyz' And Standard='xyz' ";
$data=mysqli_query($mysqli,$query)or die(mysqli_error());
if(mysqli_num_rows($data) > 0) {
$ID = array();
while($row=mysqli_fetch_array($data)){
$ID[] = $row['ID'];
}
$IDall = "'" . implode("','", $ID) . "'";
$query2="SELECT mobno FROM euser WHERE UserId IN ($IDall)" ;
$data2=mysqli_query($mysqli,$query2)or die(mysqli_error());
$mobiles = array();
while($row=mysqli_fetch_array($data2)){
$mobiles[] = $row['MobileNum'];
}
$mobilesStr = implode(',', $mobiles);
echo $mobilesStr;
}
In this the second query will execute when the first query has a result.

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 )

Categories