Getting values from JSONarray - php

I am writing a PHP script which
connects to the database
fetches all orders in an array. ($result)
I want to go through the array and fetch all say "userName"
The trouble is, with my code below, I am able to only get the first character of each "userName" in the array.I want an array with all "userName"s.
<?php
$dbhost = 'localhost';
$dbuser = 'user';
$dbpass = 'password';
$dbname = 'dbname';
//Create database connection
$dblink = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$sql = "select * from ordertest";
$retval = mysqli_query($dblink, $sql) or die(mysqli_error($dblink));
$result = mysqli_fetch_array($retval, MYSQLI_ASSOC);
if (mysqli_num_rows($retval) > 0) {
$arr = json_decode($result, true);
foreach ($result as $key => $value) {
echo $value["userName"];
}
} else {
echo $sql;
}

The solution should be next:
<?php
$sql = "select * from ordertest";
// retrieve query result from DB
$retval = mysqli_query($dblink, $sql) or die(mysqli_error($dblink));
// if result not empty
if (mysqli_num_rows($retval) > 0) {
// retrieve single row from $retval
while ($result = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
echo $result["userName"];
echo "\n";
}
} else {
echo $sql;
}
Look example here: PHPize.online

Related

echo something out MySQL database

I am trying to get a question with answers out of my database. I just want to get one thing out of the database and not with a row. I thought this would work but it puts out this: Resource id #4 can someone explains what I am missing.
Thanks :)
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db('lotto');
$sql = 'SELECT id, vraag, AntwA, AntwB, AntwC, AntwD FROM vraag1';
$test = mysql_query($sql);
echo $test;
?>
As said at least 10000 times everywhere in internet, never use MySQL_ ! (If your are trying to learn something new by using tutorials over internet, don't use old ones)
I recommend to use PDO which is modern API in PHP and a lot more secure when using it correctly with prepared statement ! But you can also use MYSQLI which is more similar to the MYSQL !
You have to export your data from return array :
Using PDO :
$db = new PDO ("mysql:host=".$hostname.";dbname=".$dbname, $username, $password);
$query = $db -> prepare ("SELECT * FROM vraag1");
$query -> execute (array ());
$rows = $query -> fetchAll (PDO::FETCH_ASSOC);
foreach ($rows as $row)
{
echo $id = $row["id"];
echo $vraag = $row["vraag "];
echo $AntwA = $row["AntwA "];
echo $AntwB = $row["AntwB "];
echo $AntwC = $row["AntwC "];
echo $AntwD = $row["AntwD "];
}
Using MYSQLI :
$db = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$query = "SELECT * FROM vraag1";
$rows = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($rows))
{
echo $row["id"];
echo $row["vraag"];
echo $row["AntwA"];
echo $row["AntwB"];
echo $row["AntwC"];
echo $row["AntwD"];
}
First of all the mysql function you are using is depreciated and no longer supported. you should use mysqli or pdo instead with prepared statements.
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "lotto";
// Create connection
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, vraag, AntwA, AntwB, AntwC, AntwD FROM vraag1";
$test = mysqli_query($conn, $sql);
if (mysqli_num_rows($test) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($test)) {
echo "ID : ".$row['id']."<br>";
echo "vraag :".$row['vraag']."<br>";
echo "AntwA :".$row['AntwA']."<br>";
echo "AntwB :".$row['AntwB']."<br>";
echo "AntwC :".$row['AntwC']."<br>";
echo "AntwD :".$row['AntwD']."<br>";
}
} else {
echo "no results found";
}
mysqli_close($conn);
?>
For select function mysql_query() returns a resource on success, or FALSE on error.
so your assignment statement
$test = mysql_query($sql);
assign the resource to $test.
if you want the data inside the resource you can do
while($row= mysql_fetch_assoc($test)):
print_r($row);
endwhile;
also you can access the $row['column_name']
If you want to return only one row you can do this limit in query
$sql = 'SELECT id, vraag, AntwA, AntwB, AntwC, AntwD FROM vraag1 limit 1';
You need to add something like the following:
while($row = mysql_fetch_array($result)){
echo $row['id'];
echo $row['vraag'];
echo $row['AntwA'];
echo $row['AntwB'];
echo $row['AntwC'];
echo $row['AntwD'];
}
use mysqli instead of mysql
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
mysqli_select_db('lotto');
$sql = 'SELECT id, vraag, AntwA, AntwB, AntwC, AntwD FROM vraag1';
$test = mysqli_query($sql);
echo $test;
?>

PHP Insert Values from 1 Array into another Array at a specific point

I have an Associative Array called $sqldata. This array looks like:
{"assignment":"1","grade":"11.00000"}
My Code:
function displayfetchAssignGrades($sqldata) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "moodle";
$sqlr = array();
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
foreach ($sqldata as $x => $sqld) {
$sqlqueryinfo = $sqld;
$sql = "SELECT name FROM mdl_assign WHERE id='$sqlqueryinfo'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
$row["grade"] = $sqldata["grade"][$x];
$sqlr = $row;
}
} else {
echo "";
}
}
echo json_encode($sqlr);
mysqli_close($conn);
}
What I want is as the foreach loop iterates I want the name of the assignment received from the SQL Query and the grade (from the original $sqldata array) in another associative. The order of the grades values corresponds to the Assignment Name. So the final array should look like in JSON:
{"assignment name":"Task 1","grade":"11.00000"}
Try this:
$newArr = [];
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
$newArr[] = array(
'assignment name' => 'Task ' . $row["assignment"],
'grade' => $row["grade"]
);
}
}
$json = json_encode($newArr, true);

