Get all the values from single column in MySQL PDO [duplicate] - php

This question already has answers here:
PDO fetch one column from table into 1-dimensional array
(2 answers)
Closed 5 years ago.
I have value in user_id column (1,47,6). How to get all the values?
I have used following code.
$array_data = array($project_id);
$query = "SELECT * FROM p
INNER JOIN pl ON p.pl_id = pl.pl_id
INNER JOIN user ON p.user_id = user.user_id WHERE
p.p_id=?";
$stmt = $conn->prepare($query);
$stmt->execute($array_data);
$result_data = $stmt->fetchAll( PDO::FETCH_ASSOC );
$ids = array();
foreach($result_data as $rows) {
$ids[] = $rows['user_id'];
}
$id = implode(',',$ids);
echo $id;
This $id returns only the first value (1). I need all 3 values. Please help & thanks in advance.

Declare the $ids array before the loop and echo the imploded content after the array
$array_data = array($project_id);
$query = "select `user_id` from p
inner join pl on p.pl_id = pl.pl_id
inner join user on p.user_id = user.user_id where
p.p_id=?";
$stmt = $conn->prepare($query);
$stmt->execute($array_data);
$result_data = $stmt->fetchAll( PDO::FETCH_ASSOC );
$ids = array(); /* declare variable before loop */
foreach($result_data as $rows) {
$ids[] = $rows['user_id'];
}
$id = implode(',',$ids); /* output after loop */

Related

Mysql/PHP Json nested array

I got issue with nested array which seems are not Json object for some reason. When i try for e.g access jsonData["user"] it works, but when i try go deeper such as jsonData["user"]["photo_url"] then it's treated like a string and i cant access the value.
Current code:
<?php
require_once("db_connection.php");
$userId = $_GET["user_id"];
$query = "WITH user AS (SELECT id, JSON_OBJECT('display_name', u.display_name, 'photo_url', u.photo_url) AS user FROM users u WHERE id = :userId), info AS (SELECT id, JSON_ARRAYAGG(JSON_OBJECT('text', text, 'start_at', start_at, 'end_at', end_at, 'status', status)) AS information FROM report GROUP BY id), img AS (SELECT report_id, JSON_ARRAYAGG(JSON_OBJECT('name', name)) AS images FROM report_images GROUP BY report_id), cmt AS (SELECT report_id, COUNT(*) AS totalcomments FROM report_comments rc JOIN users u ON rc.user_id = u.id GROUP BY report_id) SELECT u.user, info.information, img.images, cmt.totalcomments FROM report r JOIN user u ON u.id = r.user_id LEFT JOIN info ON info.id = r.id LEFT JOIN img ON img.report_id = r.id LEFT JOIN cmt ON cmt.report_id = r.id";
$stmt = $db->prepare($query);
// Bind our variables.
$stmt->bindValue(":userId", $userId);
// Execute.
$stmt->execute();
$result = $stmt->fetchAll();
if (count($result) > 0) {
$toJson = json_encode($result);
echo $toJson;
} else {
$toJson = json_encode("Error");
echo $toJson;
}
?>
Old code which worked:
<?php
require_once("db_connection.php");
require_once("functions.php");
$userId = $_GET["user_id"];
$query = "SELECT * FROM report WHERE `user_id` = :userId";
$stmt = $db->prepare($query);
// Bind our variables.
$stmt->bindValue(":userId", $userId);
// Execute.
$stmt->execute();
$result = $stmt->fetchAll();
if (count($result) > 0) {
foreach ($result as $key => $value) {
$result[$key]["user"] = getUserById($db, $value["user_id"]);
}
$toJson = json_encode($result);
echo $toJson;
} else {
$toJson = json_encode("Error");
echo $toJson;
}
?>
Because you are aggregating some of the values as JSON in your query, you need to decode those first before attempting to use the values and then JSON encode the whole result set. You need to do that as you fetch the data, so replace:
$result = $stmt->fetchAll();
with:
$result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row['user'] = json_decode($row['user']);
$row['images'] = json_decode($row['images']);
$row['comments'] = json_decode($row['comments']);
$result[] = $row;
}

Merge 3 sql selects into one. return assosiative array in PHP

