Select values from table and show it by while? - php

I want to select values by 'while' but ther is problam, this is the code:
<?php
$following_select_article = mysql_query("SELECT * FROM follow WHERE user_follower_id='$user_id'");
while( $following_select_article_row = mysql_fetch_array($following_select_article) ) {
$article_following_user_id = $following_select_article_row['user_following_id'].",";
$mmnnss = substr_replace($article_following_user_id, "", -1);
$echo $mmnss;
}
note $user_id = 1
The desired output is
2,3,4
but what I get is
234
The db is like this:
follow table:
id | user_follower_id | user_following_id
1 | 1 | 2
2 | 1 | 4
3 | 1 | 3
thanks

Do This
<?php
$following_select_article = mysql_query("SELECT * FROM follow WHERE user_follower_id='$user_id'");
$article_following_user_id = "";
while($following_select_article_row = mysql_fetch_array($following_select_article)){
$article_following_user_id .= $following_select_article_row['user_following_id'].",";
}
$mmnnss = substr_replace($article_following_user_id, "", -1);
echo $mmnnss;
since your substr_replace is in loop so every time after creating $article_following_user_id with , it replace the last character every time
Edit
As suggested by Glavić if you can replace your
substr_replace($article_following_user_id, "", -1);
With
substr($article_following_user_id, 0, -1);

Related

PHP Compare column values and edit database accordingly

I am a newbie to PHP and I am stuck at a certain point. I tried looking up a solution for it however, I didn't find exactly what I need.
My goal is to create a leaderboard, in which the values are displayed in descending order plus the rank and score are displayed. Furthermore, it should also display whether or not a tie is present.
The database should look like this:
+---------+------+----------------+-------+------+
| user_id | name | email | score | tied |
+---------+------+----------------+-------+------+
| 1 | SB | sb#gmail.com | 1 | 0 |
+---------+------+----------------+-------+------+
| 2 | AS | as#web.de | 2 | 0 |
+---------+------+----------------+-------+------+
| 3 | BR | br#yahoo.com | 5 | 1 |
+---------+------+----------------+-------+------+
| 4 | PJ | pj#gmail.com | 5 | 1 |
+---------+------+----------------+-------+------+
And the outputted table should look something like this:
+------+-------------+-------+------+
| rank | participant | score | tied |
+------+-------------+-------+------+
| 1 | BR | 5 | Yes |
+------+-------------+-------+------+
| 2 | PJ | 5 | Yes |
+------+-------------+-------+------+
| 3 | AS | 2 | No |
+------+-------------+-------+------+
| 4 | SB | 1 | No |
+------+-------------+-------+------+
I managed to display the rank, participant and the score in the right order. However, I can't bring the tied column to work in the way I want it to. It should change the value, whenever two rows (don't) have the same value.
The table is constructed by creating the <table> and the <thead> in usual html but the <tbody> is created by requiring a php file that creates the table content dynamically.
As one can see in the createTable code I tried to solve this problem by comparing the current row to the previous one. However, this approach only ended in me getting a syntax error. My thought on that would be that I cannot use a php variable in a SQL Query, moreover my knowledge doesn't exceed far enough to fix the problem myself. I didn't find a solution for that by researching as well.
My other concern with that approach would be that it doesn't check all values against all values. It only checks one to the previous one, so it doesn't compare the first one with the third one for example.
My question would be how I could accomplish the task with my approach or, if my approach was completely wrong, how I could come to a solution on another route.
index.php
<table class="table table-hover" id="test">
<thead>
<tr>
<th>Rank</th>
<th>Participant</th>
<th>Score</th>
<th>Tied</th>
</tr>
</thead>
<tbody>
<?php
require("./php/createTable.php");
?>
</tbody>
</table>
createTable.php
<?php
// Connection
$conn = new mysqli('localhost', 'root', '', 'ax');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL Query
$sql = "SELECT * FROM names ORDER BY score DESC";
$result = $conn->query("$sql");
// Initalizing of variables
$count = 1;
$previous = '';
while($row = mysqli_fetch_array($result)) {
$current = $row['score'];
$index = $result['user_id']
if ($current == $previous) {
$update = "UPDATE names SET tied=0 WHERE user_id=$index";
$conn->query($update);
}
$previous = $current;
?>
<tr>
<td>
<?php
echo $count;
$count++;
?>
</td>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['score'];?></td>
<td>
<?php
if ($row['tied'] == 0) {
echo 'No';
} else{
echo 'Yes';
}
?>
</td>
</tr>
<?php
}
?>
I think the problem is here
$index = $result['user_id'];
it should be
$index = $row['user_id'];
after updating tied you should retrieve it again from database
So I solved my question by myself, by coming up with a different approach.
First of all I deleted this part:
$current = $row['score'];
$index = $result['user_id']
if ($current == $previous) {
$update = "UPDATE names SET tied=0 WHERE user_id=$index";
$conn->query($update);
}
$previous = $current;
and the previous variable.
My new approach saves the whole table in a new array, gets the duplicate values with the array_count_values() method, proceeds to get the keys with the array_keys() method and updates the database via a SQL Query.
This is the code for the changed part:
// SQL Query
$sql = "SELECT * FROM names ORDER BY score DESC";
$result = $conn->query("$sql");
$query = "SELECT * FROM names ORDER BY score DESC";
$sol = $conn->query("$query");
// initalizing of variables
$count = 1;
$data = array();
// inputs table into an array
while($rows = mysqli_fetch_array($sol)) {
$data[$rows['user_id']] = $rows['score'];
}
// -- Tied Column Sort --
// counts duplicates
$cnt_array = array_count_values($data);
// sets true (1) or false (0) in helper-array ($dup)
$dup = array();
foreach($cnt_array as $key=>$val){
if($val == 1){
$dup[$key] = 0;
}
else{
$dup[$key] = 1;
}
}
// gets keys of duplicates (array_keys()) and updates database accordingly ($update query)
foreach($dup as $key => $val){
if ($val == 1) {
$temp = array_keys($data, $key);
foreach($temp as $k => $v){
$update = "UPDATE names SET tied=1 WHERE user_id=$v";
$conn->query($update);
}
} else{
$temp = array_keys($data, $k);
foreach($temp as $k => $v){
$update = "UPDATE names SET tied=0 WHERE user_id=$v";
$conn->query($update);
}
}
}
Thank you all for answering and helping me get to the solution.
instead of the update code you've got use something simular
$query = "select score, count(*) as c from names group by score having c > 1";
then you will have the scores which have a tie, update the records with these scores and your done. Make sure to set tie to 0 at first for all rows and then run this solution
UPDATE for an even faster solution sql based:
First reset the database:
$update = "UPDATE names SET tied=0";
$conn->query($update);
All records have a tied = 0 value now. Next update all the records which have a tie
$update = "update docs set tied = 1 where score IN (
select score from docs
group by score having count(*) > 1)";
$conn->query($update);
All records with a tie now have tied = 1 as we select all scores which have two or more records and update all the records with those scores.

