Select from database and store in an array - 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

Related

Passing String Array in sql query using PHP

I have two tables is sql 1) friends_details and 2) user_info.
Now using the below query am getting the list of friends of that particular using $number = is coming from app
$sql = "select friends from user_info WHERE user_number ='$number' ";;
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
now $emparray have names of friends in String fromat. Now i want to pass this array into another query so that i can find the details of these friends. And Can't find the way to do. I have tried this code.
$friendsArray2 = "'" .implode("','", $emparray ) . "'";
$query120 = "SELECT * FROM friends_deataisl WHERE name IN ( $friendsArray2 )";
echo $query120;
and the result of echo $query120 is SELECT * FROM friends_deatails WHERE name IN ( 'Array','Array' )
So this means values are not going in the query. Any help would be appreciated.
And i have already checked $emparray is not empty it contains the name that means first query is right but the problem is in second query.
$emparray is a 2-dimensional array, not an array of strings, because $row in the first loop is an associative array.
You need to change the first loop to do:
$emparray[] = $row['friends'];
But you could just combine the two queries into a JOIN:
SELECT DISTINCT fd.*
FROM friend_details AS fd
JOIN user_info AS ui ON fd.name = ui.friends
WHERE ui.user_number = '$number'
Also, the column name friends makes me suspect that this is a comma-separated list of names. Using = or IN won't work with that -- it will try to match the entire list with friend_details.name. It's best to normalize your database so you don't have lists in a column. If you can't fix that, you need to use FIND_IN_SET to join the tables:
SELECT DISTINCT fd.*
FROM friend_details AS fd
JOIN user_info AS ui ON FIND_IN_SET(fd.name, ui.friends)
WHERE ui.user_number = '$number'
And in your original code, you'll need to explode $row['friends']:
$emparray = array_merge($emparray, explode(',', $row['friends']));

How to use two different records from database?

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.
}

display all cells in a mysql column

I need all values from a table column put into an assoc array. I am having trouble finding the answer.
the table is only six rows deep.
example:
|--id--|--name--|--A--|--B--|--C--|
|--01--|--xl33--| 1.30| 2.45| 4.40|
i would like to get an assoc array for column B
name[xl33]=2.45
name[xl34]=....and so on
The trick is that the form will tell the script which column to fetch. A,B,C,D,E,F OR G
I know i could re-format the table and accomplish what i want but I need it structured the way i have it.( i have left out some columns for simplicity)
function return_column($letter){
$result = mysql_query("SELECT name, $letter FROM example") or die(mysql_error());
while($row = mysql_fetch_assoc( $result )) {
$return[$row['name']] = $row[$letter];
}
return $return;
}
$results = return_column('A');
print_r($results);
Something like :
$col = 'B';
$name = array();
$result = mysql_query("SELECT * FROM table") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$name[$row['name']] = $row[$col];
}
This creates an array $name and uses the name column as the key and the $col column for the value ...
You are looking for the mysql_fetch_assoc() function.
Example/
$query = $this->query($YOUR_QUERY);
$returnMap = array();
while ($row = mysql_fetch_assoc($query)) { array_push($returnMap, $row); }
Use mysql_fetch_assoc — Fetch a result row as an associative array.
while ($row = mysql_fetch_assoc($result)) {
$data[$row["column1"]]= $row["column2"];
..............
.........
}

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"];

Create Comma Seperated List from MySQL PHP

I have a list of users in my table. How would I go about taking that list and returning it as one PHP variable with each user name separated by a comma?
You could generate a comma-separated list with a query:
SELECT GROUP_CONCAT(username) FROM MyTable
Or else you could fetch rows and join them in PHP:
$sql = "SELECT username FROM MyTable";
$stmt = $pdo->query($sql);
$users = array();
while ($username = $stmt->fetchColumn()) {
$users[] = $username;
}
$userlist = join(",", $users);
You would fetch the list from the database, store it in an array, then implode it.
The best way I was able to figure this out was by storing the results from each col, or field, and then echoing the implode:
$result = mysqli_query($conn, $sql) //store the result
$cols = array(); //instantiate an array
while($col = mysqli_fetch_array($result)) {
$cols[] = $col['username']; //step through results and save each username in array
}
echo implode(",",$cols); //turn the array into a comma separated string and echo it
This took me a while to figure out exactly how to do this. Hope it helps!

Categories