How to add query parameters in PHP code database output - php

I have tasks.php file which shows all results of database.
I'm now looking to add query parameters in the URL that would result in "tasks.php/query=books" that would only show raw data showing data that contains "books" in columns Task_title or task_description from my SQL database.
Say if query="" then return all tasks and if query=somevalue then filter based on it.
I have tried creating a separate file for search query with success, but I need to include in this tasks.php for app dev and I'm not sure how to integrate.
Here is my tasks.php
<?php
// Create connection
$con=mysqli_connect("test","test","test","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Select all of our stocks from table 'stock_tracker'
$sql = "
SELECT * FROM `tasks` ORDER BY `tasks`.`date_added` DESC
";
$cValue=str_replace(array("'",",","."), array("&#039;","&#44;","&#46;"), $_POST['contractValue']);
// Confirm there are results
if ($result = mysqli_query($con, $sql))
{
// We have results, create an array to hold the results
// and an array to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each result
while($row = $result->fetch_object())
{
// Add each result into the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Encode the array to JSON and output the results
echo json_encode($resultArray, DEFINED('JSON_INVALID_UTF8_IGNORE') ? JSON_INVALID_UTF8_IGNORE : 0);
}
// Close connections
mysqli_close($con);
?>

Step 1.
In Url it should be - tasks.php?query=books instead of tasks.php/query=books
Step 2.
Get your query value form url
$search_key = $_GET['query'];
Step 3.
Change your select query.
SELECT * FROM `tasks` WHERE `Task_title` LIKE '%$search_key%' OR `task_description` LIKE '%$search_key%' ORDER BY `tasks`.`date_added` DESC

Related

PHP search query results not showing apostrophes

Running a simple search query, which feeds into an android studio textview. When I first managed to display results via .php site, all special characters ([{]}) were on show, but i added this line to remove:
echo json_encode($resultArray, DEFINED('JSON_INVALID_UTF8_IGNORE') ? JSON_INVALID_UTF8_IGNORE : 0);
However, this now means that the results that show are also missing special characters, mainly " ' ". So "You're", is actually showing "Youre".
I have tried to play with the above json query, but with no luck - any idea what I'm doing wrong?
Full code for clarity:
<?php
// Create connection
$con=mysqli_connect("server","user","pass","table");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Select all of our stocks from table 'stock_tracker'
$sql = "
SELECT Task_title
, task_description
FROM TASKS
ORDER
BY RAND () ASC
LIMIT 1
";
// Confirm there are results
if ($result = mysqli_query($con, $sql))
{
// We have results, create an array to hold the results
// and an array to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each result
while($row = $result->fetch_object())
{
// Add each result into the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Encode the array to JSON and output the results
echo json_encode($resultArray, DEFINED('JSON_INVALID_UTF8_IGNORE') ? JSON_INVALID_UTF8_IGNORE : 0);
echo json_last_error_msg(); // Print out the error if any
die(); // halt the script
}
// Close connections
mysqli_close($con);
?>
I resolved this by adding $cValue=str_replace(array("'",",","."), array("&#039;","&#44;","&#46;"), $_POST['contractValue']);underneath the search query. Worked a charm!

MySQL query returning blank rows, even though I don't have blank rows

I have a search query that returns the results from the table, however it also returns blank rows. In my table, I don't have blank rows.
I have tried to limit the results to show 1, but it doesn't seem to have any affect. Would it be that I don't have a "if 0 results then...."?
php code:
<?php
// Create connection
$con=mysqli_connect("server","user","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Select all of our stocks from table 'stock_tracker'
$sql = "
SELECT Task_title
, task_description
FROM TASKS
ORDER
BY RAND () ASC
LIMIT 1
";
// Confirm there are results
if ($result = mysqli_query($con, $sql))
{
// We have results, create an array to hold the results
// and an array to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each result
while($row = $result->fetch_object())
{
// Add each result into the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
The issue was the UTF8, i edited my code to the following:
echo json_encode($resultArray, DEFINED('JSON_INVALID_UTF8_IGNORE') ? JSON_INVALID_UTF8_IGNORE : 0);
To find this issue, I added the following to my script to show what the error was for the blank values:
Just after the json_encode() function that you have:
echo json_last_error_msg(); // Print out the error if any
die(); // halt the script

Running two select queries in php and encoding it in json format?

I have two tables billing_all and payment_details. I am trying to write php code such that I can run the 2 queries in the same php code and encode their data in json format.I am currently using the following code to achieve that without json encode :-
<?php
include "config.php";
$dbname ="webappdb";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$dbname);
if(!$con)
{
echo "Connection Error".mysqli_connect_error();
}
else{
//echo "";
}
$sql = "SELECT SUM(total_wt) FROM `billing_all` WHERE date ='15-Apr-2016';";
$sql .= "SELECT pymt_amount, mode_of_pymt FROM `payment_details` WHERE DATE ='15-Apr-2016';";
// Execute multi query
if (mysqli_multi_query($con,$sql))
{
do
{
// Store first result set
if ($result=mysqli_store_result($con)) {
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
printf("%s%s\n",$row[0],$row[1]);
}
// Free result set
mysqli_free_result($result);
}
}
while (mysqli_next_result($con));
}
mysqli_close($con);
?>
How can I encode the received data in json format? I tried something like:-
// Store first result set
if ($result=mysqli_store_result($con))
{
$r = array();
while($row = mysqli_fetch_array($result))
{
array_push($r,
array('total_wt'=>$row[0],
'pymt_amount'=>$row[0],$row[1],
'mode_of_pymt'=>$row[0],$row[1]));
}
echo json_encode(array("result"=>$r));
Which does not give me the expected result.How can I encode the data
in the right way? The following is the structure for the 2 tables
I am new to programming any help is appreciated.Thank you?
<?php
//Joining both tables on the basis of doc_no column
$sql = "SELECT billing_all.SUM(total_wt) AS total
,payment_details.pymt_amount
,payment_details.mode_of_pymt
FROM billing_all
,payment_details
WHERE billing_all.doc_no = payment_details.doc_no
AND billing_all.DATE = '15-Apr-2016'";
// Executing query
$res = mysqli_query($con,$sql);
//initializing array to store result
$rows = array();
//Iterating result and storing each row in $r then array $rows to covert result set into array because json accept array as parameter.
while($r = mysqli_fetch_assoc($res))
{
$rows[] = $r;
}
//print whole array in json format
echo json_encode($rows); ?>

The following code returns the value twice, once encoded in JSON :

$sql = " select * from Papers where IND < 317";
// Check if there are results
if ($result = mysqli_query($conn, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_assoc())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode(array("Papers"=>$resultArray));
}
// Close connections
mysqli_close($conn);
?>
When I open my php file on the local host my rows from mysql database are correctly be converted into json objects however they are being duplicated.
FIXED - Had to clean my database. I had ran several instances of the insert statement that had caused many duplicate instances.
You probably can just do:
array_push($resultArray, $row);
Since you dont need to assign this to a variable.

PHP: Retrieving two most recent mySQL table entries and storing each in a different variable

Please see the below code.
I am trying to retrieve the most recent two "element_value"s from my database table and then put them into a different table, with one column each. I can do this part with a mysql insert statement if I can get them into variables within the PHP, at the moment I have them being echoed out to the screen instead.
Does anyone know please how I can get them into two separate variables instead?
Thanks!
//Connect to database
$con=mysqli_connect("localhost","user","pass","dbname");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL database: " . mysqli_connect_error();
}
//Query the database
$result = mysqli_query($con, 'SELECT element_value FROM wp_formmaker_submits ORDER BY id DESC LIMIT 2;');
//Process the results
if (mysqli_num_rows($result) > 0) {
while ( $dataValue = mysqli_fetch_row($result))
echo "<p>".$dataValue[0]."</p>";
}
Change :
while ($dataValue = mysqli_fetch_row($result))
echo "<p>".$dataValue[0]."</p>";
To this :
$values = null;
while ($dataValue = mysqli_fetch_assoc($result))
{
$values[] = $dataValue['element_value'];
}
print_r($values);
This will store your values in an array, I've added print_r at the end just so you can see the resulting data structure.
If you want to display them in an array again, you can do this :
foreach ($values as $value)
{
echo "<p>".$value."</p>";
}
I've changed your fetch_row method for fetch_assoc, an explanation can be found here : https://stackoverflow.com/a/9540590/2483649

Categories