I have the following code
<?php
require_once('db_connection.php');
$return_arr = array();
$param = $_GET["term"];
$query = "SELECT *
FROM exp_weblog_data,exp_weblog_titles WHERE field_id_5
LIKE '%". $param ."%'
LIMIT 50";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch_assoc()) {
$row_array['jItemCode'] = $row['field_id_5'];
$row_array['jItemDesc'] = $row['title'];
/* $row_array['jItemWholesale'] = $row['itemWholesale'];
$row_array['jItemRetail'] = $row['itemRetail'];
$row_array['jItemPrice'] = $row['itemPrice'];
$row_array['jQtyOnHand'] = $row['qtyOnHand'];*/
array_push( $return_arr, $row_array );
}
$result->free_result();
$mysqli->close();
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
I have two tables. "exp_weblog_data" and "exp_weblog_titles". Each table has "entry_id". When I use "field_id_5" from "exp_weblog_data" to start the autosuggest I need to pull additional information from the "exp_weblog_titles" table
This is for an auto complete query. I need to pull related data from "title" in another table in the same database can someone please help I know the problem lies with my query but I have tried all kinds of syntax with JOINS and UNIONS and LEFT JOINS what have you. Can someone please help me
I got it to work this way
$query = "SELECT field_id_5, exp_weblog_titles.title, field_id_57
FROM exp_weblog_data, exp_weblog_titles
WHERE exp_weblog_titles.entry_id = exp_weblog_data.entry_id AND field_id_5
LIKE '%". $param ."%'
LIMIT 10";
Thanks for all the help guys!
Use a JOIN clause. You can with one request get related data from 2 or more tables.
http://dev.mysql.com/doc/refman/5.0/en/join.html
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.
}
I'm using my mysqli query as JSON output.
This is my query:
$sql = "SELECT p.*,comments.*,COUNT(comments.id) AS numComments FROM people AS p
LEFT JOIN comments ON comments.people_id = p.id
WHERE p.name LIKE '%".$data."%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$myArray[] = $row;
}
echo json_encode($myArray);
} else {
echo 0;
}
What I want to do, is to group all the person comments and place it under the person data. for example:
The desired output is that I will be able to access the comments not directly from the query, but from the person itself.
for example:
echo $person['comment'][0]['content']
Currently, I access it like any of the query data..
echo $person['content']
JSON OUTPUT:
As you can see, the person data and the comment data is mixed in the same array. I want the comments to have an array of their own.
Any ideas?
Edit: Seem like I have problem with the query. it returns only the first comment!
You need so-called eager loading for this task. It will involve two queries, but it will be way better than one.
You have to select your people first, then get people ids and query comments table for the comments. And finally you will have to combine the two arrays together.
I will use PDO as it will take 5 times less code to write, thanks to some neat PDO features.
$stmt = $conn->prepare("SELECT * FROM people WHERE name LIKE ?");
$stmt->execute(["%$data%"]);
$people = $stmt->fetchAll(PDO::FETCH_UNIQUE);
$ids = array_keys($people);
$in = str_repeat('?,', count($ids) - 1) . '?';
$stmt = $db->prepare("SELECT people_id, * FROM comments WHERE people_id IN ($in)");
$stmt->execute($ids);
$comments = $stmt->fetchAll(PDO::FETCH_GROUP);
foreach($people as $id=>$row)
{
$row['comments'] = $comments[$id];
$people[$id] = $row;
}
I have a small issue that I can't figure out.
I have to pull data from two different tables, in one loop. I've never done that before, so I have no idea how. I tried two different queries. That looked like this:
$query = "SELECT * FROM colors ";
$color_select = mysqli_query($connection, $query);
$second_query = "SELECT * FROM votes";
$vote_select = mysqli_query($connection, $second_query);
And then put them into a loop:
while($row = mysqli_fetch_assoc($color_select) && $second_row = mysqli_fetch_assoc($vote_select))
{
$color = $row['Colors'];
$votes = $second_row['Votes'];
echo "<tr><td>$color</td><td>$votes</td></tr>";
}
But that didn't work. I didn't expect it to, just wanted to try. :) Maybe someone experienced can help me out. Thanks.
At the end of the day I need a table displayed, that has two columns, one of them contains the color name from one DB table and the other one contains a number of votes.
As requested: table structures.
Table: colors has only one field Colors.
Table: votes has four fields city_id, City, Colors and Votes
*************************EDIT**************************************
So fixed up the query as suggested, but is still shows nothing.
Here is the edited code:
$query = "SELECT * FROM colors,votes WHERE colors.Colors=votes.Colors";
$color_votes_select = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($color_votes_select))
{ $color = $row['Colors'];
$votes = $row['Votes']; }
if table having relation.
try this in single query .
SELECT
`colors`.*,votes.*
FROM
`colors`
INNER JOIN
`votes` ON
`votes`.colorId = `colors`.Id
Most imp *****You should have some relationship between tables
Otherwise workaround
Run query on color, Save it in ArrayA
Run query on vote, Save it in ArrayB
Create New Array ArrayC
$arrayC = array();
Loop array A or C if they both contact same row count
array_push($ArrayC, key and value of color, key and value of votes);
Final loop ArrayC to print tr and td
First Relate These two tables, write color_id in votes table.
$query = "SELECT * FROM colors,votes where colors.id=votes.color_id";
$color_select = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($color_select))
{
$color = $row['Colors'];
$votes = $row['Votes'];
}
Try this:
$query = "SELECT colors FROM colors";
$color_select = mysqli_query($connection, $query) or die (mysqli_error());
$second_query = "SELECT votes FROM votes"; //you only need column votes right?
$vote_select = mysqli_query($connection, $second_query) or die (mysqli_error());;
while( $row = mysqli_fetch_assoc($color_select) && $second_row = mysqli_fetch_assoc($vote_select)){
$color[] = $row['colors'];
$votes[] = $second_row['votes'];
echo "<tr><td>$color</td><td>$votes</td></tr>";
}
Short explanation:
It will fetch the select and store into an array (because what you were doing is selecting multiple rows into one single variable) and then just display with the echo.
$sql = "SELECT * FROM
fbr.*, c.sample, ci.dob, ci.country, ci.sex
FROM `finalBloodReport` fbr ,`clients` c, `client_info` ci
WHERE fbr.sampleSerialNo = (CONCAT(c.resellerSerialId,'-',c.kitSerialNo) )
AND c.client_id = ci.id";
This is my query it works fine and gives the desired output,But since i am showing data in table i also want to get columns name only for this query to show them as table header .
I tried Something like this , but result is null.
$sql = "SHOW COLUMNS
fbr.*, c.sample, ci.dob, ci.country, ci.sex
FROM `finalBloodReport` fbr ,`clients` c, `client_info` ci
WHERE fbr.sampleSerialNo = (CONCAT(c.resellerSerialId,'-',c.kitSerialNo) )
AND c.client_id = ci.id";
Can anyone help ? I am not so good with mysql ; (
You need to retrieve column information after query is executed. This can be done by using mysqli_fetch_field()
You code should look like following
$result = mysqli_query($sql);
while($field = mysqli_fetch_field($result)) {
print $field->name . "\t";
}
while ($row = mysqli_fetch_row($result) {
print_r($row);
}
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"];