Reordering a sql matrix on php - php

This is more of a php question than a sql one.
I have a database like this:
A B C D E
1 1
1 1 1
1 1
I need to order it but not using ORDER BY becouse the parameter needed is not inside the table. I need a sum of several of this numbers "1".
If my requirements needs the fields A, B, C. So the result of the second row is 3, the first row is 2 and the third one is 1.
But if my requirements change for example to just include the field E, then the third row has "1" and the other just have 0.
So I need to sume theese values, something like this:
while($row = $result->fetch_assoc()) {
$ranking = $row['A'] + $row['B'] + $row['C'] + $row['D']
;}
I think I need to now insert this new $ranking value inside the $result matrix, and then, sort it using that column and brake it again... But that goes beyond my comprehension of php?
Any light on this please?
Edited 1:
Can I do something like this?
while($row = $result->fetch_assoc()) {
$result = array("$row['A']" => ($row['A'] + $row['B'] + $row['C'] + $row['D']))
;}

Consider a simple select query and have PHP dynamically build the sum string if selected columns regularly change. Use the calculated column for your other application needs.
SQL (sqlfiddle)
SELECT IFNULL(`A`, 0) + IFNULL(`B`, 0) + IFNULL(`C`,0) As ColsSum
FROM matrix;
PHP
$cols = array('A', 'B', 'C', 'D', 'E');
$selected = array('A', 'B', 'C');
$colsSQL = "";
$results = array_intersect($cols, $selected);
foreach ($results as $a) {
$colsSQL .= 'IFNULL(`'. $a .'`,0) + ';
}
$colsSQL = substr($colsSQL, 0, -2);
$strSQL = "SELECT ". $colsSQL ." As ColSums FROM matrix;";
...
mysqli_query($conn, $strSQL);

Related

Add Numbers Together From Mysql Database in PHP

I need to add some numbers together that are being pulled from a MySQL table to get a total value.
Currently the issue I have is the numbers being added to the end of a string instead.
e.g:
1,2,3,4 becomes 1234 instead of 10
Here is what I am using to get the numbers from the database:
$count = mysqli_query($connect, "SELECT QUANTITY FROM Table");
while($row = mysqli_fetch_assoc($count)) {
$total .= $row['Quantity'];
//I Have also tried
$total .= (int)$row['Quantity'];
}
echo $total;
The Quantity Column is set to be an INT in the table so I would have expected it to add together automatically. What am I doing wrong?
You should probably look at the difference between .= and +=
By adding a . in front of = you concatenate - You add the value ad the end of the variable.
If you would use a + in front of your = you would actually get the result you want.
$count = mysqli_query($connect, "SELECT QUANTITY FROM Table");
$total = 0;
while($row = mysqli_fetch_assoc($count)) {
$total += $row['Quantity'];
}
echo $total;
http://php.net/manual/en/language.operators.string.php

add value +1 in phrase number

