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"];
Related
This question already has answers here:
selecting unique values from a column
(9 answers)
Closed 6 months ago.
I have a database with multiple entries. One specific column of entries I am interested in is called sample_group. If there are 10 rows of entries in sample_group, I am trying to create a array of the unique entries using PHP.
For example, the entries would be "food", "food", "water", "food", "swabs", "swabs", "swabs", "food", "water", "water"and after creating an array should be: array("food", "water", "swabs").
Here is my attempted code, it sort of works but the array has an empty entry at the end:
$sql3 = "SELECT * FROM samples_database WHERE order_id=$order_id;";
$result3 = mysqli_query($conn, $sql3);
$group_array = '';
while ($input = mysqli_fetch_array($result3)) {
$group_array .= $input['sample_group'] . ',';
}
$group_array2 = array_filter(array_unique(explode(',', $group_array)));
And then the foreach loop:
foreach ($group_array2 as $group) {
//do something
}
Can anybody please push me in the right direction?
It would be much simpler if you made $group_array an actual array:
$group_array = array();
while ($input = mysqli_fetch_array($result3)) {
$group_array[] = $input['sample_group'];
}
$group_array = array_unique($group_array);
foreach ($group_array as $group) {
//do something
}
I would suggest just doing a SELECT DISTINCT on the MySQL side:
$sql = "SELECT DISTINCT sample_group FROM samples_database WHERE order_id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("i", $order_id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$group_array[] = $row['sample_group'];
}
}
Note: You should ideally use a prepared statement when building your SQL query, and avoid concatenation. I have attempted to provide code which uses a prepared statement.
Also, I replaced your SELECT * (all columns) with just SELECT sample_group. The reason for this is that for one thing, selecting all columns when your script only needs one of them wastes network bandwidth, and might hurt performance. Another reason is that SELECT * makes it ambiguous about which columns your script really needs to use.
This question already has answers here:
Get sum of MySQL column in PHP
(9 answers)
Closed 1 year ago.
I'm trying to get the sum off all the prize money from a column in a MySql table, but I'm not getting a result.
$result = mysqli_query("SELECT SUM(prize_money) FROM cards");
while ($rows = mysqli_fetch_array($result)) {
echo $rows['SUM(prize_money)'];
}
I just want to add all of the numbers in the prize_money column then echo the results.
Thank You
You should apply an alias to the SUM so it is easier to access in the PHP.
You then need to pass the connection string to the mysqli_query function as the first parameter.
So for example if your database connection were:
$con=mysqli_connect("localhost","my_user","my_password","my_db");
then you'd use this code to execute the query and assign the alias:
$result = mysqli_query($con, 'SELECT SUM(prize_money) AS sum_prize_money FROM cards');
$row = mysqli_fetch_assoc($result);
$sum = $row['sum_prize_money'];
echo $sum;
Do you get a result if you do this:
$result = mysqli_query("SELECT SUM(prize_money) FROM cards");
$rows = mysqli_fetch_array($result);
echo $rows
As good practice, you should learn to aliase your sql variables e.g. SUM(prize_money) AS total etc
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.
}
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How do i “echo” a “Resource id #6” from a MySql response in PHP?
I am looking for the result out of a query, but it keeps giving me resource id #3.
The following is my code.
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
print_r($typeResult);
What step am I missing here?
You need to fetch the result. All you're doing is sending the query.
Be aware that if you are writing new code, you should use mysqli_ or PDO functions as your query is vulnerable to SQL injection and mysql_ functions are being deprecated. Hesitantly, below is a sample for mysql_fetch_assoc.
<?php
$sql = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row[sellingid];
}
mysql_free_result($result);
?>
Reference
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
$row = mysql_fetch_array($typeResult);
print_r($row);
More clear hint - use MySQLi class/functions, read this:
http://lt1.php.net/manual/en/mysqli-result.fetch-assoc.php
or if you like OOP approach more then
http://lt1.php.net/manual/en/mysqli-result.fetch-object.php
You are not actually fetching the results of your query. Below are two examples that use WHILE loops to fetch the results as rows. You can then grab the column values and work with them.
Incorrect and depreciated method, but working:
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
// for each row
while ($row = mysql_fetch_array($typeResult)) {
// grab the columns
$value = $row['column_name'];
}
I would recommend using MySQLi or PDO like to following (MySQLi):
$mysqli_connection = new mysqli("hostname", "username", "password", "database");
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$res = $mysqli_connection->query($type);
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
$value = $row['column_name'];
}
$res->free();
$mysqli_connection->close();
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...