How to update multiple rows in one query (using for loop) [duplicate]

This question already has an answer here:
Post form and update multiple rows with mysql
(1 answer)
Closed last year.
For example, I have two data on my table:
| ID | Name | Age |
| 1 | Steve | 25 |
| 2 | Bob | 28 |
When i updating one value (for example: change "Bob" to "George"), it changes all value. This is the result:
| ID | Name | Age |
| 1 | George | 28 |
| 2 | George | 28 |
How to updating multiple rows in one query? To collect values, I use for loop like this:
<?php
...
$id_array = $_POST['id'];
$name_array = $_POST['name'];
$age_array = $_POST['age'];
$id = array();
$name = array();
$age = array();
for ($i = 0; $i < count($id_array); $i++) {
//count($id_array) --> if I input 4 fields, count($id_array) = 4)
$id[] = mysql_real_escape_string($id_array[$i]);
$name[] = mysql_real_escape_string($name_array[$i]);
$age[] = mysql_real_escape_string($age_array[$i]);
}
mysql_query("UPDATE member SET name = '$name', age = '$age' WHERE id = '$id'");
}
...
?>
Can you help me? Thank you.
Construct your query within the loop:
<?php
...
$id_array = $_POST['id'];
$name_array = $_POST['name'];
$age_array = $_POST['age'];
for ($i = 0; $i < count($id_array); $i++) {
//count($id_array) --> if I input 4 fields, count($id_array) = 4)
$id = mysql_real_escape_string($id_array[$i]);
$name = mysql_real_escape_string($name_array[$i]);
$age = mysql_real_escape_string($age_array[$i]);
$query .= "UPDATE member SET name = '$name', age = '$age' WHERE id = '$id';";
}
mysql_query($query);
}
...
?>
Hope that helps..!
Answer to your Question
MySQL updates all rows matching the WHERE clause, so to update multiple rows with the same value, you should use a condition matching all rows. To update all rows, dont set any where clause.
To update multiple rows with different values, you can't, use several queries.
Answer to your issue
In your code, $id, $name and $age are arrays so you can not use it in a string, this will not work. You should do the update in your FOR loop.
I advise you to try to respect resource oriented principe that all properties are assigned to their item (with associative array or object).
If you dont check the result, you could do all queries in one using a semi-colon.

FIFO calculation in php (mysql)