I want to add value in phrase in database sql in database i save phrasr like this
DO-2500-01
DO-2500-02
now my question how can add +1 in last value like this DO-2500-03 / DO-2500-04
this my code
$getse = $DB_con->prepare("SELECT serial FROM `customer` WHERE user_add=:id ORDER BY serial DESC LIMIT 1");
$getse->execute(array(":id"=>$user_id));
$getse = $getse->fetch(PDO::FETCH_OBJ);
$addone = $getse->serial + 1;
echo $addone;
this is my code i get last serial and i want to add +1 for example last serial in database is DO-2500-04 I want to get this value and add +1 To become like this DO-2500-05
Split string, increase the last part and combine it back
$addone = explode('-', "DO-2500-04");
$addone[count($addone)-1] += 1;
// Append 0 if the last part less then 10
$addone[count($addone)-1] = str_pad($addone[count($addone)-1], 2, 0, STR_PAD_LEFT);
echo $addone = implode('-', $addone);
You can get this based on your requirement.
If DO-2500-99 should be DO-2501-00 then below code can work.
$serialArr= explode('-', $getse->serial);
$serialNo = (int)$serialArr [1].$serialArr [2];
$newSerialNo = $serialNo + 1;
$newSerialNo = substr($newSerialNo, 0, -2)."-".substr($newSerialNo , -2);
$newSerial = $serialArr[0].'-'.$newSerialNo;
If DO-2500-99 should be DO-2500-100 then below code can work.
$getse = 'DO-2500-99';
$serialArr= explode('-', $getse->serial);
$serialNo = (int)$serialArr [2];
$serialArr[2] = $serialNo + 1;
$newSerial = implode('-',$serialArr);
DO-2500-04 it's a String value and you cannot use arithmetic operators on it. If you just want last counter to get incremented, what you need to do is get the last value by splitting the string by -.
Then get the last value and increment it and then again join the array by -.
To split and join the array we can use explode() and implode().
This is how you can get the last value from string using explode()
$values=explode("-","DO-2500-04"); // $values is now array.
$lastvalue=(int)$values[2];
$lastvalue++;
if($lastvalue<9) {
$lastvalue = "0" . $lastvalue;
}
$values[2]=$lastvalue;
$incremented_string=implode("-",$values);
First parameter in explode denotes the chracter by you want to split the string same as first parameter in implode denotes the glue by you want to join the array.
http://php.net/manual/en/function.explode.php
http://php.net/manual/en/function.implode.php
Just for fun, you could do a lot of this in the SQL like:
$getse = $DB_con->prepare("SELECT serial,
LEFT(serial,8) AS serialBase,
SUBSTRING(serial,8) AS serialIdx
FROM `customer` WHERE user_add=:id
ORDER BY serial DESC LIMIT 1");
$getse->execute(array(":id"=>$user_id));
$getse = $getse->fetch(PDO::FETCH_OBJ);
$addone = $getse->serialBase + str_pad(($getse->serialIdx + 1),2,'0',STR_PAD_LEFT);
echo $addone;
Updated the SQL.

Get the ranking of the TOTAL values from PHP that is not stored in mysql

Good Day, I am working on some scoring system that would display all the scores by all of the users and would sum it up using PHP from MySQL. The result is working fine and the computation as well (the computation is done with php, not on MySQL). Now my problem is, how can I rank the total scores from highest to lowest.
Here's the code:
$sel_query="Select * from tbl_scores";
$result = mysql_query($sel_query);
while($row = mysql_fetch_array($result)) {
$crit_3 = $row["crit_3"];
$crit_3a = number_format($crit_3);
$crit2_3 = $row["crit2_3"];
$crit2_3a = number_format($crit2_3);
$crit3_3 = $row["crit3_3"];
$crit3_3a = number_format($crit3_3);
$user1 = ($crit_3) ;
$user2 = ($crit2_3);
$user3 = ($crit3_3);
$divide = ($user1 + $user2 + $user3);
$total = number_format($divide / 9 , 2, '.', '');
$average = number_format($total * 0.15 , 2, '.', '');
?>
Thanks in advance.
1.Please stop using (deprecated from php5.5 +removed from php7) mysql_*,use mysqli_* OR PDO.
2.Define an array variable outside of the loop, and inside in the loop assign total scores to that array.
3.Now you will get an array of scores and now you can use rshort() method to get data correctly.
So the code should be like below:-
$sel_query="Select * from tbl_scores";
$result = mysql_query($sel_query);
$scores_array = array();//create an array
while($row = mysql_fetch_array($result)) {
$crit_3 = $row["crit_3"];
$crit_3a = number_format($crit_3);
$crit2_3 = $row["crit2_3"];
$crit2_3a = number_format($crit2_3);
$crit3_3 = $row["crit3_3"];
$crit3_3a = number_format($crit3_3);
$user1 = ($crit_3) ;
$user2 = ($crit2_3);
$user3 = ($crit3_3);
$divide = ($user1 + $user2 + $user3);
$total = number_format($divide / 9 , 2, '.', '');
$average = number_format($total * 0.15 , 2, '.', '');
$scores_array[$row['user_name']] = $total; // assign total to the array and i assume that your table has one column name user_name for each user, change accordingly
}
rsort($scores_array);// sort the array in decending order of total scores
foreach ($scores_array as $key=>$value){ // iterate through array
echo $key.'has scored total score:-'.$value; //print the score along with username
}
?>
Note:- Please take the variable names in such a way that they will not produce any ambiguity.

PHP Count Generated Results From Loop

I have this for loop that generates 10 results:
<?php
include "dbconnect.php";
$table = "SELECT id FROM players ORDER BY RAND()* ( 1 / percentage)";
for ($i = 0; $i < 10; $i++){
$result[0] = mysql_fetch_array(mysql_query($table));
foreach ($result as $winner){
echo $winner[0] . " ";
}
}
?>
It generates a result like:
10 10 11 9 13 11 10 12 8 12
My question is how do I count the generation? For the above example it would be:
8's = 1, 9's = 1, 10's = 3, 11's = 2, 12's = 2, 13's = 1.
I basically want to count the amount of specific results generated. Sorry if i'm not making much sense.
You need to get off of MySQL functions and check out PDO or MySQLI at a minimum. But for the meat of the question:
Don't run a query, full or limited in the loop
Look at the LIMIT clause in the query
array_count_values will count the values. You can loop it and echo or whatever
Example:
$table = "SELECT id FROM players ORDER BY RAND()*(1/percentage) LIMIT 10";
$result = mysql_query($table);
while($row = mysql_fetch_array($result)) {
$winner[] = $row[0];
}
echo implode(' ', $winner);
foreach(array_count_values($winner) as $number => $count) {
$output = "$number's = $count";
}
echo implode(', ', $output);
You're existing code to make the random choice work would look like (LIMIT 1):
$table = "SELECT id FROM players ORDER BY RAND()*(1/percentage) LIMIT 1";
for($i = 0; $i < 10; $i++){
$result = mysql_fetch_array(mysql_query($table));
$winner[] = $row[0];
}
echo implode(' ', $winner);
if you check the php manual:
http://php.net/manual/en/function.mysql-query.php
then try something like this:
while ($row = mysql_fetch_assoc($table)) {
echo $row['column_name'];
echo $row['column_name'];
//.. you get the idea
}
The id is usually the first column in a database table. This is why you are just getting the id. You need to access each row in the same way you access arrays.
I should point out that the mysql library is deprecated. So you should consider using something like PDO instead.

Loop through mysql table row and check if any column matches a set number in php

Im trying to loop through a mysql table and check if a row contains the number I specify:
Here is what I have:
mysql table with numbers:
mysql table:
no1|no2|no3|no4|no5
1 3 5 2 6
4 7 8 9 8
2 6 9 1 0
...
For Example: I have number
4 5 3 7
So in the first row i should get a total of 2 as there are numbers 3 and 5 first row and this numbers are in the number I have specified.
In the second row I should get a total of 1 as only a 4 is in the row and the number i have specified.
And in the last row total should be 0 as there are no matches.
I hope its clear.
I have tried the following but it dont work I hope someone can help me work it out thanks in advance.
$lottono1=4;
$lottono2=5;
$lottono3=3;
$lottono4=7;
$no1 = 0;
$no2 = 0;
$no3 = 0;
$no4 = 0;
do { ?>
// i done the following if code for each numbers but
//putting this only to take less space
if (($row_Recordset1['no1']=$lottono1) || ($row_Recordset1['no1']=$lottono2) || ($row_Recordset1['no1']=$lottono3) || ($row_Recordset1['no1']=$lottono4)) {
$no1=1;
}
while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
select *,
if(no1 in (4,5,3,7),1,0)+
if(no2 in (4,5,3,7),1,0)+
if(no3 in (4,5,3,7),1,0)+
if(no4 in (4,5,3,7),1,0)+
if(no5 in (4,5,3,7),1,0) as found
from table
Well for one, your operators are wrong in your "if" conditions (you're setting rather than comparing).
Regardless i'd do something more like:
$numbers_to_match = array(4,5,3,7) ;
$query = mysql_query("select * from `table` where ____",connection_here);
$matches[] = array();
$i=0;
while($r=mysql_fetch_array($query)){
$matches[$i]=0;
foreach($r as $val){
if (in_array($val,$numbers_to_match)){
$matches[$i]++;
}
}
$i++;
}
print_r($matches);
Untested, but this should give you an array that lists the number of matches for each row
To accomplish with PHP/MySQL you can do the following:
$query = 'SELECT * FROM table';
$result = mysql_query($query) or die();
$matchValues = array(4,5,3,7);
while($row = mysql_fetch_array($result)){
$counter = 0;
foreach($matchValues as $value)
{
if(in_array($value, $row))
{
$counter++;
}
}
print "Searched row and found $counter matches<br/>";
}

Categories