Remove unnecessary brackets in php array

I wrote a code to parse data in php as follows:
<?php
$db_name="hotels";
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$db_name);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
else{
//echo"<h3>Database cannection established</h3>";
}
$sql_query_for_username = "select distinct `username` from hotels.ratingoffooditem";
$usernames_result = mysqli_query($conn, $sql_query_for_username);
$users = array();
while($row=mysqli_fetch_array($usernames_result)){
array_push($users, $row["username"]);
}
//print_r($users);
$response=array();
foreach($users as $user){
$sql_query= "select `food item`,rating from hotels.ratingoffooditem where username='$user'";
$result= mysqli_query($conn,$sql_query);
$abc = array();
if($result !=false){
while($row=mysqli_fetch_array($result)){
$def = array($row["food item"]=>$row['rating']);
//echo (json_encode($def));
//echo "</br>";
array_push($abc,$def);
}
}
//echo "</br>";
//print_r(json_encode($abc));
//echo "</br>";
array_push($response, array("$user"=>array($abc)));
//echo "</br>";
}
echo json_encode($response);
//echo "</br>";echo "</br>";echo "</br>";
mysqli_close($conn);
?>
I would like to get result like:
{"Shree":{"Chiken-Momo":4,"Buff-Momo":3,"Chicken-Thukpa":3,"Chiken Momo":4,"Buff Chowmein":2.5,"Veg-Chowmein":3.5},"Juppi":{"Samosa":4},"lil":{"Chiken-Momo":1},"bidur":{"Chiken-Momo":4.5}}
But, I got this:
[{"Shree":[[{"pizza":"3"},{"Burger":"3.5"},{"Chiken-Momo":"4.5"},{"Chiken Momo":"4"},{"Chiken Momo":"4"},{"Chiken-Momo":"4"},{"Veg-Chowmien":"2"},{"Buff-Momo":"3"},{"Chiken-Thukpa":"4"},{"Chiken-Thukpa":"4"},{"Chiken-Thukpa":"2"}]]},{"Juppi":[[{"Samosa":"4"},{"Chiken-Momo":"4"}]]},{"lil":[[{"Chiken-Momo":"1"}]]},{"bnabin51":[[{"Chiken-Momo":"4.5"}]]},{"bidur":[[{"Chiken-Momo":"4.5"}]]}]
Now how can i remove the unnecessary brackets?
Finally i got this simply as follows:
$response=array();
foreach($users as $user){
$sql_query= "select `food item`,rating from hotels.ratingoffooditem where username='$user'";
$result= mysqli_query($conn,$sql_query);
$abc = array();
if($result !=false){
while($row=mysqli_fetch_array($result)){
$abc[$row['food item']]=$row['rating'];
}
}
$response[$user]=$abc;
}

Trying to get property of non-object: Using SELECT

I got little problem with my code... because I try to SELECT sth from database and then INSERT some value to another table, but in normal code from w3school
and I got error
Tryingo to get property of non-object
Here is my code:
<?php
session_start();
function connectionDB(){
$host = "localhost";
$username = "root";
$password = "";
$db_name = "project";
$conn = new mysqli($host, $username, $password, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
function getID(){
$id = $_GET['id'];
return $id;
}
$login =$_SESSION['login'];
$conn =connectionDB();
$idCar = getID();
echo $idCar;
$sqluser = "SELECT ID_USER FROM login_table WHERE LOGIN = $login";
if($result->num_rows > 0)
$result = $conn->query($sqluser);
{
while($row = $result->fetch_assoc())
{
$sql = "INSERT INTO cart (id_user) VALUES ('".$row['ID_USER']."')";
}
}else echo"error";
?>
THIS IS THE CODE OF SIDE WITH PRODUCT
Please see change near your IF loop
$sqluser = "SELECT ID_USER FROM login_table WHERE LOGIN = $login";
$result = $conn->query($sqluser); //check result first
if($result->num_rows > 0) //get number of rows
{
while($row = $result->fetch_assoc())
{
$sql = "INSERT INTO cart (id_user) VALUES ('".$row['ID_USER']."')";
}
}else echo"error";

PHP Database output. Arrays

In first case, i will get full array:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test.com";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM articles WHERE writer='$w_name' ";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row[header];
}
}
mysqli_close($conn);
?>
In the second case, i will get just 1st value from array:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test.com";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM articles WHERE writer='$w_name' ";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$q=$row[header];
}
}
mysqli_close($conn);
?>
<div>
<? echo $q ?>
</div>
What should I do, to make 2nd case work like 1st? I mean, how to put into $q, all values of array, not just the first.
You are not defining $q as an array at all.
$q=array();
...
while ($row = mysqli_fetch_assoc($result)) {
$q[]=$row['header'];
}
...
an example of output :
foreach($q as $header) {
echo $header.'<br>';
}
You are overwriting $q . Try using $q[]=
change $q=$row[header]; line to $q[]=$row[header];
and then not echo $q; but print_r($q);
Try to change this into the while
$q = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
array_push($q, $row['header']); // i guess header is a column of the table
}
}
and then you must have your array when print the $q variable, i mean do an print_r($q)
More info about array_push: http://php.net/manual/es/function.array-push.php
Hope this helps :)

Categories