I have two data tables stock_incomes, stock_outcomes and stock_outcomes_fifo (the one I insert pre-calculated data):
stock_incomes (stores leftovers data)
id| Levtv
-----------
7 | 100
8 | 250
9 | 350
stock_outcomes (here is the point)
id| Quantity
--------------
1 | 150*
I have no problem when stock_outcomes.Quantity is less than 100 (min(Id) from stock_incomes, please see my code below) but I have no idea what code to write I could get calculations if outcome is >100. In my example I used 150 and I would like to get data in next table as:
stock_outcomes_fifo (the one I wish to insert pre-calculated data from the previous two tables)
id| IncomeId| OutcomeId| OutcomePart| Leftv
---------------------------------------------
1 | 7 | 1 | 100 | 0
2 | 8 | 1 | 50 | 200
Here is my code with question inside (see last part of the code):
<?php
include_once("config.inc.php");
include_once("db.class.php");
// stock_outcomes
$db = new db($host, $database, $user, $passwd);
$sql = "SELECT * FROM stock_outcomes WHERE Id = '1'";
$mas = $db->get_array($sql);
if($mas) {
foreach ($mas as $k => $v) {
$OutcomeId = $mas[$k]['Id'];
$OutcomeQuantity = $mas[$k]['Quantity'];
}
}
// stock_incomes
$sql = "select * from stock_incomes where Id = (select min(Id) from stock_incomes where Leftv > 0)";
$mas = $db->get_array($sql);
if($mas) {
foreach ($mas as $k => $v) {
$IncomeId = $mas[$k]['Id'];
$IncomeLeftv = $mas[$k]['Leftv'];
}
}
// insert into stock_outcomes_fifo
if ($OutcomeQuantity <= $IncomeLeftv) {
$OutcomePart = $OutcomeQuantity;
$FifoLeftv = $IncomeLeftv - $OutcomeQuantity;
mysql_query("INSERT INTO `stock_outcomes_fifo` (IncomeId,OutcomeId,OutcomePart,Leftv) VALUES ($IncomeId, $OutcomeId, $OutcomePart, $FifoLeftv)");
}
if ($OutcomeQuantity > $IncomeLeftv) {
// I have no idea what php function to use in this case... please give me direction, thank you...
}
?>
The question has been solved, here is the final working code in case someone might need it:
<?php
include_once("config.inc.php");
include_once("db.class.php");
// stock_outcomes
$db = new db($host, $database, $user, $passwd);
$sql = "SELECT * FROM stock_outcomes WHERE Id = '1'";
$mas = $db->get_array($sql);
if($mas){
foreach ($mas as $k=>$v) {
$OutcomeId=$mas[$k]['Id'];
$OutcomeBarCode=$mas[$k]['BarCode'];
$OutcomeQuantity=$mas[$k]['Quantity'];
}
}
/* - Start code */
if ($OutcomeQuantity > 0) {
$sql = "select * from stock_incomes where Leftv > 0 order by id asc";
$mas = $db->get_array($sql);
if ($mas) {
//filing stock_outcomes_fifo
foreach ($mas as $k=>$v) {
$IncomeId = $mas[$k]['Id'];
$IncomeQuantity = $mas[$k]['Quantity'];
$IncomeUnitPrice = $mas[$k]['UnitPrice'];
$IncomeLeftv = $mas[$k]['Leftv'];
$OutcomePart = min($OutcomeQuantity, $IncomeLeftv);
$FifoLeftv = $IncomeLeftv - $OutcomePart;
$FifoCost = $IncomeUnitPrice * $OutcomePart;
mysql_query("INSERT INTO `stock_outcomes_fifo` (BarCode,IncomeId,OutcomeId,OutcomePart,UnitPrice,Leftv,Cost) VALUES ($OutcomeBarCode, $IncomeId, $OutcomeId, $OutcomePart, $IncomeUnitPrice, $FifoLeftv, $FifoCost)");
mysql_query("UPDATE `stock_incomes` SET Leftv = ".$FifoLeftv." WHERE Id = ".$IncomeId);
$OutcomeQuantity -= $OutcomePart;
if ($OutcomeQuantity <= 0) break;
}
$OutcomeCostQuery = "select sum(Cost) as summ from stock_outcomes_fifo where OutcomeId = ".$OutcomeId."";
$OutcomeCost = mysql_query($OutcomeCostQuery);
$OutcomeCostResult = mysql_fetch_array($OutcomeCost);
mysql_query("UPDATE `stock_outcomes` SET Cost = ".$OutcomeCostResult["summ"]." WHERE Id = ".$OutcomeId."");
}
} /* - Finish code */
?>
Please help me let me explain with this.....
purchase table
id purchase_id product_id qty net_unit_cost created_at
-------------------------------------------------------------------------
1 1 1 10 10 2022-10-10
--------------------------------------------------------------------------
2 2 1 20 12 2022-10-10
Sale table
sale_id product_id qty net_unit_price created_at
1 1 11 15 2022-10-10
in this, if i sold '11' units then how can i subtract from the rows to get remaining units? i've to subtract '10' units from first row and '1' unit from second row...

