json_encode and json_decode in mySql misunderstanding - php

I am stuck in my PHP page for a json_encode since a couple of days after having done 9999 tests.
The goal is to log on a swift app using mySql database.
So I guess i have something wrong in my query, and i dont know how to send answer of found/not found user in json_encode().
Here is my php code:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
// i get the email and password sent as parameter
// my swift code is working, and the next line is ok.
$logs[] = array('email' => $obj->email, 'pass' => $obj->pass);
//echo json_encode($logs); // to send back my logs (ok)
// Create connection
$con = mysqli_connect("localhost", "xx", "xx", "xx");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//echo json_encode($logs);
// its working until here if i execute the previous line and put the rest in comment
// from the next line its making errors such :
// Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set."
$sql = "SELECT * FROM clients WHERE email = '".$logs['email']."'";
//echo json_encode($logs); //not working at this place if i put the rest in comment.
// Check if there are results
if ($result = mysqli_query($con, $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_object()) {
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
//check the corresponding password
if ( $logs['pass'] == $resultArray[4]) {
// i m not sure how to send the answer as a json
echo json_encode(true);
} else {
echo json_encode(false);
}
}
// Close connections
mysqli_close($con);
?>
If I try in php without all json stuff, its working since I put
$sql = "SELECT * FROM clients WHERE email = 'ben#test.be'";
as a test.
The following code works:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
$logs[] = array('email' => $obj->email, 'pass' => $obj->pass);
$con = mysqli_connect("localhost", "xx", "xx", "xx");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM clients";
if ($result = mysqli_query($con, $sql))
{
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
}
mysqli_close($con);
?>
But if I put $sql = "SELECT * FROM clients WHERE email = '$logs['email']'"; instead of $sql = "SELECT * FROM clients";
Its not working anymore. It doesn't like my conditional query. What did I misunderstood?

Related

How to get data from MySQL with PHP

Hello all I am tryin to build IOS app and I need to get data my MySQL database. I do not know php. I found a tutorial https://codewithchris.com/iphone-app-connect-to-mysql-database/
In section 3 where we create PHP service I copy it and edit for mine information. PHP code is like that
<?php
//create connection
$con=mysqli_connect("localhost","myuserid","mypassword","i4142489_wp1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM treelibrary";
// Check if there are results
if ($result = mysqli_query($con, $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_object())
{
// 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($resultArray);
}
// Close connections
mysqli_close($con);
?>
I load it the my server and nothings pops up just the blank page... Is there any reason or where is my mistake. Thanks for helps.
Have a nice day.
I didn't read you're whole code, but I'm pretty sure you're trying to put the results into a JSON format and echo them.
Here's an easy way to do so;
<?php
//
// EDIT: dont use this code, scroll a little bit lower to see the edit I made.
//
//create connection
$con=mysqli_connect("localhost","myuserid","mypassword","i4142489_wp1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM treelibrary";
// Executes the SQL statement and puts results into $res
$res = $con->query($sql);
// Checks if there's any rows
if($res->num_rows > 0) {
// Puts all results in $row
$row = $res->fetch_assoc();
// echo & encode datas
echo json_encode($row);
} else {
echo "no data found";
}
// Close connections
mysqli_close($con);
Edit: The code above does work but only echoes the first row.
Here's one that actually echoes all of the rows in JSON format (tested).
<?php
//create connection
$con=mysqli_connect("localhost","myuserid","mypassword","i4142489_wp1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM treelibrary";
// Executes the SQL statement and puts results into $res
$res = $con->query($sql);
// Checks if there's any rows
if($res->num_rows > 0) {
// defines $data
$data = array();
// grabs all data and adds them to the $data array
while ($row = $res->fetch_assoc()) {
array_push($data, $row);
}
// echo & encode datas
echo json_encode($data);
} else {
echo "no data found";
}
// Close connections
mysqli_close($con);

How to get the username of current user in php and use it in a mysql query

I'm a beginner in using php, and I want to send a query using the username of the current logged in user.
Where should I start the session? in the login php file?
how can i pass the variable to other php files?
<?php
session_start();
//importing required script
require_once '../includes/DbOperation.php';
// Create connection
$con=mysqli_connect(" ","root"," ","myiosapp");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM ITEM WHERE username = $_SESSION['username']"; //?
// Check if there are results
if ($result = mysqli_query($con, $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_object())
{
// 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($resultArray);
}
// Close connections
mysqli_close($con);
?>
First u need to fetch data off logged-in user
then u have to set those data in session variable
and then u will be able to use that session variable in your query.
you need to create api
http://example.com/testfile.php?username='abc';
then in php
<?php
//session_start();
//importing required script
require_once '../includes/DbOperation.php';
// Create connection
$con=mysqli_connect(" ","root"," ","myiosapp");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_GET['username'];
$sql = "SELECT * FROM ITEM WHERE username = $username"; //?
// Check if there are results
if ($result = mysqli_query($con, $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_object())
{
// 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($resultArray);
}
// Close connections
mysqli_close($con);
?>
Are you storing your login data to your IOS app? If yes, then pass your username for the query and then you might not get any problem.

My array didn't return anything in php

The array $response didn't return my item from database, it produce the result empty, causing my android application to display the error: "JSONException : End of input at character 0 of". Please provide any help, i will be appreciated.
<?php
include("connection1.php");
// connecting to db
$conn = mysqli_connect($hostname_localhost, $username_localhost, $password_localhost, $database_localhost);
/* check connection */
if (mysqli_connect_errno()) {
print "Error: Connect failed: %s\n";
exit();
}
mysqli_set_charset($conn, 'utf8');
$response = array();
/* Select queries return a resultset */
$query = "SELECT image FROM subject WHERE version = 'new'";
if ($result = mysqli_query($conn, $query)) {
$response = array();
while ($row = mysqli_fetch_array($result)) {
$item = array();
$item["image"] = $row["image"];
array_push($response, $item);
}
/* close result set */
mysqli_free_result($result);
}
echo json_encode($response);
/* close connection */
mysqli_close($conn);
?>
while ($row = mysqli_fetch_array($result)) {
array_push($response, base64_encode($row["image"]));
}
You set your $item as array and then you try to pass it as string. Basically $item = string and $item[] = array. So you just have to push the image value in the array you want. Try my code and give me some feedback. From what i see you made a circle out of it and got lost inside the while loop while you could just go simple.
As you will see here array push requires the array you want to store your values (array type) and the values (string type).

php returns empty GET array when trying to fetch MySQL data

I am trying to make a php REST API for my mobile backend to interact with a MySQL database. I have written out the following code to try and retrieve data from a MySQL query:
<?php include "FILE WITH DB_INFO"; ?>
<html>
<body>
<h1>Testing page</h1>
<?php
$connection = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
if (mysqli_connect_errno()) echo "Failed to connect to MySQL" . mysqli_connect_error();
$database = mysqli_select_db($connection, DB_DATABASE);
if (strlen($username_query)) {
doesUsernameExist($connection, $username_query);
}
doesUsernameExist($connection, $username_query);
$username_query = $_GET['usernameToQuery'];
echo($_GET['usernameToQuery']);
function doesUsernameExist($connection, $username) {
$u = mysqli_real_escape_string($connection, $username);
$query = "SELECT username from users WHERE username = ('$u');";
if (!mysqli_query($connection, $query)) {
$response = array("success" => false, "message" => mysqli_error($connection), "sqlerrno" => mysqli_errno($connection), "sqlstate" => mysqli_sqlstate($connection));
echo json_encode($response);
} else {
$sth = mysqli_query($connection, $query);
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
$response = array("success" => true);
echo json_encode($rows);
}
}
?>
This is what the actual request looks like: http://my_ec2_instance/DoesUsernameExist.php?usernameToQuery=lmao.
This is sent through POSTMAN.
Because the MySQL database that I am using contains usernames with the value lmao, the php function should return an array that is not empty. But the json_encode($rows); line returns an empty array []. What am I doing wrong.
It seems you call doUsernameExiste() and just before strlen with a variable $username_query. But you define $username_query only after.
You should first do your affectation. Put this after your line with the mysqli_select_db
$username_query = $_GET['usernameToQuery'];

php- cant get result from mysql (mysqli)

I'm attempting to set up an API for an app project.
I've got a mysql table called 'users', which I've added a row to.
using the code:
// Create connection
$mysqli = new mysqli("localhost","user", "pass", "db");
// Check connection
if($mysqli->connect_errno){
$result = "Failed to connect to MySQL: " . mysqli_connect_error();
print_r( json_encode($result) );
return false;
}
$row = $mysqli->query("SELECT * FROM users");
print_r( json_encode($row) );
I get an empty result, how come? (connection doesn't throw an error)
to be exact i get:
{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}
EDIT:
got the answer to ym original question, thanks!
so now using the code:
$row = $mysqli->query("SELECT * FROM users WHERE email = '".$email."'");
$result = $row->fetch_array();
print_r( json_encode($result) );
I get the result:
{"0":"test","username":"test","1":"test#test.com","email":"test#test.com","2":"test","password":"test","3":"2013-10-18 22:22:53","date_registered":"2013-10-18 22:22:53","4":"1","id":"1"}
where what i want is something like:
{"username":"test","password":"test","email":"test#test.com", ...etc }
how do i get that?
Try this:
$result = $mysqli->query("SELECT * FROM users");
$row = $result->fetch_array(MYSQLI_ASSOC);
print json_encode($row); // json_encode returns a string...
Try this for your associative array:
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$rows[] = $row;
}
print json_encode($rows);
or you can try... $rows = $result->fetch_all(MYSQLI_ASSOC);
mysqli_query() will return a mysqli_result, you need to fetch (as an array in this case) your rows before doing anything with them. Added a line:
// Create connection
$mysqli = new mysqli("localhost","user", "pass", "db");
// Check connection
if($mysqli->connect_errno){
$result = "Failed to connect to MySQL: " . mysqli_connect_error();
print_r( json_encode($result) );
return false;
}
// Get a mysql_result
$row = $mysqli->query("SELECT * FROM users");
// Get it into an array without numeric indexes
$result = $row->fetch_assoc();
// Display the row
print_r( json_encode($result) );

Categories