How to get data from MySQL with PHP - 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);

Related

Error is Trying to get property 'id' of non-object, but seems object has

I am using PHP for 1st time.
I am just trying to fetch data from database. Here is my code -
try{
///try to connect with database
$conn=new PDO("mysql:host=localhost:3306;dbname=try", "root", "abcdef12");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex){
echo "error";
}
$mysqlcode="SELECT * FROM users";
$ret=$conn->query($mysqlcode);
foreach($ret as $ret1)
print $ret1->id;
in the browser,
showing this error:
Notice: Trying to get property 'id' of non-object in /opt/lampp/htdocs/secAsite/verifylogin.php on line 44
In the users table, I have 4 data.
In here, why $ret seems non object. I can't find anything wrong. How to fetch data. Or debug the object.
I have checked your code. Everything is fine. Just do this.
foreach($ret as $ret1)
print $ret1['id'];
You are not getting data because you are not fetching it..
you have to fetch the data before print it
updated code
$mysqlcode = "SELECT * FROM users";
$ret = $conn->query($mysqlcode);
if ($ret->num_rows > 0) {
// output data of each row
while($row = $ret->fetch_assoc()) {
echo "id: " . $ret["id"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
that'll work fine.
Before trying to use Object Oriented PHP, is much easier to understand Procedural. Take a look at the code below.
First, connect to database:
<?php
//Store log in info into variables
$servername = 'localhost';
$serveruser = 'youruser';
$serverpassword = 'yourpassword';
$serverdatabase = 'yourdatabase';
// Create connection
$conn = mysqli_connect( $servername, $serveruser, $serverpassword, $serverdatabase );
if ( !$conn ) {echo "Connection Fail" . mysqli_connect_error();}
//else {echo "Connected to database $serverdatabase";}
?>
Then, call the information from your database and your table and store it into an associative array $data
$sql = "SELECT * FROM `table`";
$result = mysqli_query($conn, $sql);
$data = mysqli_fetch_all($result, MYSQLI_ASOCC);
mysqli_free_result($result);
Now you can use the array to print the results with print_r
echo '<pre>'; print_r($data); echo '</pre>';}
Now you are ready to use foreach depending on your table columns,for example if you have ID column then
<?php foreach ($data as $value){
echo $value['id]."<br>";
} ?>
It will print out all the IDs. Hope this helps.

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).

json_encode and json_decode in mySql misunderstanding

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?

JSON output from MySQL works, but then white screen appears?

I've used the below code to generate JSON from a MySQL table. It works great when I'm only generating 2 arrays, but for some reason when I try and generate 3 or 4 arrays, I get the "white screen of death". I thought it was happening because I needed to bump up my PHP Memory Limit, but I've done that and still get the same problem. See below:
The code that works is:
<?php
//Create Database connection
$db = mysql_connect("localhost","user","dbpassword");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("dbname",$db);
//Replace * in the query with the column names.
$result = mysql_query("select * from customer", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['customerfname'] = $row['customerfname'];
$row_array['customerlname'] = $row['customerlname'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db);
?>
But when I attempt to call more values, this is where I get the blank screen:
<?php
//Create Database connection
$db = mysql_connect("localhost","user","dbpassword");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("dbname",$db);
//Replace * in the query with the column names.
$result = mysql_query("select * from customer", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['customerfname'] = $row['customerfname'];
$row_array['customerlname'] = $row['customerlname'];
$row_array['customeremail'] = $row['customeremail'];
$row_array['customertel'] = $row['customertel'];
//push the values in the array
array_push($json_response,$row_array);
}
var_dump($json_response);
echo json_encode($json_response);
?>
Update**
The error appears to be with my last line (echo json_encode ($json_response);
The following output is generated when I add print_r($row) before that last line.
Array ( [id] => 1 [customerfname] => First [customerlname] => Last [customeremail] => test#test.com [customerphone] => 000-000-0000
Update 2
Adding var_dump($json_response); before the echo json_encode line results in the blank screen.
For future reference: If someone else is visiting this question due to having a similar problem, the error with the blank page occurred since the query returned too many rows and json_encode() did not seem to be able to handle it.
Try the following, and share with us your result,
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
//Create Database connection
$db = mysql_connect("localhost","user","dbpassword");
if (!$db)
die('Could not connect to db: ' . mysql_error());
mysql_select_db("dbname",$db);
mysql_query('SET CHARACTER SET utf8');
$result = mysql_query("select `customerfname`, `customerlname`, `customeremail`, `customertel` from customer", $db) or die("Error: ".mysql_error());
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$json_response[] = $row;
}
var_dump($json_response);
/* If the var_dump works, you can try and uncomment this section
if (function_exists('json_encode'))
{
echo json_encode($json_response);
echo "JSON Error: ".json_last_error();
}
else { echo "json_encode() is not supported"; }
*/
?>
When you use flcose($db) that is going to cause some trouble. remove that line.
flcose is used to close ressources such as writing to text files.
to close connection use mysql_close():
mysql_close($db);
and also Your loop can be reduce to this:
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
//push the values in the array
array_push($json_response,$row);
}
//Close the database connection
mysql_close($db);
echo json_encode($json_response);
and I would probably echo the json after closing the connection but thats no biggie.
And I find white screen of death very funny :D

Categories