This question already has answers here:
add extra column to sql query result with constant value
(2 answers)
Closed 5 months ago.
I want to know what is the best approach if I want to perform select query to MySQL database and then add a new column to the result array which will be exported to a file at later time?
To clarify the process, assume the table have the following data:
id name lastname email
1 john doe example#example.com
2 jane doe example2#example2.com
if I perform the following select query :
$query = "SELECT * from table_name";
$result = mysqli_query($conn, $query);
I get the previous result , and then I want to add a new column to it with static value for all the rows like the following:
Important note: I want to add the column to the returned result not to the database ,because this result is written into a file at a later time.
const_value id name lastname email
samevalue 1 john doe example#example.com
samevalue 2 jane doe example2#example2.com
currently I'm doing this using PHP:
while($row = mysqli_fetch_assoc($result))
{
array_unshift($row , 'samevalue');
}
So is there an easy method of doing this in php or in MySQL during the query ?
You can do that in the original query if that makes sense to your process like this
SELECT 'SameValue' as const_value, id, lastname, email from table_name;
If you really want to do it in PHP then something like this
while($row = mysqli_fetch_assoc($result))
{
$row['const_value'] = 'SameValue';
. . . your other code
}
Or if you want to keep all the rows for later processing
$rows = [];
while($row = mysqli_fetch_assoc($result))
{
$row['const_value'] = 'SameValue';
$rows[] = $row
}
Related
I have a MySQL table that looks like this
index (auto incremented)
data
type
1
a1
1
3
a2
1
4
b62
3
9
m52
1
and i loop through it with this code
for($i=1; $i<= number of rows; $i++){
$query = "SELECT * FROM messagesforinstructor where type='1' and index='$i'";
$result = mysqli_query($db, $query);
$display=mysqli_fetch_assoc($result);
echo $display['data'];
}
but as you can see that it would fail cause the auto incremented indexes are not sequential.so at i=2 it would fail without making it to i=3.
any idea how to make it select the next index in the table
Simple solution
Don't use * use specified column names
Use one query to retrieve the entire result set
Use OOP approach and save yourself having to repeat code (you don't neeed to change the connection but you can:
// From...
$db = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
// To...
$db = new mysqli($db_host,$db_user,$db_pass,$db_name)
I assume that type is an integer field; no need to use quotation marks in the query
Code
// Run the query to select the messages
$sql = "SELECT data FROM messagesforinstructor WHERE type = 1";
$query = $db->query($sql);
// Option 1
// Loop though result set with a foreach loop
foreach ($query as $message) {
echo $message[0];
}
// Option 2
// Loop through the result set with a while loop
while ($message = $query->fetch_assoc()) {
echo $message["data"];
}
I am trying to use the selected id's as an array a other statement. It seems it is not counting all the result as it is much lower that it is.. I have tried to find my answer on google but none of the options are working for me or i do not know how to use them in my case. There are no errors and i have error log on!
Here is my code, what am i doing wrong?
$counttheid = array();
$stmt3 = $mysqli->prepare("SELECT
id
FROM account
WHERE level <= '5' AND door = ? AND `group_name` = ? AND betaald = 'Yes'");
$stmt3->bind_param("ss",$usernamesession,$groupname);
$stmt3->execute();
$result3 = $stmt3->get_result(); //only works when nd_mysli is set on the server!
while ($rowid = $result3->fetch_assoc())
{
$counttheid[] = $rowid['id'];
$countid = implode(',', $counttheid);
}
$sql = "SELECT SUM(mobcash) AS totalcash FROM account WHERE id IN (?)
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s",$countid);
$stmt->execute();
$stmt->bind_result($row['totalcash']);
while($stmt->fetch()) $sumcash = $row['totalcash'];
//echo print_r($counttheid);
//echo implode(',', $counttheid);
echo $sumcash;
I am no profesional developer just started learning this, any help is welcome!
Since you have edited the question, my original answer is no longer relevant.
I suggest for you to simplify your two queries into a single query. In your first query you select a bunch of ids and in the second query you sum a different value from the same table using the ids. You can just to that in one query:
SELECT SUM(mobcash) AS totalcash
FROM account
WHERE level <= '5'
AND door = ?
AND `group_name` = ?
AND betaald = 'Yes';
Original answer
You use $result->fetch_all(MYSQLI_ASSOC), meaning each row from the result set will be an associative array with the column names as the keys and the cell values as values. That is also the case, if you only select one column.
That means for this example table
id | name | balance
----+------+---------
1 | acc1 | 12.34
2 | acc2 | 1.23
your variable $dataid will have the following value (for the simplified query SELECT id FROM account):
$dataid = [
[
"id": 1
],
[
"id": 2
]
];
To get more familiar with PHP, you could write some foreach loops yourself, but you can also use the built-in PHP function array_column (php.net: array_column):
$ids = array_column($dataids, "id");
From an SQL perspective I would also suggest for you to learn about nested queries, since you could avoid this PHP logic altogether.
This question already has answers here:
mysqli query results to show all rows
(4 answers)
Closed 4 years ago.
i've been trying for quite some time already to get this working, but no success at all
I looked around many places, and by what i understood, the method im using isnt retrieving the data i want, but in fact, ALL the data inside the DB (despite there only 1 value to be returned)
This is my code right now:
$query = "SELECT id from produtos where tipo = 'Tubo' and inteiro_pedaco = '$tipo' and marca = '$marca' and comprimento = '$comprimento' and diaexterno = '$externo' and diainterno = '$interno'";
$result = $conec->query($query);
echo $result;
die;
At the code above im trying to retrieve ID from a table named produtos
And here is the table 'produtos' content:
id: 102 | tipo: Tubo | inteiro_pedaco: Inteiro | marca: Science | comprimento: 1000 | diaexterno: 1 | diainterno: 1 |
id: 103 | tipo: Whatever | inteiro_pedaco: Whatever | marca: Whatever | comprimento: Whatever | diaexterno: Whatever | diainterno: Whatever |
etc...
$result variable was supposed to retrieve "102"
After retrieving 102, i want to echo it just for tests purposes
However, if i can manage to make it work and echo "102", my next step is making an insert into ANOTHER table with $result content, which is "102"
I want to insert at entrada_produtos table some data with the following command:
mysqli_query($conec,"INSERT INTO entrada_produtos (fk_id, usuario, data_inclusao, qtd) VALUES ('$result', '$usuario', now(), '$qtd')");
Any help would be appreciated, plus, i dont want just some code working, i would like to understand how it works
If possible, try to explain any code posted bellow, it would be of great help, also, i want to make it as simple as possible, i dont wanna use like 10 lines of code just to retrieve some data into a variable (if its the only possible way, then there's nothing i can do, but go this way...)
Thanks in advance
You need to fetch the results:
$row = $result->fetch_assoc();
$id = $row['id'];
echo $id;
fetch_assoc() returns the next row of results as an associative array.
You can then use the $id variable in your INSERT query.
There's no need to use two queries to insert this into another table, you can do that with one query.
$stmt = $conec->prepare("
INSERT INTO entrada_produtos (fk_id, usuario, data_inclusao, qtd)
SELECT id, ?, now(), ?
FROM produtos
where tipo = 'Tubo'
and inteiro_pedaco = ?
and marca = ?
and comprimento = ?
and diaexterno = ?
and diainterno = ?");
$stmt->bind_param("sssssss", $usuario, $qtd, $tipo, $marca, $comprimento, $externo, $interno);
$stmt->execute();
I've rewritten this as a prepared statement to prevent SQL injection. The ? in the query are placeholders, which are filled in with the variable values given in the call to bind_param().
BTW, if you're selecting the row that you just inserted into produtos, you can use the MySQL function LAST_INSERT_ID() or the PHP variable $conec->insert_id to get the auto-increment ID that was assigned, you don't need a query for that.
This question already has answers here:
SQL select only rows with max value on a column [duplicate]
(27 answers)
Closed 7 years ago.
How do I select from a database table a user id that is linked to the minimum value of the table
for example
User ID Pending
------- --------
0 5
1 4
2 7
'$resultSet = $mysqli->query("SELECT MIN(write_pending) FROM writerdata_tb");
if ($temp = $resultSet->fetch_assoc()) {
}'
in this case, I would want the data that is returned to have the value of the user with the least pending, in this case being user 1. How do I set up a MySqli query to handle this? And what would be the best way to save the result as a variable for use in the rest of my php?
Probably something like this, but it depends heavily on what your table structure is like. I've assumed you've got a generic users table with some IDs and this pending value you've mentioned.
SELECT userID FROM users WHERE pending = ( SELECT MIN(pending) FROM users );
The nested Select statement gets the smallest pending value in that column of your table, then you can refine your select userID statement by forcing pending to be the value returned from that nested select call.
UPDATE
To clarify your followup question of processing results, here's a modification of the code you provided:
$resultSet = $mysqli->query("SELECT userID FROM users WHERE pending = ( SELECT MIN(pending) FROM users )");
if($resultSet->num_rows > 0) {
//We use a while loop here, in the event that there are multiple rows
while($row = $resultSet->fetch_assoc()) {
echo $row["userID"]; //Accessing the rows index at "userID"
}
}
I have two different tables
And:
First i have used $timeapp_id which is the current user_id of the logged in user.
I want to display only the rows in user_info where $timeapp_id appears in timesheet_approver_1
So if my $timeapp_id is currently 8 then i should only get three rows displayed from user_info.
I have managed to get this part working with this code:
$data2b = "select * from user_info where timesheet_approver_1 = $timeapp_id";
$result2b = mysql_query($data2b);
while ($row2b = mysql_fetch_assoc($result2b)) {
$timesheet_approver_1 = $row2b['timesheet_approver_1'];
$timesheet_approver_2 = $row2b['timesheet_approver_2'];
$user_id2 = $row2b['user_id'];
//echo "( $timesheet_approver_1 / ";
//echo "$timesheet_approver_2 )";
echo "(($user_id2))";
So running this code gives me three rows from the table user_info where user_id is 5, 7 and 34.
This is where i am now stuck. What i want to do is only display the rows in time_data if the user_id in time_data matches the user_id in user_info
If this worked i should only see the rows in time_data where the user_id is 8, so only one row would be displayed.
How would i do this?
Thanks
David
For the variable $data2b you can JOIN the table user_info with table time_data ON user_info.user_id = time_data.user_id first, and then you can give the parameter WHERE the user_info.timesheet_approver_1 = $timeapp_id
What i did was pass the data through an array. I had got the code close to working but fatally wrong and so was not working through the array this is the correct working code i have used as corrected by Barmar on this site:
PHP array displaying last row values from table
$array = array();
while ($row2b = mysql_fetch_assoc($result2b)) {
$timesheet_approver_1 = $row2b['timesheet_approver_1'];
$timesheet_approver_2 = $row2b['timesheet_approver_2'];
$array[] = $row2b['user_id'];
}
$withComma = implode(", ", $array);