How can I create a json object in php - php

I am working in android and php.
I want to return a json object to android program from php program.
If these is a entry in a database then it is working properly. But when there is no record in database then it goes wrong.
I would welcome suggestions
I want to make json object like this ([{"id":"5"}])
This is my php program:-
$server = "localhost";
$username = "root";
$password = "";
$database = "mymusic";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id=$_GET["id"];
$pass=$_GET["password"];
//$id='ram';
//$pass='ram';
$sql = "SELECT id FROM login where userid='$id' and password='$pass'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
if (mysql_num_rows($result)==0)
{
//what should i right here to make jsonobject like this:- ([{"id":"5"}])
echo myjsono;
}
else
{
while($row = mysql_fetch_assoc($result))
{
$records[] = $row;
}
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
}
?>

How about something like this: (replace with your own variables)
if (empty($row)){
$arr = array('success' => 'false');
} else {
$arr = array('success' => 'true');
}
echo json_encode($arr);

If you want your android app to receive an object with a special id in the case of a not found condition I would return this:
{"id":"0"}
Then in your android app check if the id == 0 and that will tell you no records were found.

This is very correct solution for my question:-
$server = "localhost";
$username = "root";
$password = "";
$database = "mymusic";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id=$_GET["id"];
$pass=$_GET["password"];
//$id='ram';
//$pass='ram';
$sql = "SELECT id FROM login where userid='$id' and password='$pass'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
if (mysql_num_rows($result)==0)
{
// {"messages":{"message":[{"id": "17","user": "Ryan Smith","text": "This is an example of JSON","time": "04:41"}]};}
**echo '('.'['.json_encode(array('id' => 0)).']'.')';** //**note this**
}
else
{
while($row = mysql_fetch_assoc($result))
{
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
}
//mysql_close($con);
//echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>

Related

How can fetch a variable in sql to php according to post id? [duplicate]

I am getting an error "Fatal error: Call to undefined function fetch_assoc()". Can you please advise on how I should proceed?
The code is mentioned below
$servername = "localhost";
$username = "s";
$password = "j";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "select idnew_table, new_tablecol from new_schema.new_table;";
$result = $conn->query($sql);
$r = count($result);
if ($result['num_rows'] != 10) {
while($row = $result[fetch_assoc()]){
echo "id: " . $row["idnew_table"]. " - Name: " . $row["new_tablecol"];
}
} else {
echo "0 results";
}
$conn->close();
This line:
while($row = $result[fetch_assoc()]){
should be:
while($row = $result -> fetch_assoc()){

PHP MySQL queries return no results

My queries to MySQL via PHP are returning no results. First, I have tried connecting and doing a select on a known table and get no results. I then try to get a listing of the tables and again no results. When I look at the database via phpMyAdmin I can see the tables and their contents. Here is my code. Can anyone offer some help as to what I am doing wrong?
<?php
# /* $ php -f db-connect-test.php */
echo"preparing to connect";
$dbname = '#########';
$dbuser = '#########';
$dbpass = '#########';
$dbhost = 'localhost';
$connect = #mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) or die("Unable to Connect to '$dbhost'");
echo"<html>";
echo"<title>test page</title>";
echo"<body>";
echo"<h2> test page</h2>";
/* check connection */
if ($conn->connect_error) {
die("Connection failed: " . mysqli_connect_error());
}
else{
echo"Successfully Connected <p>";
}
if(mysqli_ping($connection)){
echo "got it<p>";
}
$sql = "SELECT * FROM `announcements`";
$result = mysqli_query($dbname, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo 'date: ' . $row['date'] . '\tTitle: ' . $row['title'] . '\tBody: ' . $row['body'] .'<br />';
}
} else {
echo "0 results<p>";
$sql = "SHOW TABLES";
$result = mysqli_query($dbname, $sql);
if (!$result) {
echo "DB Error, could not list tables<p>";
echo 'MySQL Error: ' . mysqli_error();
}
else{
while ($row = mysqli_fetch_row($result)) {
echo "Table: {$row[0]}<p>";
}
}
}
$conn->close();
echo"</body>";
echo"</html>";
?>
Here is the result I am seeing:
preparing to connect
test page
Successfully Connected
0 results
DB Error, could not list tables
MySQL Error:
end of results
For some reason I am unable to get MySQL to return a error message.
When calling mysqli_query()
mysqli_query($dbname, $sql);
The first parameter is your database link not the name...
mysqli_query($connect, $sql);
Also - don't use # for your connection (or preferably anywhere) as this suppresses errors.
Update:
Also just noticed...
mysqli_ping($connection)
which should be...
mysqli_ping($connect)
You just have to Copy and Paste this code
You don't have to use $dbname
Have to use $connect
<?php
# /* $ php -f db-connect-test.php */
echo"preparing to connect";
$dbname = '#########';
$dbuser = '#########';
$dbpass = '#########';
$dbhost = 'localhost';
$connect = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) or die("Unable to Connect to '$dbhost'");
echo"<html>";
echo"<title>test page</title>";
echo"<body>";
echo"<h2> test page</h2>";
/* check connection */
if ($conn->connect_error) {
die("Connection failed: " . mysqli_connect_error());
}
else{
echo"Successfully Connected <p>";
}
if(mysqli_ping($connection)){
echo "got it<p>";
}
$sql = "SELECT * FROM `announcements`";
$result = mysqli_query($connect, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo 'date: ' . $row['date'] . '\tTitle: ' . $row['title'] . '\tBody: ' . $row['body'] .'<br />';
}
} else {
echo "0 results<p>";
$sql = "SHOW TABLES";
$result = mysqli_query($connect, $sql);
if (!$result) {
echo "DB Error, could not list tables<p>";
echo 'MySQL Error: ' . mysqli_error();
}
else{
while ($row = mysqli_fetch_row($result)) {
echo "Table: {$row[0]}<p>";
}
}
}
$conn->close();
echo"</body>";
echo"</html>";
?>

