How do I update mysql database WHERE value = value from PHP array? - php

I am trying to use the keys of an array as values to update a column in my database. The column in question is the sort order for the rows.
Lets say the sort column values for each row are 1, 3, 5, 8, 9, 10, 12.
When the code is executed this is to be updated to read 1, 2, 3, 4, 5, 6, 7.
My code below does what I am trying to achieve when I echo the values however I am having a problem with the update query.
$sql = "SELECT asset, sort FROM portfolio ORDER BY sort ASC";
$query = mysqli_query($conn, $sql);
$i = 0;
while ($row = mysqli_fetch_assoc($query)){
$asset[$i] = $row['asset'];
$sort[$i] = $row['sort'];
$new_sort = $i+1;
$assets = implode(',', $asset);
$update_sql = "UPDATE portfolio SET sort='$new_sort' WHERE asset IN ('$assets')";
mysqli_query($conn, $update_sql);
$i++;
}
Using the following only the first row is being updated:
$assets = implode(',', $asset);
Using the following all rows are being updated, however they are all being set to the last value, in this example it would be 7.
$assets = join("','",$asset);
UPDATE: $assets is a string, an example would be google,yahoo,apple etc..
Any ideas where I am going wrong?
Many Thanks.

You are setting the new_sort for every asset every time you loop through.
First loop:
$assets[0] => "asset1"
$new_sort => 2
Update new_sort = 2 where asset in $assets. (So only asset1 will be updated.)
Second loop:
$assets[0] => "asset1"
[1] => "asset2"
$new_sort => 3
Update new_sort = 3 where asset in $assets (So asset1 and asset 2 will be updated)
This will result into always setting the new_sort for every asset to the latest new_sort value;
The code for your output could be:
while ($row = mysqli_fetch_assoc($query)){
$new_sort = $i+1;
$update_sql = "UPDATE portfolio SET sort='" . $new_sort . "' WHERE asset='" . $row['asset'] . "';";
mysqli_query($conn, $update_sql);
$i++;
}

This the solution for your desired output.
$sql = "SELECT asset, sort FROM portfolio ORDER BY sort ASC";
$query = mysqli_query($conn, $sql);
$i = 0;
while ($row = mysqli_fetch_assoc($query)){
$asset[$i] = $row['asset'];
$sort[$i] = $row['sort'];
$new_sort = $i+1;
$assets = implode(',', $asset);
$update_sql = "UPDATE portfolio SET sort='$new_sort' WHERE asset like '".$row['asset']."'";
mysqli_query($conn, $update_sql);
$i++;
}

First of all you need to move your UPDATE query outside the while loop than you can use like that:
$assets = implode("','", $asset); // split $asset in comma and single quote.
$update_sql = "UPDATE portfolio SET sort='$new_sort' WHERE asset IN ('$assets')";
You are already store your values in an array $asset[$i] = $row['asset']; so no need to use query inside the while loop.
In your code, you are update the last value of $i in sort column.
The other solution is very simple, update single record as:
<?php
$sql = "SELECT asset, sort FROM portfolio ORDER BY sort ASC";
$query = mysqli_query($conn, $sql);
$i = 0;
while ($row = mysqli_fetch_assoc($query)){
$new_sort = $i+1;
$assets = $row['asset'];
$update_sql = "UPDATE portfolio SET sort = '$new_sort' WHERE asset = '$assets'";
mysqli_query($conn, $update_sql);
$i++;
}
?>

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.

How to calculate the sum of number array elements from multiple database rows using php?

I need to count the number of elements that exist in the column of a MySQL database row for multiple rows and them add them all together. This is the code I used to count the number of array elements (which are numbers separated by commas):
$result = substr_count($count_fetch['micro_analysis'], ",") + 1;
But now I need to do this for each row, which could vary depending on the query. I need to add the $result of each row together to get a final sum of all the rows. I used the following code but I get the incorrect value, can someone please point me in the right direction?
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$count_query = mysqli_query($conn, $sql);
$count_fetch = mysqli_fetch_assoc($count_query);
foreach ($count_fetch as $row) {
$result = substr_count($count_fetch['micro_analysis'], ",") + 1;
$end_result += $result;
}
echo $end_result;
You are just fetching 1 row and then trying to count over that row, instead you need to loop over the rows and add the fields in that...
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$end_result = 0;
$count_query = mysqli_query($conn, $sql);
while( $row = mysqli_fetch_assoc($count_query)) {
$end_result += substr_count($row['micro_analysis'], ",") + 1;
}
echo $end_result;
Replace your code with the following:
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$count_query = mysqli_query($conn, $sql);
$count_fetch = mysqli_fetch_assoc($count_query);
$end_result=0;//initialize variable to 0
foreach ($count_fetch as $k => $row) {
if($k == 'micro_analysis'){
$result = substr_count($row, ",") + 1; //change over here
$end_result += $result;
}
}
echo $end_result;

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

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

Setting dynamic array key in while loop php

I have this code
$query = "SELECT `subscriberid`,`data` FROM `****table_name*****`"
. "WHERE `subscriberid` IN (123,456,789,101)";
$result = $cxn->query($query);
$Points = array();
while ($row = $result->fetch_assoc()) {
$Points[$row['subscriberid']] = $row['data'];
}
I want the keys for $Points to be the subscriberid, but when I print out $Points I keep getting default keys 0-3 and I can't see any reason for this to be happening.
Credits to #Jongosi's Comment, about the if ($result = $cxn->query($query)) part.
Your query is currently as follows:
$query = "SELECT `subscriberid`,`data` FROM `****table_name*****`"
. "WHERE `subscriberid` IN (123,456,789,101)";
If you only edited ****table_name*****, you are missing a space ( between * and WHERE).
Your result will be nothing or an error.
$query = "SELECT `subscriberid`,`data` FROM `****table_name*****`"
. " WHERE `subscriberid` IN (123,456,789,101)";

Categories