How to display array in table format that has fields before each other in php

I have an array like this.
$array[0] = 'email1';
$array[1] = 'email2';
$array[2] = 'email3';
$array[3] = 'mobile1';
$array[4] = 'mobile2';
$array[5] = 'mobile3';
$array[6] = 'email1_c';
$array[7] = 'email2_c';
$array[8] = 'email3_c';
$array[9] = 'mobile1_c';
$array[10] = 'mobile2_c';
$array[11] = 'mobile3_c';
Now i want to dispay a table like this
--------------------------------
email1 | email1_c
email2 | email2_c
email3 | email3_c
mobile1 | mobile1_c
mobile2 | mobile2_c
mobile3 | mobile3_c
Now when i loop through the array i get this
--------------------------------
email1 | email2
email3 | mobile1
mobile2 | mobile3
email1_c | email2_c
email2_c | mobile1_c
mobile1_c | mobile3_c
Now this is not what i want and i know simple looping wont do what i want.
So is there any alternative way to achieve this.
Note : The data given is only sample data. I am actually working in a pre-defined
template in wordpress and wordpress simply throw me an object so i can use it. In
the backend i have tried everything even sorting but i get the data like above.
I need alternative so i can change easily and i dont want to modify default files.
It appears that it depends on an offset value. As you have it shown that value would be six:
$html = "<table>\n";
$offset = 6;
for ($i=0; $i<=5; $i++){
$html .= "<tr><td>".$array[$i]."</td><td>".$array[$i + $offset]."</td></tr>\n";
}
$html .= "</table>\n";
Depending on what you need you might need to dynamically calculate the offset. For example:
$offset = count($array)/2;

php get mysql result not as array, but as text

I want to get text result like:
+----+-------+----------------------------------+----+
| id | login | pwd | su |
+----+-------+----------------------------------+----+
| 1 | root | c4ca4238a0b923820dcc509a6f75849b | 1 |
+----+-------+----------------------------------+----+
1 row in set (0.00 sec)
in PHP (string).
Example in php:
$query = mysql_query("SELECT * FROM users");
for (; $row = mysql_fetch_assoc($query); $data[] = $row);
I get array of arrays ($data):
$data =
0 => (id=>1, login=>root..)
But i want to get this as string:
+----+-------+----------------------------------+----+
| id | login | pwd | su |
+----+-------+----------------------------------+----+
| 1 | root | c4ca4238a0b923820dcc509a6f75849b | 1 |
+----+-------+----------------------------------+----+
1 row in set (0.00 sec)
By the way for query "insert into users set login = 'sp', pwd = 1, su = 0", this string must be "Query OK, 1 row affected, 2 warnings (0.18 sec)".
Like sql terminal though php!
Either invoke mysql client as an external command, or build the ASCII drawing table yourself. You can't get it purely by using PHP's MySQL library functions. Off the top of my head,
$result = `echo 'SELECT * FROM users' | mysql --user=username --password=password dbname`;
(ugly, slow, insecure, don't recommend); or simply get it as the array, iterate, and decorate with plusses imitating what mysql does (recommended). It's really easy.
However, I have no clue why you'd want that, unless you're using your PHP program as a command-line tool.
Collect the database result into an array of arrays(your $data variable is correct)
echo ascii_table($data);
I stole the following from someone named stereofrog
function ascii_table($data) {
$keys = array_keys(end($data));
# calculate optimal width
$wid = array_map('strlen', $keys);
foreach($data as $row) {
foreach(array_values($row) as $k => $v)
$wid[$k] = max($wid[$k], strlen($v));
}
# build format and separator strings
foreach($wid as $k => $v) {
$fmt[$k] = "%-{$v}s";
$sep[$k] = str_repeat('-', $v);
}
$fmt = '| ' . implode(' | ', $fmt) . ' |';
$sep = '+-' . implode('-+-', $sep) . '-+';
# create header
$buf = array($sep, vsprintf($fmt, $keys), $sep);
# print data
foreach($data as $row) {
$buf[] = vsprintf($fmt, $row);
$buf[] = $sep;
}
# finis
return implode("\n", $buf);
}
You can please query the following sql:
SELECT GROUP_CONCAT(id, ' | ', login, ' | ', pwd, ' | ', su)
AS 'User Object' FROM users group by id
Result Would Be:

Categories