how to convert my sql query into json using php? - php

I have created a text box in which a query is entered and I need to run the query to display the values stored in the mysql table using php. Kindly help me with the approach of the project or any links that can help me. I have tried doing it by taking single query in php:
<?php
$username = "username";
$password = "password";
$host = "localhost";
$database="test";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "SELECT `date_joined`, `city` FROM `users`";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
But I want to get the json for every query that is being entered in the textbox. How do I handle that ?

Try this:
<?php
$username = "username";
$password = "password";
$host = "localhost";
$database="test";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "";
$myquery = $_POST["id_of_the_text_box"];
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
But try to validate first the SQL entered in the textfield.

Related

Return list of strings with mysql query in PHP

I'm trying to make a simple query with PHP that returns a list of Strings with all the names of the users, but I can figure out how to do do it. The only thing i thought wa this:
<?php
$host_name = "hostname";
$database = "database";
$user_name = "username";
$password = "pass";
$connect = mysqli_connect($host_name, $user_name, $password, $database);
$select = "SELECT username from userstasker";
$result = $connect->query($select);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
$connect->close();
?>
But this returns a JSon, ant idea how to do it?
<?php
$host_name = "hostname";
$database = "database";
$user_name = "username";
$password = "pass";
$connect = mysqli_connect($host_name, $user_name, $password, $database);
$select = "SELECT username from userstasker";
$result = $connect->query($select);
$usernames = array();
while($r = mysqli_fetch_assoc($result)) {
$usernames[] = $r["username"];
}
$connect->close();
// Do something with $usernames
?>

How to retrieve images from database in php

I have a database which has a table called 'propImages' and there are two columns.- 'pid' and 'location'.
And i have data in the database where multiple images can contained by single pid.
image contains database data
now i want to retrieve images from database according to given pid. there can be more than one image.
All i know it there should be an iteration to retrieve images.
I want to display images in HTML .
can you please show me the way to do it in php?
Thanks in advance guys
This may help you
<?php
include 'inc/database.php';
$conn = new mysqli($servername, $username, $password, $database);
$propid = $_GET['propid'];
$sql = "SELECT * FROM propImages WHERE propid='" . $propid . "';";
$result = $conn->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<img src=" . $row['image'] . ">";
}
}
else {
echo "No results";
}
?>
in the inc/database.php :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "database";
?>
To see how it works try visiting : file.php?propid=22
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "databasename";
// Create connection
$con = mysqli_connect($servername, $username, $password, $dbname);
//create sql
$sql = "SELECT * FROM `propImages` where pid='$YOUR_PID'";
$result = mysqli_query($con, $sql);
$row = mysqli_num_rows($result);
//retrive data print here
if($row > 0){
while($col = mysqli_fetch_assoc($result))
{
echo $col['location'];
}
} else {
echo 'no result found.';
}
?>
wish it helps

extracting an array from a database in php

im currently trying to extract a table from my database (articles) and the table article and put it in an array but im not sure weather or not it wokred because i dont know how to print an array. i was following this link.
http://phpscriptarray.com/php-arrays-tutorials-tour/how-to-extract-mysql-database-data-into-php-array-variable.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// create connection
$conn = new mysqli($servername, $username, $password);
// check connection
if ($conn->connect_error){
die("connection failed: " . $conn->connect_error);
}
// connect to DB
$db_selected = mysqli_select_db('article', $conn);
if (!$db_selected){
die("can't use article : " .mysqli_error());
}
// extract databases table to PHP array
$query = "SELECT * FROM `articles`";
$result = mysqli_query($query);
$number = mysql_numrows($result);
$article_array = array();
$x = 0
while($x < $number)
{
$row = mysqli_fetch_array($result);
$artic = $row['name'];
$amount = $row['quantity'];
$article_array[$artic] = $amount;
$x++;
}
echo count($article_array);
//echo "hello";
<?
even the echo hello wont work and im not sure if i was supposed to put a name and quantity in:
$artic = $row['name'];
$amount = $row['quantity'];
You are mixing object oriented with procedural style. Your query and loop should look like this:
$query = "SELECT * FROM `articles`";
$result = $conn->query($query);
$article_array = array();
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$artic = $row['name'];
$amount = $row['quantity'];
$article_array[$artic] = $amount;
}
http://php.net/manual/en/mysqli.query.php
Also your PHP closing tag is faulty - should be ?> or omitted.

