Remove unnecessary brackets in php array - php

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;
}

Related

Getting values from JSONarray

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

I can't get any data output from the database, i only get "0 results" as the else statement, what's the case?

I'm having some troubles with fetching some database information with my php code.
All I'm getting is this message: "Connected successfully0 results".
Here's my code guys, thanks for the help in advance.
<?php
$servername = "example";
$username = "example1";
$password = "example2";
$row = array();
$conn = new mysqli($servername,$username,$password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "Select Distinct subject from mobile_math_science_toc";
$result = mysqli_query($conn, $sql);
if ($result = $conn->query($sql)) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Subject " ,$row["subject"];
}
} else {
echo "0 results ";
}
mysqli_close($conn);
?>
You should add dbname while creating your connection to database. You can use mysqli_num_rows function to count no. of rows.
<?php
$servername = "example";
$username = "example1";
$password = "example2";
$dbname = "your_db_name"; // Specify your db-name here.
$conn = new mysqli($servername,$username,$password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "Select Distinct subject from mobile_math_science_toc";
$result = mysqli_query($conn, $sql);
// Checking if there are some records available.
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Subject " ,$row["subject"];
}
} else {
echo "0 results ";
}
mysqli_close($conn);
?>
Change
$conn = new mysqli($servername,$username,$password);
To
$conn = new mysqli($servername,$username,$password, "<your database name>");
And
$result = mysqli_query($conn, $sql);
if ($result = $conn->query($sql)) {
}
To
$result = $conn->query($sql);
if ($result) {
}
Try
if (mysqli_num_rows($result) > 0) {
While checking you got the data or not

MySQLI LOOP DATA

I want to get all the records from the while loop. I'm unable to get all the rows from the query. It shows only the first row.
Is there anything I was going wrong in my code.
function Connect($DB_HOST = 'localhost', $DB_USER = 'root', $DB_PASS = '', $DB_NAME = 'bodhilms')
{
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
return $mysqli;
}
function GetCoeficient($coeficient = false, $con)
{
if(!$con)
return 0;
$result = array();
$sql[] = "SELECT * FROM users ";
if($coeficient != false)
$sql[] = "WHERE username = '".$coeficient."' ORDER BY u.id";
//print_r($coeficient);
$query = $con->query(implode(" ",$sql));
//print_r($query);
while($row = $query->fetch_assoc())
{
$result[] = $row;
}
return (!empty($result))? $result : 0;
}
$con = Connect();
$result = GetCoeficient($coeficient,$con);
$username = $result[0]['username'];
$firstname = $result[0]['firstname'];
$lastname = $result[0]['lastname'];
$email = $result[0]['email'];
First of all,to make sure the infomation of mysql is right,like port.
and I wonder the code of you $result = Getcourse($coeficient,$con);, how the var coeficient come from.Then
You can try the code below:
$mysqli=new mysqli("localhost","root","root","123");
$query="select * from test";
$result=$mysqli->query($query);
if ($result) {
if($result->num_rows>0){
while($row =$result->fetch_array() ){
echo ($row[0])."<br>";
echo ($row[1])."<br>";
echo ($row[2])."<br>";
echo ($row[3])."<br>";
echo "<hr>";
}
}
}else {
echo 'failure';
}
$result->free();
$mysqli->close();

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

Multi URL paramaters with PHP and SQL

<?php
$username = "username";
$password = "password";
$hostname = "localhost";
$database = "database";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($database,$dbhandle)
or die("Could not select database");
$id = 0;
if(isset($_GET['Day'])){ $id = (int)$_GET['Day']; }
if(!$id){
$query = "SELECT * FROM `TimeTable`";
} else {
$query = "SELECT * FROM `TimeTable` WHERE `Day`='".$id."'";
}
$result = mysql_query($query);
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
or die(mysql_error());
print json_encode($rows);
?>
This code worked previously, but has now stopped, and is producing Parse error: syntax error, unexpected T_LOGICAL_OR in /Directory/TimeTable.php on line 27
I am also looking to add more parameters, (eg: Where Day = $id and Year = $Year )
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
or die(mysql_error());
This is a syntax error, doesn't know what to do with that or die() statement. Change to this:
$result = mysql_query($query);
if (!$result) {
die('Error');
}
while(...) {
}
I have looked up the new mysql functions an have changed to mysqli.
<?php
$username = "username";
$password = "password";
$hostname = "localhost";
$database = "database";
$link = mysqli_connect($hostname, $username, $password, $database);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
$id= 0;
if(isset($_GET['Day'])){ $id=(int)$_GET['Day']; }
$year = 0;
if(isset($_GET['Year'])){ $year=(int)$_GET['Year'];}
if(!$id){
$query = "SELECT * FROM TimeTable";
} else {
if (!year) {
$query = "Select * FROM TimeTable";
} else {
$query = "SELECT * FROM TimeTable WHERE Day=$id AND Year=$year";
}
}
$rows = array();
//Perform JSON encode
if($result = mysqli_query($link, $query)){
while($r = mysqli_fetch_assoc($result)){
$rows[] = $r;
}
}
print json_encode($rows);
?>

Categories