Storing multiple rows from MySQL in separate variables - php

I am writing a web application in PHP which will store employee data and generate employee ID cards to PDF. I am using FPDF for creation of PDFs and that works fine. I am having a problem with showing results from MySQL database.
I have to generate PDF with 4 employee ID cards and I am not sure how to get them from the database. So far I am using LIMIT option in the query to get only 4 results and i will have an if statement based on mysql.php?id=1 id which will define the limit. It is a little messy but there are not going to be more than 80 employees.
This is my code:
$id = $_GET['id'];
if ($id == 1) {
$limit_start = 0;
$limit_end = 4;
}
$result=mysql_query("SELECT users.tajemnik, users.dateCreated, users.showmeID,
users.workerName, users.dateCreated, users.workerPlace, users.workerSID, uploads.userID, uploads.data, uploads.filetype
FROM users INNER JOIN uploads ON users.showmeID = uploads.userID ORDER BY workerName DESC LIMIT $limit_start, $limit_end") or die (mysql_error());
mysql_query("SET NAMES 'utf8'") or die('Spojení se nezdařilo');
while($row = mysql_fetch_array($result)){
$workerName = $row["workerName"];
$workerPlace = $row["workerPlace"];
$workerSID = $row["workerSID"];
$tajemnik = $row["tajemnik"];
$showmeID = $row["showmeID"];
$mysqldatetime = strtotime($row['dateCreated']);
$image = $row["data"];
$phpdatetime = date("d.m.Y",$mysqldatetime);
}
This will get me the first result from the query. I need to get information from all 4 rows and have them stored in variables like $workerName1, $workerName2 etc. I hope it makes sense what I am trying to do.
Thank you for your replies!
V.

I need to get variables like $workerName1, $workerName2 etc
Nope, you don't.
You actually need an array.
So, first, get yourself a function
function sqlArr($sql){
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if ($res) {
while($row = mysql_fetch_array($res)){
$ret[] = $row;
}
}
return $ret;
}
then write a code
mysql_query("SET NAMES 'utf8'") or die('Spojení se nezdařilo');
$sql = "SELECT users.tajemnik, users.dateCreated, users.showmeID, users.workerName,
users.dateCreated, users.workerPlace, users.workerSID, uploads.userID,
uploads.data, uploads.filetype
FROM users
INNER JOIN uploads ON users.showmeID = uploads.userID
ORDER BY workerName DESC LIMIT $limit_start, $limit_end";
$data = sqlArr($sql);
Now you have all your data in the $data array.
So, you can loop over it or access single values like
echo $data[0]['tajemnik'];
or
foreach($data as $row) {
//do whatever you want with database row
echo $row['tajemnik'];
}

Related

Create a randomized assoc array from database table results

I am creating a simple drag and drop jquery game and it requires a shuffled resultset of 10 rows from my database table. I am able to achieve this by repeating 10 separate blocks of queries, but I am sure there must be a more elegant way to do this. I tried many things, with loops and append etc. but I can't get the loop-way working.
I can't get this loop version to work:
<script type="text/javascript">
<?php
// first create list of 10 fake id's and shuffle them
$id_array = range(0, 9);
shuffle($id_array);
/*
// then loop to fetch all data from MySql table with spanish, english
// CANNOT GET THIS WORKiNG ?
for (i = 0; i < 10; i++) {
$query = "SELECT id, english, spanish FROM colors WHERE id = $id_array[i]";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$rand_value.append(i) = $row['english'];
$name.append(i) = strtoupper($row['spanish']);
}
*/
Writing it out works, but there must be an easier way...
<script type="text/javascript">
<?php
// create all input from MySql table for drag and drop area with spanish, english
$query = "SELECT id, english, spanish FROM colors WHERE id = $id_array[0]";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$random_key0 = $row['id'];
$rand_value0 = $row['english'];
$name0 = strtoupper($row['spanish']);
$query = "SELECT id, english, spanish FROM colors WHERE id = $id_array[1]";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$random_key1 = $row['id'];
$rand_value1 = $row['english'];
$name1 = strtoupper($row['spanish']);
// and so on to run 10 queries total
?>
Simplify everything by using RAND() in your query. Use just one query and retrieve all ten rows in a shuffled order.
$query="SELECT id,english,UPPER(spanish) FROM colors ORDER BY RAND() LIMIT 10;";
$result=mysqli_query($link,$query);
while($row=mysqli_fetch_array($result)){
// prepare and handle your results using: $row['id'], $row['english'], $row['spanish']
}
EDIT: I've added UPPER() to the query so that the spanish values don't need to be modified later in your php.

How to query a database with an array outside a loop

Hie. I am trying not to place an SQL query inside a loop, since this improves performance. I think I am supposed to use implode. But can't figure out how to do it. Here is my code:
<?php
//FUNCTION CONNECTNG TO DB HERE
function turn_result_to_array($result)
{
$result_array = array();
for ($count=0; $row = mysql_fetch_array($result); $count++)
{
$result_array[$count] = $row;
}
return $result_array;
}
function get_sender_username()
{
//connect to DB
$query = sprintf("SELECT DISTINCT sender FROM direct_messages
WHERE receiver_username='%s'
ORDER BY direct_messages.id DESC",
mysql_real_escape_string($_COOKIE['username']));
$result = mysql_query($query);
$result = turn_result_to_array($result);
return $result;
}
$senders = get_sender_username();
foreach($senders as $sender)
{ //SELECT IMAGE(S) FROM USER TABLE WHERE USERNAME = $SENDERS }
Instead of putting the query inside the FOREACH, i want to put it after, so i don't make multiple round trips to the database. FYI i already know that we supposed to switch to PDO. Thanks in advance.
Here is one way of doing it:
$senderInString = implode("','",$senders);
$senderInString = "('$senderInString')";
$newQuery = "SELECT something FROM tables WHERE sender in $senderInString;"
$newResult = mysql_query($newQuery);
Use
$query= "SELECT IMAGE(S) FROM USER TABLE WHERE USERNAME IN (".implode(',',$senders).")";
$result = mysql_query($query);
In the place of foreach

how to get a particular field from a database via php

I am trying to get four different values from my database. The session variable username and usernameto are working, but I want to get 4 different values -- two each from username and usernameto:
<?php
session_start(); // startsession
$Username=$_SESSION['UserID'];
$Usernameto= $_SESSION['UserTO'];
$db = mysql_connect("at-web2.xxxxxx", "yyyyy", "xxxxxxx");
mysql_select_db("db_xxxxxx",$db);
$result1 = mysql_query("SELECT user_lon and user_lat FROM table1 WHERE id = '$Usernameto'");
$result2 = mysql_query("SELECT user_lon and user_lat FROM table1 WHERE id = '$Username'");
$myrow1 = mysql_fetch_row($result1);
$myrow2 = mysql_fetch_row($result2);
while($myrow1)
{
$_Mylon=$myrow1[0];
$_Mylat=$myrow1[1];
}
while($myrow2)
{
$_Mylon2=$myrow2[0];
$_Mylat2=$myrow2[1];
}
?>
Edit - just realized that you didn't tell us what wasn't working about the code you provided. Are you getting an error message or are you not getting the correct data back? You still should fix your query, but we'll need some more information to know what's wrong.
Your query statements shouldn't have "and" between the select parameters, so it should be:
Edit 2 - I just noticed that you had a while loop that you don't need, try this:
$result1 = mysql_query("SELECT user_lon, user_lat FROM table1 WHERE id = '$Usernameto'");
$result2 = mysql_query("SELECT user_lon, user_lat FROM table1 WHERE id = '$Username'");
$myrow1 = mysql_fetch_row($result1);
$myrow2 = mysql_fetch_row($result2);
if (isset($myrow1)) {
$_Mylon=$myrow1[0];
$_Mylat=$myrow1[1];
}
if (isset($myrow2)) {
$_Mylon2=$myrow2[0];
$_Mylat2=$myrow2[1];
}
An example from the php manual echoing an html table
I don't know if you can derive what you need from this?
More specific: You can use:
$line = mysql_fetch_array($result, MYSQL_ASSOC);

Is there a more efficient way to express this query

I have a query for my mysql database but I just want to know if there is more of a simpler way of achieving something, here is my code:
$sql="SELECT value
FROM drivers
WHERE drivers_id = '$driver1' OR drivers_id = '$driver2' OR drivers_id = '$driver3'";
$result = mysql_query($sql);
$i = 1;
while ($row = mysql_fetch_assoc($result)) {
${'value'.$i} = $row['value'];
$i++;
}
This is how I want my code as it is shorter, but the problem I am having is that I need to know that where the $driver1 variable is found in the database the data retrieved for that is placed inside the value1 variable, and the retrieved information for $driver2 is placed inside $value2. However it grabs the data from the database in the order that it comes across the matches. I don't want to have to write 3 different queries for this because I am sure it can be done in one.
$sql="SELECT drivers_id, value FROM drivers WHERE drivers_id IN ('$driver1','$driver2','$driver3')";
$result=mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
${'value_for_'.$row['drivers_id']}=$row['value'];
}
Boom.
Though personally, instead of on-the-fly variables, I'd use an array w/ the id's as keys:
...
$resultArray = array();
while($row = mysql_fetch_assoc($result)) {
$resultArray[$row['drivers_id']]=$row['value'];
}
If you want to change the order of the results, you can add an order by clause to the query:
$sql = "SELECT drivers_id, value FROM drivers WHERE drivers_id IN ('$driver1','$driver2','$driver3') ORDER BY drivers_id";
...

PHP - Select a unique mysql line without while [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 6 months ago.
I want to select only unique values with php/mysql.
I can do it with many line, but I forget how to do it without while... :)
Thanks a lot.
Here is the code that I want to do without while.
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
while($row = mysql_fetch_array($result_1m))
{
/* Get the data from the query result */
$date1_1m = $row["date1"];
$date2_1m = $row["date2"];
}
mysql_fetch_assoc + SELECT with DISTINCT
I'm not sure I understand your question, but here's what I think you want to do :
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
list($date1_1m, $date2_1m) = mysql_fetch_row($result_1m);
Note that this will only get the first row from the result set (just as if you LIMIT 1)
like this?
$dbresult = mysql_query("SELECT DISTINCT field FROM table");
$result = array();
while ($row = mysql_fetch_assoc($dbresult))
{
$result[] = $row;
}
This gets you all unique values from "field" in table "table".
If you really wish to avoid the while loop, you can use the PHP PDO objects, and in particular call the PDO fetchAll() method to retrieve the complete results array in one go. PDO fetchAll() documentation
$db = new PDO('dblib:host=your_hostname;otherparams...');
$db->query("SELECT DISTINCT col FROM table");
$results = $db->fetchAll();
// All your result rows are now in $results
Heres how I do it and Json encode after. This will ensure it will encode only UNIQUE json Values (Without duplicates) as an example
$tbl_nm = "POS_P";
$prod_cat = "prod_cat";
//Select from the POS_P Table the Unique Product Categories using the DISTINCT syntax
$sql = "SELECT DISTINCT $prod_cat FROM $tbl_nm";
//Store the SQL query into the products variable below.
$products = mysql_query($sql);
if ($products){
// Create an array
$rows = array();
// Fetch and populate array
while($row = mysql_fetch_assoc($products)) {
$rows[]=$row;
}
// Convert array to json format
$json = json_encode(array('Categories'=>$rows));
echo $json;
}
//Close db connection when done
mysql_close($con);
?>
That is very easy, take out the while, like below
$row = mysqli_fetch_assoc($result);
$date1_1m = $row["date1"];

Categories