Mysql parameterized queries in php

I have a php code for some MYSQL interogations,
Code is:
$DBTYPE = 'mysql';
$DBHOST = 'localhost';
$DBUSER = 'tuser';
$DBPASSWORD = 'password';
$DBNAME = 'dbname';
$link = mysql_connect($DBHOST, $DBUSER, $DBPASSWORD);
mysql_select_db($DBNAME);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//IMG**0**
$hotelc = $hotelCodes[**0**];
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
$ImageURL**0** = $row["ImageURL"];
}
//IMG**1**
$hotelc = $hotelCodes[**1**];
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
$ImageURL**1** = $row["ImageURL"];
}
..........................
//IMG**x**
$hotelc = $hotelCodes[**x**];
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
$ImageURL**x** = $row["ImageURL"];
}
The repeating value on each code line is bolded.
How can i create a Mysql parameterized queries in php.n to avoid write all the lines .I need to extract ~100 $ImageURL from the Flat_table where the $hotelc is found.
For example you have to repeat it $N times:
for($i=0; $i<$N; $i++)
{
$hotelc = $hotelCodes[ $i ];
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
if(!$result) {
die("Database query failed: ".mysql_error());
}
while ($row = mysql_fetch_array($result)) {
${'ImageURL'+$i} = $row["ImageURL"];
}
}
To loop, use for:
for($n=0; $n<100; $n++){
$hotelc = $hotelCodes[$n];
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
$ImageURL[$n] = $row["ImageURL"];
}
}
But the inner functions inside the loop is inefficient because mysql query will be executed 100 times. You can query all the ImageURL by using IN() syntax in mysql:
//Wrap all hotelCodes into one string for query, like ["a","b"] to "'a','b'"
$len = count($hotelCodes);
foreach($hotelCodes as $key=>$code){
$hotelCodes[$key] = "'".$code."'";
}
$codesStr = implode(",", $hotelCodes);
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode IN (".$codeStr.")", $link);
//Other things...
When writing a function, you look for the commonality. Furthermore, you want to minimize the database interaction. I am, for the sake of deprecation, going to assume $link uses mysqli_connect()
$ImageURL = array();
$list = implode('", "', $hotelCodes);
$result = mysqli_query($link, 'SELECT ImageURL FROM Flat_table where HotelCode IN "' . $list . '"');
while($row = mysql_fetch_assoc($result)) {
$ImageURL[] = $row["ImageURL"];
}
This runs only one query and then loops through the results, generating an associative array. So echo $ImageURL[0]; will output your first URL.