Convert php data to Json

I'm a newbie to php. I'm working on fetching the result from the DB and to send those details in the format of Json to the ajax call. Whereas I'm not able to convert using json_encode.
I'd like to get the result in the format of
[{"id":1,"name":"Rafael","password":"rafael"},{"id":1,"name":"nadal","password":"nadal"}]
My php code is
// credentials of MySql database.
$username = "root";
$password = "admin";
$hostname = "localhost";
$jsonArray = array();
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("Angular",$dbhandle)
or die("Could not select Angular");
//execute the SQL query and return records
$result = mysql_query("SELECT name,password FROM User");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
$id = $row{'id'};
$name = $row{'name'};
$password = $row{'password'};
$jsonData = json_encode($name,$password);
}
echo "Json:".$jsonData;
Change the code after mysql_query to:
while($row = mysql_fetch_assoc($result))
{
$jsonArray[] = $row;
}
echo json_encode($jsonArray);
Note that you do not select the ID in the query. it should be
$result = mysql_query("SELECT id, name, password FROM User");
The parameters within a json_encode must be an array.
You should use
$jsonData = json_encode( $array ); //$array is your array element
Use Something like this
$queryString = "SELECT * FROM user";
$query = mysql_query($queryString) or die(mysql_error());
$db = array();
while($dbs = mysql_fetch_assoc($query)) {
$db[] = $dbs;
}
echo
$output = json_encode(array(
"success" => mysql_errno() == 0,
"information" => $db
));
myoutput will be look like this;
it will display all the fields in your databasetable
{"success":true,"information":[{"id":"1","username":"sampleName","LastName":"SampleLastName"}]
}
Hope it works :D

Multi URL paramaters with PHP and SQL

<?php
$username = "username";
$password = "password";
$hostname = "localhost";
$database = "database";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($database,$dbhandle)
or die("Could not select database");
$id = 0;
if(isset($_GET['Day'])){ $id = (int)$_GET['Day']; }
if(!$id){
$query = "SELECT * FROM `TimeTable`";
} else {
$query = "SELECT * FROM `TimeTable` WHERE `Day`='".$id."'";
}
$result = mysql_query($query);
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
or die(mysql_error());
print json_encode($rows);
?>
This code worked previously, but has now stopped, and is producing Parse error: syntax error, unexpected T_LOGICAL_OR in /Directory/TimeTable.php on line 27
I am also looking to add more parameters, (eg: Where Day = $id and Year = $Year )
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
or die(mysql_error());
This is a syntax error, doesn't know what to do with that or die() statement. Change to this:
$result = mysql_query($query);
if (!$result) {
die('Error');
}
while(...) {
}
I have looked up the new mysql functions an have changed to mysqli.
<?php
$username = "username";
$password = "password";
$hostname = "localhost";
$database = "database";
$link = mysqli_connect($hostname, $username, $password, $database);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
$id= 0;
if(isset($_GET['Day'])){ $id=(int)$_GET['Day']; }
$year = 0;
if(isset($_GET['Year'])){ $year=(int)$_GET['Year'];}
if(!$id){
$query = "SELECT * FROM TimeTable";
} else {
if (!year) {
$query = "Select * FROM TimeTable";
} else {
$query = "SELECT * FROM TimeTable WHERE Day=$id AND Year=$year";
}
}
$rows = array();
//Perform JSON encode
if($result = mysqli_query($link, $query)){
while($r = mysqli_fetch_assoc($result)){
$rows[] = $r;
}
}
print json_encode($rows);
?>

Categories