How to combine multiple query's into one? - php

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.

Related

creating outer array php

UPDATE: a solution has been found stated below: however new issue poses i didnt want to keep creating question so updated this one when i use ajax to pass through to html i get the following error response.forEach is not a function
where the code is as below is this because there are now 2 arrays?
$.get('php/test.php', function(response) {
console.log(response);
var row;
response.forEach(function(item, index) {
console.log(item);
$(`td.${item.beacon}`).css('background-color', item.location).toggleClass('coloured');
});
});
Im Pretty naff when it comes to this type of thing but i need to try get these 2 queries added to 1 ajax I have been told i should add both queries to an outer array but im not sure how to do this and the example i got was $array = $other_array
but im not sure how to write it any help would be greatly appreaciated
$sql = "SELECT beacon,TIME_FORMAT(TIMEDIFF(max(`time`),min(`time`)), '%i.%s')
AS `delivery_avg`
FROM `test`.`test`
where date = CURDATE()
and time > now() - INTERVAL 30 MINUTE
group by beacon ";
$result = $conn->query($sql);
$sql2 = 'SELECT
*
FROM
(SELECT
beacon,location,date,
COUNT(location) AS counter
FROM `test`.`test`
WHERE `date` = CURDATE() and `time` > NOW() - interval 40 second
GROUP BY beacon) AS SubQueryTable
ORDER BY SubQueryTable.counter DESC;';
$result = $conn->query($sql2);
$result = mysqli_query($conn , $sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
$result2 = mysqli_query($conn , $sql2);
$rows2 = array();
while($r = mysqli_fetch_assoc($result2)) {
$rows2[] = $r;
}
echo json_encode($rows2);
You already got most of it right. To get the data in one go, you can combine the arrays (see the line staring with $result) and then send it JSON formatted.
$sql1 = "SELECT ...";
// Query the database
$result1 = $conn->query($sql);
// Fetch the result
$rows1 = $result1->fetch_all(MYSQLI_ASSOC);
// Same for second query
$sql2 = 'SELECT ...';
$result2 = $conn->query($sql2);
$rows2 = $result2->fetch_all(MYSQLI_ASSOC);
$result = array(
'query1' => $rows1,
'query2' => $rows2
);
header("Content-Type: application/json");
echo json_encode($result);
Some more hints:
You only need to run the query once (you have ->query() and mysqli_query() in your code).
You don't need the loop to get all result rows. The function mysqli_fetch_all() does that for you.
When you have your 2 arrays with db results, you can do something like this :
$return = array (
$result,
$result2
);
echo json_encode($return);
$sendResponse = array (
'sql1' => $sqlResult1,
'sql2' => $sqlResult2
);
echo json_encode($sendResponse);
This would be a more suitable and convenient (from JavaScript size) way
$response = [];
$response['result_first_query'] = $rows;
$response['result_second_query'] = $rows2;
echo json_encode($response);

PHP: use an array in a select where condition [duplicate]

This question already has answers here:
Passing an array to a query using a WHERE clause
(17 answers)
Closed 11 months ago.
I'm trying to query a MySQL database using an array but I'm having trouble!
I have a table called clients, I want to be able to select 'name' from all rows whose 'sector' column is equal to $sectorlink.
I then want to put all the names into an array so I can perform my next query: select all rows from another table whose 'client' column is equal to one of the names returned from the first query. I'm doing something wrong because it returns a fatal SQL error. I'm getting confused with all the variables!
$sectorlink and $connection are the only variables that are defined outside of this code
Any suggestions?
$query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'";
$clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR);
while($row = mysql_fetch_array($clientresult)){
foreach($row AS $key => $value){$temp[] = '"'.$value.'"';}
$thelist = implode(",",$temp);
$query = "SELECT count(*) FROM studies WHERE client IN ($row) ORDER BY (date) desc";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
}
The second query should use $thelist not $row, and it should be outside of the while loop. The foreach loop is unnecessary when processing a single row. You can access the name in $row with a simple $row[0]. Something like this (untested):
$query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'";
$clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR);
while($row = mysql_fetch_array($clientresult)){
$temp[] = '"'.$row[0].'"';
}
$thelist = implode(",",$temp);
$query = "SELECT count(*) FROM studies WHERE client IN ($thelist) ORDER BY (date) desc";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
Caution: Please be aware that your code is highly vulnerable to SQL injection attacks. It's fine for testing or internal development but if this code is going to be running the Fort Knox web site you're going to want to fix it up quite a bit. Just an FYI. :-)
Try This:
$query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'";
$clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR);
while($row = mysql_fetch_array($clientresult)){
$client = $row['name'];
$query = "SELECT * FROM studies WHERE client='$client' ORDER BY date DESC";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
/* echo results here */
}
Couple of things. First you have an unnecessary loop there. Try:
while (list($name) = mysql_fetch_row($clientresult)) {
$temp[] = $name;
}
To build your temporary array.
Second, the parts of the IN clause are strings, so when you implode, you'll need to enclose each value in quotes:
$thelist = "'". implode("','", $temp) . "'";
Lastly, in your query you are passing $row to the IN clause, you should be passing $thelist:
$query = "SELECT count(*) FROM studies WHERE client IN ($thelist) ORDER BY date desc";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
So altogether:
$query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'";
$clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR);
while (list($name) = mysql_fetch_row($clientresult)) {
$temp[] = $name;
}
$thelist = "'". implode("','", $temp) . "'";
$query = "SELECT count(*) FROM studies WHERE client IN ($thelist) ORDER BY date desc";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
I expect you'd be better off doing this in one query with a join:
$query = "SELECT COUNT(*) FROM `studies` INNER JOIN `clients` on studies.client = clients.name WHERE clients.sector = '$sectorlink' ORDER BY studies.date DESC";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);