Currently I make 3 sql select queries to 3 different tables. Is it possible to merge into just one?
SELECT * FROM recomendados INNER JOIN carpas ON recomendados.fk_id = carpas.id
SELECT * FROM recomendados INNER JOIN sacos ON recomendados.fk_id = sacos.id
SELECT * FROM recomendados INNER JOIN colchon ON recomendados.fk_id = colchon.id
The php code to make the queries is like:
$sql = "SELECT * FROM recomendados INNER JOIN carpas ON recomendados.fk_id = carpas.id";
$result = $conexion->query($sql);
$row = $result->fetch_all(MYSQLI_ASSOC);
if ($result->num_rows > 0) {
return $row;
}
If possible I would like an assosiative array with the table name as the key.
Use this code::
$tables = ['carpas': [], 'sacos': [], ...];
foreach ($table in $tables) {
$result = $conn->query("SELECT ... INNER JOIN ${table} ON recommendados.id = ${table}.ud");
$rows = $result->fetch_all(...);
$tables[$table] = $rows;
}
print($tables["carpas"]); // dataset from *carpas*
// etc

Return JSON with id in front

How do I pull out the id in front of each JSON return object from my API?
Current:
{
"1516":{
"id":"1516",
"firstname":"Aluno",
"lastname":"Teste",
"email":"teste#gmail.com",
"dlastaccess":"28-10-2016",
"coursename":"Curso Demonstra\u00e7\u00e3o"
}
}
How do I want to leave:
[
{
"id":"1516",
"firstname":"Aluno",
"lastname":"Teste",
"email":"teste#gmail.com",
"dlastaccess":"28-10-2016",
"coursename":"Curso Demonstra\u00e7\u00e3o"
}
]
I'm trying to do this because my checklist-model does not work the way the JSON return comes, so I can not check all the checkboxes.
API:
This does the job:
$json = '{"1516":{"id":"1516","firstname":"Aluno","lastname":"Teste","email":"teste#gmail.com","dlastaccess":"28-10-2016","coursename":"Curso Demonstra\u00e7\u00e3o"}}';
$values = json_decode($json, true);
$values = array_values($values);
echo json_encode($values);
returns:
[{"id":"1516","firstname":"Aluno","lastname":"Teste","email":"teste#gmail.com","dlastaccess":"28-10-2016","coursename":"Curso Demonstra\u00e7\u00e3o"}]
I guess your $result is an array (or object) of this type:
$result[id] = array(sql retrieved);
Because sql returns you a list of results, even if the result is unique. Imagine that your query returned two results, how could you separate them?
Try:
echo json_encode($result[$cursoid])
or
echo json_encode($result->$cursoid)
$cursoid = $_GET['idcurso'];
$sql = 'SELECT
user2.id AS ID,
user2.firstname AS Firstname,
user2.lastname AS Lastname,
user2.email AS Email,
IF (user2.lastaccess = 0,"nunca",
DATE_FORMAT(FROM_UNIXTIME(user2.1astaccess),"%d-96m-W")) AS dLastAccess ,c.fullname AS Coursename
FROM mdl_user_enrolments AS ue
JOIN mdl_enrol AS e ON e.id = ue.enrolid
JOIN mdl_course AS c ON c.id = e.courseid
JOIN mdl_user AS user2 ON user2 .id = ue.userid
WHERE (SELECT timeaccess FROM mdl_user_lastaccess WHERE userid=user2.id AND courseid=c.id) IS NULL and c.id = ?';
$params = array($cursoid);
$result = $DB->get_records_sql($sql, $params);
echo json_encode(array_values($result)); // You can easily access array values without their keys by array_values(array $param) function
Use array_values, default php function
$values = $DB->get_records_sql( $sql, $params );
$result = array_values( $values );
return json_encode($result);

Need help in mysql RIGHT join

