I'm trying to retrieve multiple rows from joining two tables where store.itemid = item_list.id.
$query = "SELECT s.price, il.*
FROM store s LEFT JOIN item_list il ON s.itemid = il.id";
I then have:
if($result = $conn->($query)) {
$array = $result->fetch_array(MYSQLI_ASSOC);
}
With my current code, the query is only retrieving the first row from the 'store' table. I have made certain that there should definitely be more than one row to return.
print_r($array) shows:
Array ( [price] => 400 [id] => 5 [name] => Computer )
That's because you are only running fetch_array() once. You probably need to run it in a loop, e.g.:
if ($result = $conn->query($query)) {
while ($array = $result->fetch_array(MYSQLI_ASSOC)) {
// do something with $array
}
}
instead of this:
$array = $result->fetch_array(MYSQLI_ASSOC);
use this:
while($row = $result->fetch_array(MYSQLI_ASSOC)){
//put your code here!
}
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 want to convert my query result to two dimensional array the query is
SELECT c.name,c.mobile_number,t.service_time
FROM CUSTOMER AS c
JOIN TRANSACTION AS t ON c.id = t.customer_id
WHERE t.service_date = '$date'
AND employee_id = '$employee_id
I get name(varchar),mobile num(int) and time which is time format. I wrote some code but it is not working:
$results = array();
echo $num_fields=mysqli_num_fields($array1);
echo $num_rows=mysqli_num_rows($array1);
while($line = mysqli_fetch_array($array1))
{
for($i=0;$i<$num_rows;$i++)
{
for($j=0;$j<$num_fields;$j++)
{
$results[$i][$j]=$line[$i][$j];
}
}
}
The result I am getting is:
[["k ","a ","r "],["9 ","8 ","7 "],["0 ","2 ",": "]]
The output contains only first characters that to one. I want each row of two dimensional array to have row of my query result.
You can just add the result to a new array and change mysqli_fetch_array to mysqli_fetch_row:
$results = array();
while ($line = mysqli_fetch_row($array1))
{
$results[] = $line;
}
Alternatively you can use mysqli_fetch_assoc() to make for an associative array (e.g. $results[0]['name'] will be the name column of the first row).
Edit
If there are duplicate column names you can use aliases:
SELECT one.name AS one_name, two.name AS two_name FROM one INNER JOIN two USING ...
The associative array will then have $result[0]['one_name'] and $result[0]['two_name'].
try this:
while($line = mysqli_fetch_row($array1))
{
array_push($result, $line);
}
This should do it
$con = mysqli_connect("localhost","my_user","my_password","my_db");
$result = mysqli_query($con, "SELECT * FROM .....");
$rows = array();
if($result){
while($row = mysqli_fetch_assoc($con, $result)){
array_push($rows, $row);
}
mysqli_free_result($result);
}
var_dump($rows);
This is my database:
This is the query:
SELECT * FROM users
Now when I do this:
$query = $connection->query($_GET['query']); // SELECT * FROM users
print_r($query->fetch_assoc());
I get this as output:
Array (
[id] => 3
[username] => karel )
Why does it not output id 4 and username ccscs?
When I a while loop:
while($row = $query->fetch_assoc()){
print_r($row);
}
This is happening because you don't give any order to your query so it automatically get first record. If you want to return last record you can order by id desc as follow
SELECT * FROM users ORDER BY id DESC
If you instead need to retrieve all records you will need to loop throw your records
while($row = $query->fetch_assoc())
{
print_r($row);
}
Based on new op info i would not fetch twice but one as follow
$fields = array();
while($row = $query->fetch_assoc())
{
print_r($row);
$fields[] = $row;
}
fetch_assoc() retrieves a single row from a result set. See here.
mysqli_result::fetch_assoc -- mysqli_fetch_assoc — Fetch a result row
as an associative array
You should use something like this :
while($row = $query->fetch_assoc()){
print_r($row);
}
That's because fetch_assoc() just fetches one row.
To get each row you can do it like this:
while($row = $query->fetch_assoc()){
print_r($row);
}
I am trying to display only user selected pages in dashboard
I have two columns in database like this
create table users(userid varchar(50), scripts varchar(100))
in userid column i will have the logged in user name and in scripts column, names of the pages which they want to display it in dashboard in comma separated format. ex: total, cust_orders,...
I want to fetch page name from scripts column separately like total.php, cust_orders.php...
i tried doing like this
$sql = "select scripts from users where userid = '".$_SESSION['UserID']."' ";
$result = DB_query($sql,$db);
$myrow = DB_fetch_array($result);
foreach ($myrow as $res)
{
$array123[] = $res;
$var123 = $array123[0];
$var222 = $array123[1];
}
but it wont work as the pages can be from 1 to 8, can somebody please help me in this?
EDITED
I have done like this
$result = DB_query($sql,$db);
$myrow = DB_fetch_array($result);
$arr= $myrow['scripts'];
$arr1 = explode(',', $myrow['scripts']);
print_r ($arr1);
and it worked, it displays like this
Array ( [0] => total_dashboard [1] => customer_orders [2] => unpaid_invoice [3] => lat
but dynamically how can i separate it and i have to add .php to this ...
$sql = "select scripts from users where userid = '".$_SESSION['UserID']."' ";
$result = mysql_query($sql,$db);
while($myrow = mysql_fetch_array($result))
{
$arr=explode(',',$myrow["scripts"]);//this will strip the , separated values in an array
//now you can fetch the scripts from database
}
You can use PHP - explode like:
while ($myrow = mysql_fetch_object($result))
{
// $myrow->scripts = "text1.php,text2.php,text3.php";
$scripts = explode(',', $myrow->scripts);
}
So $scripts will then contain each PHP-Page/Skript as own position in the array.
$scripts[0] = "text1.php";
$scripts[1] = "text2.php";
$scripts[2] = "text3.php";
I want to select some data from db and store in an array. Suppose I have a column "keyword" in my db table. I want to select all rows where keyword column is like "nature".
I am trying following code:
<?
$term= "nature";
$arr = array();
$sql = "select keyword from keywords where keyword LIKE '%$term%'";
$result = mysql_query($sql) or die(mysql_error());
$rows = mysql_fetch_array($result);
foreach ($rows as $row){
array_push($arr, $row['keyword']);
}
print_r($arr); //output: Array ( [0] => n [1] => n )
?>
So the result from db should return only one keyword 'nature' which i need to store in array.
Why it is storing same string two times? There is no any other row in db similar to the term nature.
Why it is storing only first letter in the array? Shouln't it store "nature" instead of "n"?
Please help me fixing this.
Should be something like
$term = "nature";
$arr = array();
$sql = "select keyword from keywords where keyword LIKE '%$term%'";
$result = mysql_query($sql) or die(mysql_error());
while( $row = mysql_fetch_assoc( $result ) ) {
arr[] = $row[ 'keyword' ];
}
In your solution you only fetch the first record from the result-set as numeric indexed array.
Btw - you are aware that a LIKE-query starting with a wildcard cannot make use of any index?
use mysql_fetch_assoc instead of mysql_fetch_array