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";
...
Related
I'm running a query to get results from the database. The results are then saved in an array. I want to know how can I use those results from array to get further results from the database in a single query. Or I'll have to use multiple queries?
$query2="SELECT officeName FROM office
WHERE parentOfficeID='$parent'";
$result2=mysqli_query($connect,$query2);
if(mysqli_num_rows($result2) != 0)
{
$results= array();
while ($row2 = mysqli_fetch_assoc($result2))
{
$results[]=$row2['officeName'];
}
}
The $results array saves the results. I want to use the officeName values individually. Is there any way I use single query? Or I'll have to process each value?
Hi If I understand your question then first you want to fetch some officeName and store them in array and then want to fetch some other info based on that officeName . You can use this one
<?php
$db = new mysqli('localhost','root','','databasename');
$result = mysqli_query($db,"SELECT officeName FROM office WHERE parentOfficeID='$parent'") or die(mysqli_error($db));
$officeName = array();
while($row = mysqli_fetch_assoc($result)){
$officeName[] = $row['officeName'];//store your office name in an array
}
$officeName= join("', '", $officeName);//The join() function returns a string from the elements of an array. It is an alias of the implode() function.
$sql = "SELECT * FROM office WHERE officeName IN ('$officeName')";// query with IN condition
$result1 = mysqli_query($db,$sql) or die(mysqli_error($db));
while($row1 = mysqli_fetch_assoc($result1)){
echo "<pre>";print_r($row1);
}
for more info more about join(). Please read http://www.w3schools.com/php/func_string_join.asp
for mysqli IN condition please read http://www.mysqltutorial.org/sql-in.aspx
To add to #Nyranith, you could also swap out your while statement and use
mysqli_fetch_all($result2, MYSQLI_ASSOC);
Which will return your values as an associative array without the need for you to loop through and build the array yourself.
It's been a really long time since I used mysqli, could need tweaking but here goes.
Here's a better way to go about the process itself:
Assume you have tables: Office and Staff and for some reason, you are binding the office to staff by the office name (bad juju)
$parent = 1;
$query2="SELECT o.officeName, s.name
FROM office AS o
INNER JOIN staff AS s ON o.officeName = s.officeName
WHERE o.parentOfficeID=?";
$stmt = $connect->prepare($query2);
$query = $stmt->bindParam($parent);
$exec = $stmt->execute();
$results2 = mysqli_fetch_all($exec, MYSQLI_ASSOC);
Now, do something with your result array
foreach($results2 as $key => $value) {
//loop through your results an do another query with them. Just like you queried the database to get these results.
}
Trying to change over to PDO, and I am missing something simple?
OLD WAY
$query="SELECT * FROM database"
$result=mysql_query($query);
$data=mysql_result($result, 2, "value");
This gets me a value from row 3, using PDO the only way I can figure is:
$result->setFetchMode(PDO::FETCH_ASSOC)
$row = $result->fetch();
$row = $result->fetch();
$row = $result->fetch();
$thisone = $row['value'];
This way seems silly and indirect, is there a better way to select a row by it's number? I need the whole database queried for other variables, so changing the database SELECT statement won't work.
You can use fetchAll to get an array containing all rows. Then it's just a matter of grabbing the row you're looking for:
$rows = $result->fetchAll();
$third = $rows[2];
$value = $third['value'];
How do I show the results for $wordavg in php. I have done the query in SQL on database after taking out variables so I believe the query is correct but don't know how to show the results of the search in php.
$usertable = 'words';
$yourfield = 'wordname';
$query = "SELECT AVG(CHAR_LENGTH( wordname)) AS $wordavg FROM $usertable WHERE $yourfield LIKE '"."$current_letter"."%' ";
$result = mysql_query($query);
First, you should be using mysqli instead. Back to your question, usually you can iterate over a result with a loop as follows:
while ($row = mysql_fetch_assoc($result)) {
echo $row['field'];
}
More info and examples in the PHP mysql_query doc.
Since you only have one row of data to return, you don't need the loop part. You can simply use
$row = mysql_fetch_assoc($result);
$wordavg = $row['wordavg'];
You shouldn't have the $ in wordavg in your query. It should be just ...AS wordavg FROM...
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'];
}
I have an array of player's IDs. There will generally be about 5 players, not likely to be more then a dozen:
$cplayers= array(1,2,5);
I want to display the players names as a list.
$query = "SELECT username,id FROM users ORDER BY id";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$playercounter =0;
while ( $row = mysql_fetch_array($result) ) {
if ($row['id'] == $cplayers[$playercounter]) {
echo "<li>".$row['username']."</li>";
$playercounter++;
}
}
So I'm pretty sure this isn't the most efficient way I could do this. Would it be better to do individual queries?
Also is there a good way to exit the while loop once $cplayers is done?
just change your query to this:
$query = "SELECT username,id FROM users WHERE id IN (".implode(",",$cplayers).")ORDER BY id";
this will return the correct players you're looking for.
Based on how I'm interpreting this, I'd use the MySQL IN clause, e.g.
$id_list= array(1,2,5);
$sql= 'SELECT username FROM users WHERE id IN('. join(",",$id_list) .') ORDER BY id';
$result= mysql_query($sql) OR die(mysql_error());
while($row= mysql_fetch_assoc($result)) {
echo "<li>{$row['username']}</li>";
}
This targets only those id values in the list, is that what you want?
Well apparently the answer is rather to normalize my database, have a separate (third) table for the join of the two rather than using an array w/in the second table.