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

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.

Related

How to pass multiple rows as json in 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

PHP searchbar not working

I'm trying to create a searchbar that search for the title .. database is working , content showing under searchbar then i search sth , it show me "connection succesfully and then no results .. what's wrong ?
<?php
include 'header.php';
?>
<h3>Rezultate</h3>
<div class"article-container">
<?php
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
echo "Connected successfully";
if(isset($_POST['submit-search']))
{
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM article WHERE a_title LIKE '%search%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if($queryResult >0)
{
while ($row = mysqli_fetch_assoc($result))
echo"<div>
<h3>".$row['a_title']."</h3>
<p>".$row['a_text']."</p>
<p>".$row['a_author']."</p>
<p>".$row['a_dat']."</p>
</div>";
}
else
{
echo "<br>No result!";
}
}
?>
</div>
Your SQL is wrong, when referencing the variable $search in the SQL query. Just change the %search% to %$search%:
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM article WHERE a_title LIKE '%$search%'";
Also, I strongly believe you should consider using Prepared Statements for anything which involves user input.
$search = "%" . $_POST['search'] . "%";
$sql = "SELECT * FROM article WHERE a_title LIKE ?";
if($stmt = $mysqli_prepare($conn, $sql)) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $search);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $district);
/* fetch value */
mysqli_stmt_fetch($stmt);
printf("%s Search Result: %s\n", $search);
/* close statement */
mysqli_stmt_close($stmt);
}
This will protect you a bit more against SQL Injections.
$sql = "SELECT * FROM article WHERE a_title LIKE '%search%'";
Your current query is searching for terms like the string "search". Fix it so it's a PHP variable.
$sql = "SELECT * FROM article WHERE a_title LIKE '%$search%'";

Why this PHP error occurs: "Strict standards: mysqli::next_result(): There is no next result set."?

I have code, which is basically a copy of a php.net's code, but for some reason it does not work. Here is the code on php.net:
<?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 CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
The first change I made was the connection:
$mysqli = new mysqli("localhost", "root", "", "fanfiction");
The second change I made was the queries:
$query = "SELECT first FROM tests;";
$query .= "SELECT second FROM tests;";
$query .= "SELECT third FROM tests;";
$query .= "SELECT fourth FROM tests";
EDIT: The full code with my changes
<?php
$mysqli = new mysqli("localhost", "root", "", "fanfiction");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT first FROM tests;";
$query .= "SELECT second FROM tests;";
$query .= "SELECT third FROM tests;";
$query .= "SELECT fourth FROM tests";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
The error I get:
Strict standards: mysqli::next_result(): There is no next result set.
Please, call mysqli_more_results()/mysqli::more_results() to check
whether to call this function/method in
address on line line number
I searched a solution over the net, and particularly here on StackOverflow, but I did not find helpful solutions. Most of the solutions I found were one of those two:
In this solution,#Hammerite says to change the loop from do-while to while. This suggest that php.net's code has a problem in its logic, and I find it very hard to believe. But more importantly, it just does not work for me.
In this solution, #mickmackusa suggests to add a condition in the while and change $mysqli->next_result() to $mysqli->next_result() && $mysqli->more_results(), but this solution do not work quite well. It does indeed removes the error but it omits the last result.
Try it with
} while ($mysqli->more_results() && $mysqli->next_result());
sscce:
<?php
ini_set('display_errors', 'on');
error_reporting(E_ALL|E_STRICT);
$mysqli = new mysqli("localhost", "localonly", "localonly", "test");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query('CREATE TEMPORARY TABLE City (ID int auto_increment, `Name` varchar(32), primary key(ID))') or die($mysqli->error);
$stmt = $mysqli->prepare("INSERT INTO City (`Name`) VALUES (?)") or die($mysqli->error);
$stmt->bind_param('s', $city) or die($stmt->error);
foreach(range('A','Z') as $c) {
$city = 'city'.$c;
$stmt->execute() or die($stmt->error);
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if (!$mysqli->multi_query($query)) {
trigger_error('multi_query failed: '.$mysqli->error, E_USER_ERROR);
}
else {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("'%s'\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->more_results() && $mysqli->next_result());
}
prints
'localonly#localhost'
-----------------
'cityU'
'cityV'
'cityW'
'cityX'
'cityY'
without warnings/notices.

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();
?>

In PHP & MySql programming how to executive more then 3 queries in a single statement?

i want to execute a more then 3 queries in a single statement.
is is possible?
i need to insert the values into the table
select entire table
count the users.
is it possible to do all these in a single statement.
Thanks
You can use more than 3 queries only in mysqli using mysqli_multi_query(), but mysql doesn't support it.
Example code :
<?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 CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
Change it accordingly. It shows multiquery in action using mysqli.

Categories