here is mytable structure?
table:category
id name
1 x
2 y
table:subproduct
id cat_id name myval
1 1 xyz test
2 1 abc test2
So basically i want to select all values from subproduct for each id of category table and show it in array in php?
here is my PHP code
$sqlnew = "SELECT c.cat_id,c.cat_title,s.sub_id,s.sub_title,s.store_cashback FROM category c JOIN subproduct s ON c.cat_id = s.pid";
$pdo = getDB();
$stmtnew = $pdo->query($sqlnew);
$resultnew = $stmtnew->fetchAll();
var_dump($resultnew);
I am using PHP PDO.
If you want to get all items with a particular category ID, you should do something like this:
$statement = $pdo->prepare("SELECT * FROM subproduct INNER JOIN category " .
"ON category.id = subproduct.cat_id WHERE category.id = :id");
$statement->bindValue(":id", $category_id, PDO::PARAM_INT);
$statement->execute();
$data = $statement->fetchAll();
You could use this to individually fetch each category ID and build an array like this:
$statement = $pdo->query("SELECT id FROM category;");
$ids = $statement->fetchAll(PDO::FETCH_COLUMN, 0);
$data = array();
foreach($ids as $id)
{
$statement = $pdo->prepare("SELECT * FROM subproduct INNER JOIN category " .
"ON category.id = subproduct.cat_id WHERE category.id = :id");
$statement->bindValue(":id", $id, PDO::PARAM_INT);
$statement->execute();
$data[$id] = $statement->fetchAll();
}
print_r($data);
I am not crazy about this because it looks inefficient and I don't like looping through queries. You could also request all the data at once and then rearrange it:
$statement = $pdo->query("SELECT * FROM subproduct");
$data = array();
while($subproduct = $statement->fetch(PDO::FETCH_ASSOC))
{
$id = $subproduct['cat_id'];
if (!isset($data[$id])
$data[$id] = array();
array_push($data[$id], $subproduct);
}
print_r($data);
I don't really like this either because using PHP to sort MYSQL data feels wrong since that is MYSQL's job. I could have requested MYSQL sort the data, but then the data would still need to be broken up into a multi-dimensional array, so I am not sure that helps.

PHP: Join two separate mysql queries into the same json data object

I'm trying to mesh the below mysql query results into a single json object, but not quite sure how to do it properly.
$id = $_POST['id'];
$sql = "SELECT contracts.po_number, contracts.start_date, contracts.end_date, contracts.description, contracts.taa_required, contracts.account_overdue, jobs.id AS jobs_id, jobs.job_number, companies.id AS companies_id, companies.name AS companies_name
FROM contracts
LEFT JOIN jobs ON contracts.job_id = jobs.id
LEFT JOIN companies ON contracts.company_id = companies.id
WHERE contracts.id = '$id'
ORDER BY contracts.end_date";
$sql2 = "SELECT types_id
FROM contracts_types
WHERE contracts_id = '$id'";
//return data
$sql_result = mysql_query($sql,$connection) or die ("Fail.");
$arr = array();
while($obj = mysql_fetch_object($sql_result)) { $arr[] = $obj; }
echo json_encode($arr); //return json
//plus the selected options
$sql_result2 = mysql_query($sql2,$connection) or die ("Fail.");
$arr2 = array();
while($obj2 = mysql_fetch_object($sql_result2)) { $arr2[] = $obj2; }
echo json_encode($arr2); //return json
Here's the current result:
[{"po_number":"test","start_date":"1261116000","end_date":"1262239200","description":"test","taa_required":"0","account_overdue":"1","jobs_id":null,"job_number":null,"companies_id":"4","companies_name":"Primacore Inc."}][{"types_id":"37"},{"types_id":"4"}]
Notice how the last section [{"types_id":"37"},{"types_id":"4"}] is placed into a separate chunk under root. I'm wanting it to be nested inside the first branch under a name like, "types".
I think my question has more to do with Php array manipulation, but I'm not the best with that.
Thank you for any guidance.
Combine the results into another structure before outputting as JSON. Use array_values to convert the type IDs into an array of type IDs. Also, fix that SQL injection vulnerability. Using PDO, and assuming the error mode is set to PDO::ERRMODE_EXCEPTION:
$id = $_POST['id'];
try {
$contractQuery = $db->prepare("SELECT contracts.po_number, contracts.start_date, contracts.end_date, contracts.description, contracts.taa_required, contracts.account_overdue, jobs.id AS jobs_id, jobs.job_number, companies.id AS companies_id, companies.name AS companies_name
FROM contracts
LEFT JOIN jobs ON contracts.job_id = jobs.id
LEFT JOIN companies ON contracts.company_id = companies.id
WHERE contracts.id = ?
ORDER BY contracts.end_date");
$typesQuery = $db->prepare("SELECT types_id
FROM contracts_types
WHERE contracts_id = ?");
$contractQuery->execute(array($id));
$typesQuery->execute(array($id));
$result = array();
$result['contracts'] = $contractQuery->fetchAll(PDO::FETCH_ASSOC);
$result['types'] = array_values($typesQuery->fetchAll(PDO::FETCH_NUM));
echo json_encode($result); //return json
} catch (PDOException $exc) {
...
}
If $contractQuery returns at most one row, change the fetch lines to:
$result = $contractQuery->fetch(PDO::FETCH_ASSOC);
$result['types'] = array_values($typesQuery->fetchAll(PDO::FETCH_NUM));
It would seem like you'd be better served by consolidating the two queries with a JOIN at the SQL level. However, assuming the two arrays have equal length:
for ($x = 0, $c = count($arr); $x < $c; $x++) {
if (isset($arr2[$x])) {
$arr[$x] += $arr2[$x];
}
}
echo json_encode($arr);
Edit: you would need to change from mysql_fetch_object to mysql_fetch_assoc for this to work properly.
Why are you using 2 distinct arrays ? I would simply add the rows of the 2nd query in $arr instead of $arr2. This way, you end up with a single array containing all rows from the 2 queries.

Categories