I'm trying to return a comma separated list of location names from a database.
So far I have the SQL statement that I know works because it returns the correct results when tested in phpMyAdmin.
I'm now trying to get the results returned and printed on screen in php.
The code I have bellow only seems to return the first result.
$sql = "SELECT user_locations.location_id, location.name AS LocName FROM user_locations INNER JOIN location ON user_locations.location_id=location.id WHERE user_id = '" . $id . "'";
$query = mysqli_query($conn, $sql);
while ($row = $query->fetch_assoc()) {
$array[] = $row['LocName'];
$comma_separated = implode(",", $array);
return $comma_separated;
}
You need to remove the implode and return outside your while loop, otherwise your loop will stop after the first value:
$sql = "SELECT user_locations.location_id, location.name AS LocName
FROM user_locations
INNER JOIN location ON user_locations.location_id=location.id
WHERE user_id = '" . $id . "'";
$query = mysqli_query($conn, $sql);
while ($row = $query->fetch_assoc()) {
$array[] = $row['LocName'];
}
$comma_separated = implode(",", $array);
return $comma_separated;
Note that you can achieve this result directly in your query using GROUP_CONCAT:
$sql = "SELECT GROUP_CONCAT(location.name) AS LocName
FROM user_locations
INNER JOIN location ON user_locations.location_id=location.id
WHERE user_id = '" . $id . "'";
$query = mysqli_query($conn, $sql);
$row = $query->fetch_assoc();
$comma_separated = $row['LocName'];
return $comma_separated;
Note that dependent on the source of your $id value, you may need to look into prepared statements to protect yourself from SQL injection.
Related
I am trying to fetch first id from one table and later after all the ids are fetched i am trying to fetch number of all that id's.
My Problem is
As i want to select the value of first query completion result
I am unable to trigger second query after the first query is completed both are triggerid at a time
First Query
$query ="SELECT * FROM abc WHERE xyz='xyz' And Standard='xyz' ";
$data=mysqli_query($mysqli,$query)or die(mysqli_error());
$ID = array();
while($row=mysqli_fetch_array($data)){
$ID[] = $row['ID'];
}
$IDall = "'" . implode("','", $ID) . "'";
Second Query
$query="SELECT mobno FROM euser WHERE UserId IN ($IDall)" ;
$data=mysqli_query($mysqli,$query)or die(mysqli_error());
$mobiles = array();
while($row=mysqli_fetch_array($data)){
$mobiles[] = $row['MobileNum'];
}
$mobilesStr = implode(',', $mobiles);
echo $mobilesStr;
}
Try this
SELECT mobno FROM euser WHERE UserId IN (SELECT ID FROM abc WHERE xyz='xyz' And Standard='xyz');
You don't need 2 queries. Only 1 is enough
SELECT mobno FROM euser WHERE UserId IN (
SELECT ID FROM abc ...
)
Try this
$query ="SELECT * FROM abc WHERE xyz='xyz' And Standard='xyz' ";
$data=mysqli_query($mysqli,$query)or die(mysqli_error());
if(mysqli_num_rows($data) > 0) {
$ID = array();
while($row=mysqli_fetch_array($data)){
$ID[] = $row['ID'];
}
$IDall = "'" . implode("','", $ID) . "'";
$query2="SELECT mobno FROM euser WHERE UserId IN ($IDall)" ;
$data2=mysqli_query($mysqli,$query2)or die(mysqli_error());
$mobiles = array();
while($row=mysqli_fetch_array($data2)){
$mobiles[] = $row['MobileNum'];
}
$mobilesStr = implode(',', $mobiles);
echo $mobilesStr;
}
In this the second query will execute when the first query has a result.
So I have the following code:
require_once('db.php');
$getUsers = mysqli_query($db, 'SELECT * FROM users');
$rows = [];
while ($r = mysqli_fetch_assoc($getUsers)) {
$rows[] = $r;
$getSkills = mysqli_query($db, "SELECT * FROM skills WHERE id = '" . $r['id'] . "'");
while($r = mysqli_fetch_assoc($getSkills)) {
$rows['skills'] = $r;
}
}
print(json_encode($rows));
Which outputs:
[{"id":"1","name":"user1","skills":{"woodcutting":"6","mining":"10"}},{"id":"2","name":user2"}]
There are two problems:
I'd like to get all of the data in the table skills EXCEPT for the id, or at-least cut it off before encoding it with json.
For some reason I can't get the "skills" shown after the first user. user2 should also have a skills object.
What am I doing wrong?
To get all the columns except the id from table skills, you can either list all the columns that you want to select, like this:
mysqli_query($db, "SELECT column1, column2, another_column FROM `skills` WHERE id = '" . $r['id'] . "'");
Or, you can SELECT everything and use unset() to weed out the id column before json-encoding:
$getSkills = mysqli_query($db, "SELECT * FROM skills WHERE id = '" . $r['id'] . "'");
while ($r = mysqli_fetch_assoc($getSkills))
{
unset($r['id']);
// whatever it is that you want to do.
}
The skills are not shown except for the last user (?) because you are re-assigning it in every iteration of the while loop. Here is something you can do instead:
require_once('db.php');
$getUsers = mysqli_query($db, 'SELECT * FROM users');
$rows = array();
while ($r = mysqli_fetch_assoc($getUsers))
{
$skills = array();
$tempRow = $r;
$getSkills = mysqli_query($db, "SELECT * FROM skills WHERE id = '" . $r['id'] . "'");
while ($r = mysqli_fetch_assoc($getSkills))
{
unset($r['id']); // since you don't want the `id`.
$skills[] = $r;
}
$tempRow['skills'] = $skills;
$rows[] = $tempRow;
}
print(json_encode($rows));
Hope that helps :)
It looks like you need something similar to this:
while($r = mysqli_fetch_assoc($getSkills)) {
unset($r['id']);
$rows['skills'] = $r;
}
Point-1: Unset id like unset($r['id']) to remove from array() $r. Before unsset id keep id to a variable because you used it for next query.
Point-2: May be there is no data exist in skills those IDs. As a result you did not get skills. Suggest you to query by those IDs whether any data exist or not in skills table.
while ($r = mysqli_fetch_assoc($getUsers)) {
$id = $r['id'];
unset($r['id']);
$rows[] = $r;
$getSkills = mysqli_query($db, "SELECT * FROM skills WHERE id = '$id'");
while($r = mysqli_fetch_assoc($getSkills)) {
$rows['skills'] = $r;
}
}
Edit: I forgot to add the explode part that I'm having the issues with. I need the query result exploded.
I have been messing with this for a while and have a workable procedure in mysql, however I want to accomplish this as part of a larger script. I have a table filled with IDs and several columns of data with "|" separated values. How can I use or edit the below PHP to query and insert normalized results into a new table?
If I run this with an actual string: "40|180|408|360|40|166|80|59"; It will insert values (not the ID, which I also need) but when I try to pass in query results, I get "Array to string conversion" errors. Any guidance would be appreciated.
$query = "Select id, imageSize from T1";
$result = mysqli_query($conn, $query);
$myArray = explode('|', $result);
foreach($myArray as $value) {
$sql = "INSERT INTO testExplode VALUES ($value)";
$result = mysqli_query($conn, $sql);
}
If you want to insert all of your results then:
$query = "Select id, imageSize from T1";
$myArray = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($myArray)) {
$sql = "INSERT INTO testExplode VALUES (" . mysqli_real_escape_string($conn, $row['imageSize']) . ")";
mysqli_query($conn, $sql);
}
//If just only one:
$query = "Select id, imageSize from T1";
$myArray = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($myArray);
$sql = "INSERT INTO testExplode VALUES (" . mysqli_real_escape_string($conn, $row['imageSize']) . ")";
mysqli_query($conn, $sql);
NOTE:
Avoid sql injecions by escaping your variables in your querys.
EDIT:
Based on the OP comment.
$query = "Select id, imageSize from T1";
$myArray = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($myArray)) {
$values = explode('|', $row['imageSize']);
foreach ($values as $value) {
$sql = "INSERT INTO testExplode VALUES (" . mysqli_real_escape_string($conn, $value) . ")";
mysqli_query($conn, $sql);
}
}
$sql = "select id from table_name ";
$result = mysql_query($sql);
$data = array();
while($row = mysql_fetch_assoc($result))
{
$data[] = $row[id];
}
/* $data contains id's fetched from sql query from db.now i want to pass this id's(array of values) in $data array one by one to below select query in where condition and obtain desired result for each id.My question is how to pass an array of values to the below select statement I dont know how to do this.Any help is greatly appreciated.*/
$query = "select * from table where id1 = $data[] ";
$query = "select * from table where `id1` in (" . implode(', ', $data) . ")";
You should use the cross database function in Moodle called get_in_or_equal()
list($where, $params) = $DB->get_in_or_equal($data, SQL_PARAMS_NAMED);
$sql = "SELECT *
FROM {table}
WHERE $id {$where}"
$records = $DB->get_records_sql($sql, $params);
You can use the IN clause.
When you are totally sure you only have numeric values in your $data array. You can do the following:
$query = "select * from table where id1 IN(" . implode(',', $data) . ")";
You can use this:
$comma_separated = implode(",", $data);
if ($comma_separated != "")
$query = "select * from table where id1 IN($comma_separated)";
I am trying to store a mysql value into a php variable. I have the following query which I know works. However, I the value for $count is always 0. Can someone explain what I need to do to get the count value? The count should be the count of x's w here name_x=.$id.
$query = "SELECT COUNT(name_x) FROM Status where name_x=.$id.";
$result = mysql_query($query);
$count = $result;
Is first letter in table name is really capital. Please check it first.
or Try :
$query = "SELECT COUNT(*) as totalno FROM Status where name_x=".$id;
$result = mysql_query($query);
while($data=mysql_fetch_array($result)){
$count = $data['totalno'];
}
echo $count;
$query = "SELECT COUNT(*) FROM `Status` where `name_x`= $id";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
$count = $row[0];
please try it
$query = "SELECT COUNT(*) FROM Status where name_x=$id";
$result = mysql_query($query);
$count = mysql_result($result, 0);
You are missing single quotes around $id. Should be
name_x = '" . $id . "'";