I wanted to know how I can store an array variable into a select query, and if its okay to have the following inside a while loop. Thanks in advance.
For example:
$roww = array();
while ($roww = $resultt->fetch_assoc()) {
$uery = $dbconn->prepare("SELECT user_ids FROM t_friendship WHERE friend_ids = $roww['id'] AND status = 'Pending'");
$uery->execute();
$uery->store_result();
$rows = $uery->num_rows;}
Use curly braces around the array variable like this {$roww['id']}
Also you could construct a string of ids like ('1','2','3') inside the while loop and in one SELECT outside the while you can use IN of MySQL to select the results.
Another alternatives for curly brackets would be use of double quotes then a concatenate it.
$query = $dbconn->prepare("SELECT user_ids FROM t_friendship WHERE friend_ids = ".$roww['id']." AND status = 'Pending'");
// Now mysql result set is stored in php variable.
$result = mysql_query($querystring, $dbconn)
$array = array();
while($row = mysql_fetch_object($result))
{
$array[] = $row;
}
Use within single quotes
$uery = $dbconn->prepare("SELECT user_ids FROM t_friendship WHERE friend_ids = '".$roww['id']."' AND status = 'Pending'");
$uery->execute();
first check out id value just echo $roww['id']. If you getting that value means use above the code
Related
I have an array of tag names which I passed via POST Method and I these tag names has its corresponding tag_id in the database. All I want is to search the id while iterating the array of tag names and I want the result of each query to be stored in an empty array. I think I just misunderstood something or what.
$tags_array = ['shoes','gadgets','fashion','food'];
$tags_array_id = [];
$tags_sql = '';
foreach ($tags_array as &$tag) {
$sql = "SELECT tag_id FROM `tbltag` WHERE tag_name = ".$tag." group by tag_name";
$query = mysqli_query($conn, $sql);
$result = mysqli_fetch_row($query);
$tags_array_id[] = $result[0];
};
Please help guys, suggestions highly appreciated.
Basically something like:
$sql = "SELECT * FROM `tbltag` WHERE tag_name IN('".implode("','", $tags_array)."')";
One last comment: You probably want to search for tag_id's instead of tag names, as you'll probably have those in your input ($_POST/$_GET). And as FuzzyTree has mentioned above, you'll want some type of ID validation and some kind of escaping of data going into the query to avoid SQL injection.
Use this instead
$tags_array = ['shoes','gadgets','fashion','food'];
$tags = implode("','", $tags_array);
$tags = "'".$tags."'";
$sql = "SELECT tag_id FROM tbltag WHERE tag_name IN ({$tags})";
Question: Do you need the & in your foreach loop? You are not directly modifying the tags_array just using the information?
Trying adding the number to the array e.g add $x so you are adding in 1 record into 1 part of the array as you loop though.
$tags_array = ['shoes','gadgets','fashion','food'];
$tags_array_id = [];
$tags_sql = '';
$x = 0;
foreach ($tags_array as &$tag) {
$sql = "SELECT tag_id FROM `tbltag` WHERE tag_name = ".$tag." group by tag_name";
$query = mysqli_query($conn, $sql);
$result = mysqli_fetch_row($query);
$tags_array_id[$x] = $result[0];
$x++;
};
Ok thanks to all of u guys for your answers.
I've made some changing but i still can't display my array ...
Look at what i've done :
$prog = array();
$i=0;
while($row = $get_programmation->fetch_assoc()){
$prog[$i] = $row;
$i++;
}
echo json_encode($prog);
I would have this a result like this : {"id":"0","artist":"xxxx", .... etc} and then use it in my iOS app to display what i want.
mysql_query("SELECT * FROM `programmation`");
Backticks instead of single quotes
Also in here $articles[] = $row;
in $row variable you have to specify MySQL table column names which you have to insert into array, for instance $row['id'], etc...
NOTE: See mysql_ deprecated post too
you can not use quotes in table name or field name but you can use backtick()
$get_programmation = mysql_query("SELECT * FROM 'programmation'");
should be:
$get_programmation = mysql_query("SELECT * FROM `programmation`");
or
$get_programmation = mysql_query("SELECT * FROM programmation");
Replace this $get_programmation = mysql_query("SELECT * FROM 'programmation'");
with this $get_programmation = mysql_query("SELECT * FROM programmation");
Then importantly change code in while loop as below
while($row = mysql_fetch_assoc($get_programmation)){
array_push($articles, $row['yourcol1'],$row['yourcol2']);
}
echo json_encode($articles);
$row is not actual array. You can get the value if it using your actual column name only. And here I have pushed it to the array in while loop to form as array.(Here I have mentioned only two column, You can take all your columns in such way.)
Input :
$sql1 = "SELECT COUNT(*) FROM matchTrip where userTripId = :tripId";
$stmt1 = $this->db->prepare($sql1);
$stmt1->bindParam(':tripId', $trip, PDO::PARAM_INT);
$temp = $stmt1->fetchObject();
echo(json_encode($temp));
Output:
How to take value from array :
of which json_encode looks like this: {"COUNT(*)":"7"}
Any help will be appreciated.
Why don't you just give the column an alias in the SQL itself?
$sql1 = "SELECT COUNT(*) as myCount FROM matchTrip where userTripId = :tripId";
Makes the rest easier to work with.
Do you mean json_decode? You can just put it between quotes and it should work; $array["COUNT(*)"].
But you can also add "AS myCount" to your SQL.
if to get rid of all the useless stuff from your code
$sql = "SELECT COUNT(*) FROM matchTrip where userTripId = ?";
$stmt = $this->db->prepare($sql);
$stmt->execute(array($table_of_user[$i]));
$count = $stmt->fetchColumn();
echo $count;
So why not just fecth as array?
$temp = $stmt1->fetch(PDO::FETCH_ASSOC);
echo $temp['COUNT(*)'];
Just use like this:
$json = json_encode($temp);
echo $json->{'COUNT(*)'}; // 7
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"];
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!