How to pass multiple rows as json in php - php

I'm trying to pass row details as JSON. How can one separate the selected columns from the query
$SQLTask = "
SELECT priority
, task_name AS title
, task_description AS description
, start_date AS start
, end_date AS end
FROM t_tasks
"; -- removed extraneous semi-colon
$RESULT_Task = mysqli_query( $conn, $SQLTask );
while($ROW_TASK = mysqli_fetch_assoc($RESULT_Task))
{
$TASK_NAME = $ROW_TASK['title'];
$TASK_DESC = $ROW_TASK['description'];
$TASK_START = $ROW_TASK['start'];
$TASK_END = $ROW_TASK['end'];
}
$TASK_DETAILS[] = array('title' => $TASK_NAME, 'description' => $TASK_DESC, 'start' => $TASK_START, 'end' => $TASK_END);
mysqli_close($conn);
echo json_encode($TASK_DETAILS);
Tried it in the format below and it worked but I need to use the priority column for other queries.
The JSON is to feed a calendar and show events.
<?php
require('../classes/class_connect.php');
$Project_ID = $_GET['id'];
$SQLTask = "SELECT task_name AS title, task_description AS description, start_date AS start, end_date AS end FROM t_tasks WHERE project_id = " . $Project_ID . "";
$RESULT_Task = mysqli_query( $conn, $SQLTask );
while($ROW_TASK = mysqli_fetch_assoc($RESULT_Task))
{
$TASK_ARRAY[] = $ROW_TASK;
// if($ROW_TASK['priority'] == 'Low')
// {
// $eventClassNames = "bg-light-secondary";
// }
// else if($ROW_TASK['priority'] == 'Normal')
// {
// $eventClassNames = "bg-light-primary";
// }
// else if($ROW_TASK['priority'] == 'High')
// {
// $eventClassNames = "bg-light-warning";
// }
// else if($ROW_TASK['priority'] == 'Urgent')
// {
// $eventClassNames = "bg-light-danger";
// }
// array_push($TASK_ARRAY,$eventClassNames);
}
mysqli_close($conn);
echo json_encode($TASK_ARRAY);```

I am not sure whether I have clearly understood your question and what you want to achieve as to "How can one separate the selected columns from the query".
But as for the second part you illustrated since all you wanted was priority field you could drop all other fields from the query. Also you could add the eventClassNames within the query.
Try to use mysqli's fetch_all and see how it works. For the first part then you wouldn't have to loop through the result set to create an array unless there was further processing to the array https://www.php.net/manual/en/mysqli-result.fetch-all.php
$SQLTask = "SELECT priority,
case priority
when 'Low' then 'bg-light-secondary'
when 'Normal' then 'bg-light-primary'
when 'High' then 'bg-light-warning'
when 'Urgent' then 'bg-light-danger'
end AS eventClassName
FROM t_tasks WHERE project_id = " . $Project_ID . "";
$RESULT_Task = mysqli_query( $conn, $SQLTask );
$TASK_ROWS=$RESULT_TASK->fetch_all(MYSQLI_ASSOC);
$TASK_ARRAY=array_column($TASK_ROWS,'eventClassName');
echo json_encode($TASK_ARRAY);

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = $mysqli->query($query);
/* numeric array */
$row = $result->fetch_array(MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);
/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
/* associative and numeric array */
$row = $result->fetch_array(MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);
/* free result set */
$result->free();
/* close connection */
$mysqli->close();
?>
echo json_encode($row)
Ref:https://www.php.net/manual/en/mysqli-result.fetch-array.php

Related

How I can execute the second query in php [duplicate]

This question already has answers here:
How I can execute many queries in one page?
(2 answers)
Closed 6 years ago.
I use this code it run very good but the problem how I can execute the second query:
$query .= "SELECT * FROM `course` where id = 201102887;";
which is from another table.The first query work fine . Can you help me or advise me to another way to run many query .
<?php
$link = mysqli_connect("localhost", "root", "", "uoh");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM `student_record` where id = 201102887;";
$query .= "SELECT * FROM `course` where id = 201102887;";
/* execute multi query */
if (mysqli_multi_query($link, $query)) {
do {
/* store first result set */
if ($result = mysqli_store_result($link)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
printf("%s\n", $row[1]);
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($link)) {
printf("-----------------\n");
}
} while (mysqli_next_result($link));
}
/* close connection */
mysqli_close($link);
?>
Try UNION for this
<?php
$link = mysqli_connect("localhost", "root", "", "uoh");
$query = "SELECT * FROM `student_record` where id = 201102887 UNION SELECT * FROM `course` where id = 201102887";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_row($result))
{
print_r($row);
}
?>
This should print two arrays (one per row), one from the student_record table (assuming id is unique) and one from the course table assuming that id is unique.

mysqli fetch result as assoc array

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";
if ($stmt = $mysqli->prepare($query)) {
/* execute statement */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($name, $code);
/* fetch values */
while ($stmt->fetch()) {
printf ("%s (%s)\n", $name, $code);
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
can somebody help me to this statement/syntax? i want the result as associative array (indexed by fieldname) and don't want to write this "$stmt->bind_result($name, $code);" statement. thanks
As you are not actually using any parameters i.e. ? then you dont really need to do a ->prepare
So you could just use the ->query() and ->fetch_assoc() mechanism
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";
$result = $mysqli->query($query)
if ( $result === FALSE ) {
echo $mysqli->error;
exit;
}
/* fetch values */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row['name'], $row['code']);
}
After your comment
This is another option, if you have to keep the prepare
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";
// there seems to be some confusion in the manual as to
// whether this next statement is needed or not
// see if that helps
$stmt = $mysqli->stmt_init();
if ($stmt = $mysqli->prepare($query)) {
/* execute query */
if (!$stmt->execute()) {
echo $stmt->error;
exit;
}
$result = $stmt->get_result();
/* fetch values */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row['name'], $row['code']);
}
} else {
echo 'Failed to prepare statement';
exit;
}
The call to $stmt->get_result() basically converts a mysql_stmt object to a mysql_result object
Try this.
$stmt = $mySqli->query($query);
$countries = mysqli_fetch_all($stmt, MYSQLI_ASSOC);
$stmt->close();
Just try this :
while ($stmt->fetch(PDO::FETCH_ASSOC)) {
printf ("%s (%s)\n", $name, $code);
}

How to separate mysql row values by comma using php?

I have tried the following code to output each student father_contact by firstly merging them and secondly separating each number by comma and could not make it working. Please help me.
$sql = "SELECT Fathers_Contact FROM student WHERE Class ='$class' AND Section='$s' and Year='$y'";
$result = mysql_query($sql);
if (!$result) {
die("Query not working");
}
$mbno_arr = array();
while ($row = mysql_fetch_array($result)) {
$mbno_arr[] = $row[0];
}
$mbno_list = implode(',', $mbno_arr);//expect here is: 9867656543,9867656443,9867654543
if(empty($mbno_list)){
echo "No number is there";
exit;
}
if(empty($msg)){
echo "Message empty!";
exit;
}
Father_contact is ten digit mobile no.
// Escapes special characters in a string for use in an SQL statement
$SQL = sprintf(
"SELECT Fathers_Contact
FROM student
WHERE Class = '%s' AND Section = '%s' and Year = '%s'",
mysql_real_escape_string($class),
mysql_real_escape_string($s),
mysql_real_escape_string($y)
);
// Result or die (print mysql error)
$result = mysql_query($SQL) or die( mysql_error() );
// Check if result has rows
if( mysql_numrows($result) > 0 )
{
$mbno_arr = array();
while ( $row = mysql_fetch_array($result) )
$mbno_arr[] = $row[0];
if( count($mbno_arr) > 0)
echo implode(',', $mbno_arr);
else
echo 'No number is there';
}
else
{
echo 'No result for query';
}
// free result
mysql_free_result($result);
NB use PDO or mysqli. mysql_* is deprecated
Firstly, mysql_* is now officially deprecated. Please use PDO or MySQLi.
Can you try this:
<?php
// Connect
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Query
$query = "SELECT Fathers_Contact FROM student WHERE Class = ? AND Section = ? and Year = ?";
if ($stmt = $mysqli->prepare($query)) {
{
// Bind params
$stmt->bind_param("sss",
$class,
$s,
$y);
// Execute statement
$stmt->execute();
// fetch associative array
$mbno_arr = array();
$result = $stmt->fetch_result();
while ($row = $result->fetch_assoc())
{
// Build data
$mbno_arr[] = $row['Fathers_Contact'];
}
// close statement
$stmt->close();
// Debug?
$mbno_list = implode(',', $mbno_arr);
if (empty($mbno_list)) {
echo "No number is there";
} else {
echo "Query Results: $mbno_list";
}
}
// Close Connection
$mysqli->close();
?>

PHP Error Gathering Database Information

Hi I have the following code below in a php file
global $server, $mysqlusername, $mysqlpassword, $db;
$conn = new mysqli($server, $mysqlusername, $mysqlpassword, $db);
function getCategories() {
global $conn;
$categories = array();
$sql = "SELECT categoryName FROM reportcategorys";
$maincat = $conn->query($sql);
while($row = $maincat->fetch_array(MYSQLI_ASSOC)) {
// do something with the $row
array_push($categories, $row);
}
$sql1 = "SELECT * FROM reportsubcategorys";
$subcats = $conn->query($sql1);
// Loop through sub categories and append to parent array
while($row = $subcats->fetch_array(MYSQLI_ASSOC)) {
$parent = $row['categoryName'];
$name = $row['subCategoryName'];
// Append subcategory name as child to the parent category
for ($i=0; $i<count($categories); $i++) {
if ($categories[$i]['categoryName'] == $parent) {
array_push($categories[$i], $name);
}
}
}
//print_r($categories);
return $categories;
}
It is giving me an error message saying
"Fatal error: Call to a member function fetch_array() on a non-object in"
Any idea what may be causing this?
Thanks
It is likely that your query has not executed properly.
mysqli->query() will return a boolean value FALSE if the query has not been executed properly, else it will return a mysqli_result object. So after every query, before calling fetch_array() method, check the result of the query. Something like this.
$maincat = $conn->query($sql) or die($conn->error);
or
$maincat = $conn->query($sql);
if(!$maincat){
echo $conn->error;
}
Also, when you established your connection with the database, check if the connection was error-free.
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
Are you using fetch_array for any reason in particular?
Try it like this one...
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* verificar la conexión */
if (mysqli_connect_errno()) {
printf("Conexión fallida: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
/* obtener array asociativo */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* liberar el resultset */
$result->free();
}
/* cerrar la conexión */
$mysqli->close();
?>

var_dump return bool(false) and #mysql_ping() return true, why ?

Problem with mysql connection via php. I have simple database as follows:
CREATE TABLE test (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
val INT
);
And when I do select in terminal connected with mysql:
select * from test;
it outputs normaly selected results.
The same selection I perform from php eg.:
<?php
$con = mysqli_connect("localhost", "root", "", "hfh") or die("Unable to Connect");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysql_query("SELECT * FROM test");
echo "results number: " . mysql_num_rows($result);
echo "<br/>";
echo mysql_num_rows($result);
echo "<br/>";
echo "results number: ";
echo "<br/>";
echo var_dump($result);
echo "<br/>";
echo #mysql_ping() ? 'true' : 'false';
mysqli_close($con);
?>
and it gives me output:
results number:
results number:
bool(false)
true
When I make an insert like:
mysqli_query($con,"INSERT INTO test (val) VALUES (55)");
It do not cause any problem.
What might be wrong above selection?
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = $mysqli->query($query);
/* numeric array */
$row = $result->fetch_array(MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);
/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
/* associative and numeric array */
$row = $result->fetch_array(MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);
/* free result set */
$result->free();
/* close connection */
$mysqli->close();
?>
refer url: http://us3.php.net/manual/zh/mysqli-result.fetch-array.php

Categories