get required result in sql

i have a sql database having two columns
1. id and 2. parent_id
i want to select all ids where parent_id=1 [let the results saved in X array] then,
select all the ids where parent_id in X[] [let the results saved in Y array] then... do the same upto 7 levels at last i want to sum all levels and get that sum in a variable name "number"
what i tried:
$sql = "SELECT count(id) as leadersearch FROM `$database`.`$mem` where parent_id = ".$parent[id];
$result = mysqli_query($con, $sql);
$lv1 = mysqli_fetch_array($result);
then again
$sql = "SELECT count(id) as leadersearch FROM `$database`.`$mem` where parent_id in ($lv1)";
$result = mysqli_query($con, $sql);
$lv2 = mysqli_fetch_array($result);
and so on.... it may give me required result but it is too much code...
i want to the same by using a loop or something else... to shorten the code.
Your first query gets count(id) and then second query uses it to get results. It seems you have many flaws in your requirement to begin with.
However, for your question you can use sub-query like following
$sql = "SELECT count(id) as leadersearch
FROM `$database`.`$mem`
WHERE parent_id in (
SELECT id FROM `$database`.`$mem` where parent_id = ".$parent['id']."
)";
$result = mysqli_query($con, $sql);
$lv2 = mysqli_fetch_array($result);
If you have many level nesting and you want to search records like this then you can consider functions:
function getLeader($parent_id){
$results = [];
$sql = "SELECT id as leadersearch FROM `$database`.`$mem` where parent_id in (".$parent_id.")";
$result = mysqli_query($con, $sql);
foreach($row = mysqli_fetch_array($result)){
$results[] = $row['id'];
}
return $results;
}
$leaders = [];
$ids = getLeader($parent['id']);
foreach($ids as $id){
$leaders[$id] = getLeader($id);
}

mysql query array counter

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

SELECT Count php/sql

I am trying to store a mysql value into a php variable. I have the following query which I know works. However, I the value for $count is always 0. Can someone explain what I need to do to get the count value? The count should be the count of x's w here name_x=.$id.
$query = "SELECT COUNT(name_x) FROM Status where name_x=.$id.";
$result = mysql_query($query);
$count = $result;
Is first letter in table name is really capital. Please check it first.
or Try :
$query = "SELECT COUNT(*) as totalno FROM Status where name_x=".$id;
$result = mysql_query($query);
while($data=mysql_fetch_array($result)){
$count = $data['totalno'];
}
echo $count;
$query = "SELECT COUNT(*) FROM `Status` where `name_x`= $id";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
$count = $row[0];
please try it
$query = "SELECT COUNT(*) FROM Status where name_x=$id";
$result = mysql_query($query);
$count = mysql_result($result, 0);
You are missing single quotes around $id. Should be
name_x = '" . $id . "'";

Categories