SQL query not functioning correctly, getting no output with a perfectly fine query

code:
<?php
session_start();
if ( isset($_GET['user']) && isset($_GET['pass']) )
{
$sql = "SELECT * FROM `users` WHERE `name` = '" . $_GET['user'] . "' AND `password` = '" . $_GET['pass'] . "';";
echo("query: $sql <br />");
$db = mysqli_connect("localhost", "root", "<password here>", "1596");
if (mysqli_connect_errno($db)) { die("err"); }
$result = mysqli_query($db, $sql);
echo($query);
$row = mysqli_fetch_aray($result);
echo($row);
if ($row['name'] == $_GET['user'])
{
$_SESSION['uid'] = $row['name'];
$_SESSION['level'] = $row['level'];
echo("logged in as " . $_SESSION['uid']);
}
}
else
{
die("Error, not enough parameters");
}
?>
If I run that query on server, it is fine.. there is no connect error, so wondering where I went wrong
$db = mysqli_connect("localhost", "root", "<password here>", "1596");
if (mysqli_connect_errno($db)) { die("err"); }
$result = mysqli_query($db, $sql); // line corrected
$row = mysqli_fetch_array($result); // line corrected

PHP reading fields in database

I have a script that reads my database table fields. Its not reading the first column which is the id.It reads the other fields and adds them into the array. I have added in the for loop a -1 to get every field but to no success.
$host=rtrim($_POST['host']);
$user=rtrim($_POST['user']);
$pass=rtrim($_POST['pass']);
$dbselect=rtrim($_POST['dbselect']);
$table=rtrim($_POST['table']);
$classname=rtrim($_POST['classname']);
$key_values = array();
$link = mysql_connect($host,$user,$pass);
$db_select = mysql_select_db($dbselect);
$query = mysql_query('SHOW COLUMNS FROM '.$table.'');
if (!$link) {
die('Could not connect to MySQL server: ' . mysql_error());
}
$dbname = $dbselect;
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
die("Could not set $dbname: " . mysql_error());
}
$res = mysql_query('select * from '.$table.'', $link);
$num_fields = mysql_num_fields($res);
for($i=0;$i<$num_fields;$i++){
$key_values[]=mysql_field_name($res,$i);
}
echo "<pre>";
print_r($key_values);
echo "</pre>";
There is no more support for mysql_* functions, they are officially deprecated, no longer maintained and will be removed in the future. You should update your code with PDO or MySQLi to ensure the functionality of your project in the future.
<?php
$host=rtrim($_POST['host']);
$user=rtrim($_POST['user']);
$pass=rtrim($_POST['pass']);
$dbselect=rtrim($_POST['dbselect']);
$table=rtrim($_POST['table']);
$classname=rtrim($_POST['classname']);
$db = new mysqli($host,$user,$pass,$dbselect);
if($db->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
// NOTE real_escape_string may not work for tables untested
$result = $db->query("SELECT * FROM " . $db->real_escape_string($table));
if (!$result)
die "Error: " . $db->error;
while ($row = $result->fetch_object())
{
echo $row->id;
}
$result->close();
$db->close();
I don't see why it might be doing that, but this should be more reliable:
$query = mysql_query('select * from `%s`', mysql_real_escape_string($table), $link);
while ($result = mysql_fetch_array($query)) {
print_r(array_keys($result));
}
Try to use php native function mysql_fetch_array (also you need view this quastion before)
After try this code ($res === 'resources'):
$res = mysql_query('select * from '.$table.'', $link);
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
$key_values[] = array_keys($row);
}
echo "<pre>";
print_r($key_values);
echo "</pre>";

Categories