The following code does show anything in the browser . All the database name and table name are correct . While adding a line echo json_encode($temp) in the while loop displays result as objects.
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'sample_userdata');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
$stmt = $conn->prepare("SELECT questions FROM sample_questions;");
$stmt->execute();
$stmt->bind_result($post);
$userdata = array();
while($stmt->fetch()){
$temp = array();
$temp['questions'] =$post;
array_push($userdata,$temp);
}
echo json_encode($userdata);
?>
When you use json_decode() function it creates object for array with keys
$x['test1'] = 1;
$x['test2'] = 2;
echo json_encode($x);
// Result: {"test1":1,"test2":2}
You can remove keys using array_values()
$x['test1'] = 1;
$x['test2'] = 2;
echo json_encode(array_values($x));
// Result: [1,2]
Related
I'm trying to convert timestamp from my mysql table in to normal time.
I've tried looking for information on the internet but there is only solutions for timestamps that you entered by hand
<?php
//setting header to
header('Content-Type: application/json');
//database
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'bitcoin');
//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = sprintf("SELECT Kaina, Laiko_Kodas FROM localbtc LIMIT 200");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row /*("SELECT date_format(Laiko_Kodas) FROM localbtc")*/;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data);
while($row = $result->fetch_assoc()) {
$data = array();
$data2[]= $row['Kaina'];
$datetime=$row['Laiko_Kodas'];
$data2[] = date('M j Y g:i A', strtotime($datetime));
$dtata[]=$data;
}
Try the following code:
<?php
//setting header to
header('Content-Type: application/json');
//database
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'bitcoin');
//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = "SELECT Kaina, Laiko_Kodas FROM localbtc LIMIT 200";
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$row['Laiko_Kodas'] = date('H:i:s', strtotime($row['Laiko_Kodas']));
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data);
I am trying to add some code to the sample below, that will allow a "Record Not Found" error to be generated - if a record is not found:
<?php
header('Content-type=application/json; charset=utf-8');
//database constants
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'test');
//connecting to database and getting the connection object
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
//Checking if any error occured while connecting
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
$stmt = $conn->prepare('SELECT * FROM donor WHERE city =? AND gender=? AND
bloodgroup=? AND age=?;');
$stmt->bind_param('ssss',$_GET['city'],$_GET['gender'],$_GET['bloodgroup'],$_GET['age']);
$stmt->execute();
//binding results to the query
$stmt->bind_result($id, $name, $gender, $city, $contact, $bloodgroup,$age);
$donors = array();
//traversing through all the result
while($stmt->fetch()){
$temp = array();
$temp['id'] = $id;
$temp['name'] = $name;
$temp['gender'] = $gender;
$temp['city'] = $city;
$temp['contact'] = $contact;
$temp['bloodgroup'] = $bloodgroup;
$temp['age'] = $age;
array_push($donors, $temp);
}
//displaying the result in json format
echo json_encode($donors);
?>
Where would you suggest I put the code to enable the "error not found" error?
You can use $stmt->num_rows or you can check it with below code
if (empty($donors)) {
echo json_encode(array('msg' => 'Record Not Found'));
}else{
echo json_encode($donors);
}
I currently downloaded MAMP on my mac and imported an SQL file containing 589 products with their own product_id.
That worked fine and I can see all the products in "Browse".
I then tested the connection to this db. That worked aswell.
DEFINE('DB_USERNAME', 'root');
DEFINE('DB_PASSWORD', 'root');
DEFINE('DB_HOST', 'localhost');
DEFINE('DB_DATABASE', 'testproducts');
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (mysqli_connect_error()) {
die('Connect Error ('.mysqli_connect_errno().')'.mysqli_connect_error());
}
echo 'Connected successfully.';
I then tried to fetch all the products to see if that worked by creting a variable $num to see how many got fetched, but then I only get 295 products with this code:
$res = $mysqli->query("SELECT * FROM ac_product");
$num = 0;
foreach ($res as $r) {
$row = mysqli_fetch_array($res);
$pid = $row['product_id'];
echo "</br>". $pid;
$num++;
}
echo "total: ".$num;
$mysqli->close();
Am I missing something from this? Thought this would just fetch all and not have a limit.
Anyone who have some knowledge of this? Thanks
Here is my simple php code:
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "********"; //hiding my password
$dbname = "course";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name FROM tutors";
$result = $conn->query($sql);
if( $result === true ) {
echo "good";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
while($row = $result->fetch_assoc()) {
echo $row["name"];
}
?>
</body>
</html>
In my database called "course", I have a table called "tutors" which has a column called "name". I have two entries in that table with the names "deep thought" and "pyrenees" respectively.
When this code runs however, the only thing that prints out is:
Error: SELECT name FROM tutors
It is supposed to simply print out the two names that I mentioned before.
Does anyone know why this happens? I know for a fact that I have the two entries in my table!
I think the word "name" is a MySQL reserved word. Wrap your query variables in a tilde backticks like this:
$sql = "SELECT `name` FROM `tutors`";
This helps to escape those values from MySQL thinking you're trying to referencing a built in variable.
Why not use mysqli like so:
function getFollowers($link, $userid)
{
$sql = "SELECT users.id, username, profileImg FROM following INNER JOIN users ON users.id = following.userid WHERE followid = " . $userid;
$result = mysqli_query($link,$sql);
$resultsArray = [];
while($row = mysqli_fetch_assoc($result)) {
$resultsArray[] = $row;
}
mysqli_free_result($result);
return $resultsArray;
}
This is just a clean example, I am sure you get the idea.
Here is what $link is
function connection()
{
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_NAME', 'databaseTable');
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
return $link;
}
Or without the methods:
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_NAME', 'databaseTable');
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT name FROM tutors";
$result = mysqli_query($link,$sql);
$resultsArray = [];
while($row = mysqli_fetch_assoc($result)) {
echo $row["name"];
}
mysqli_free_result($result);
To check if the query was successful you can do this:
if (mysqli_num_rows($result) > 0)
{
//has rows, so whatever you want with them.
}
You put the condition after defining $result.
I set up my localhost, I have all my relevant files in place. I run the php where I run the sql query, it returns NULL values. But it should not. I visit to the directory of the link via browser.
Can someone point me in the return direction, why it is returning NULL? I ran the SQL query, and works fine on my phpmyAdmin
<?php
header('Content-Type: application/json');
define('DB_HOST', '127.0.0.1');
define('DB_USERNAME', 'myusername');
define('DB_PASSWORD', 'Ihavenopassword');
define('DB_NAME', 'mytablename');
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
//$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = sprintf("SELECT playerid, score FROM score ORDER BY playerid");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data);
$result is not what you expect. You need to fetch every item, with fetch_assoc for example:
//loop through the returned data
$data = array();
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}