How to make query into arrays? - php

I'm using this code to gather information from database
$webdata = "SELECT * FROM `settings`";
if (!$web_data = $db_connect->query($webdata)) {
die('Oops, something went wrong during loading data! Error x010');
}
but now I would liek to display it like arrays so taht I can just simply use this code:
<?php echo $web_data['web_name']; ?
to display the information

Since you tagged this mysqli, you need to fetch the results into an array.
You can do so with mysqli's fetch_assoc():
$webdata = "SELECT * FROM `settings`";
if (!$web_data = $db_connect->query($webdata)) {
die('Oops, something went wrong during loading data! Error x010');
}
while ($row = $web_data->fetch_assoc()) {
echo $row['web_name'];
}

Echo will just send Array text in response.
To send an array use print_r function.

Related

Pass variables in url to get specific JSON output

I'm attempting to create an api, I'm currently trying to append variables to the url to get specific data back in the JSON output.. I can currently display all contents of a table. Any advice would be appreciated.. Please see code below...
$connection = #mysqli_connect($server, $user, $password, $bd);
if( ! $connection ) die( "Error ".mysqli_connect_error() );
$sql = "SELECT * FROM posts";
$result = mysqli_query($connection, $sql);
$array_post = array();
while($data = mysqli_fetch_assoc($result)){
$array_post[] = $data;
}
echo json_encode($array_post);
You probably mean an api response after a POST or GET Request? Am I right?
If it is, then you can do this...
$response = $array_post;
http_response_code(200);
print json_encode($response);
You need a stream to output the JSON data, you can set the HTTP status code by http_response_code($code) function and then print the response.
There are packages out there that could handle api request and response.
I suggest you take a look about Curl or much better the GuzzleHttp.
Hope it helps.
You can store particular values return from SQL query to array keys like this
while($data = mysqli_fetch_assoc($result)){
$array_post['key2'][] = $data['key2'];
$array_post['key2'][] = $data['key2'];
}
echo json_encode($array_post);
Use only those values which you required to pass in URL.
If you need all the records then your code is right.
If you are thinking about some records then change your query to
like SELECT field1,field2 FROM table_name.
because some times it will affect performance of executing SQL query.

echo json_encode after mysql_query failure

I'm currently trying to develop an Android app that communicates with a database. I use php scripts to communicate between my app and the database.
For error handling purposes, I was wondering if I could replace the die() function in php with something simliar to json_encode so that I can send an error code to my app.
mysql_query(/*the query*/) or /* something like echo json_encode*/
EDIT: here's an example of what I usually use,
$response['error1'] = "error in select query";
$result = mysql_query("SELECT id_product FROM `product`where id_category=$id_category") or die(mysql_error());
I tried something like:
$result = mysql_query("SELECT id_product FROM `product`where id_category=$id_category") or die(echo json_encode($response));
It doesn't work and I would like to know whether there is something else I can use.
Thanks for your help.
You can use an if on the result. If mysql_query() fails it returns false:
$result = mysql_query(/*the query*/);
if(!$result){
//Do stuff here, the query failed
//json_encode()
} else {
//Query succeeded
}
Sidenote: mysql_* is deprecated, I highly recommend to switch to mysqli_* or PDO
Try this code.it generate the JSON array loginsession
$return_arr = array();
//here start while loop for Mysql
$row_array['uid']=$uid;
$row_array['uname']=$uname;
$row_array['email']=$email;
$row_array['phone']=$phnumb;
$row_array['birthday']=$dob;
$row_array['address']=$address;
array_push($return_arr,$row_array);
// end your while loop
echo json_encode(array('loginsession' => $return_arr));

how to loop through PHP code and MySQL?

How do I use the PHP loop through the query instead of putting all the result into an array then looping through the array
The way I use array and loop is like this:
<?php $userInfos = $qry->querySelect( SQL CODE HERE );
foreach($userInfos as $uInfo)
{
$fName = $uInfo['fName'];
$lName = $uInfo['lName'];
$gender = $uInfo['gender'];
?>
First name is: <? echo $fName; ?> and Last name is <? echo $lName; ?>.
<?php } ?>
I wanted to know better insight on how PHP loop through the query is better than array. Please redirect me to some example or possibly with MySQL code included.
How can I convert the above php code to be more efficient if I am pulling millions of record?
Thanks so much!.
You can do a simple loop with mysqli_fetch_row()
http://php.net/manual/en/mysqli-result.fetch-row.php
It looks like you need to use something other than the querySelect function (which appears to be returning an array).
Maybe the $qry object has some other function that will return you a statement handle you can fetch from, like the normal mysqli_ and PDO interfaces provide.
It looks to me like $qry is from a homegrown MySQL library "wrapper" class, which exposes a limited subset of the functions. If that object doesn't provide a way to get a statement handle, you may need to add the appropriate functions to the object definition, or abandon that and just use mysqli or PDO.
There's lots of examples of how to do that. With PDO, our first cut (before we add error checking and exception handling) might look something like this:
$sql="SELECT t.name FROM really_big_table t";
$sth=$dbh->prepare($sql);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC) ) {
echo "<br>Name is: ". htmlentities($row['name']);
}
$sth->close();
Reference: http://php.net/manual/en/pdostatement.fetch.php
I do the following:
//DB Query getData
$q_getData = "SELECT `stuff`, `moreStuff`, `otherStuff` FROM `table`";
$rsgetData = mysqli_query($DBi, $q_getData) or die(mysqli_error($DBi));
$row_rsgetData = mysqli_fetch_assoc($rsgetData);
$rows_rsgetData = mysqli_num_rows($rsgetData);
if($rows_rsgetData>0) {
do {
echo $row_rsgetData['stuff'] . ' ' . $row_rsgetData['moreStuff'] . '<br>';
echo $row_rsgetData['otherStuff'];
} while ($row_rsgetData = mysqli_fetch_assoc($rsgetData));
$rows = mysqli_num_rows($rsgetData);
if($rows > 0) {
mysqli_data_seek($rsgetData, 0);
$row_rsgetData = mysqli_fetch_assoc($rsgetData);
}
mysqli_free_result($rsgetData);
};
That runs the query and loops through each row until there are no rows left - only if there are rows returned in the first place. Once it's all finished it frees up the connection.

empty() not working when mysql is fetching array

Not sure why this isnt working. I'm assuming it's because i am fetching an array but not sure why that would stop it.
Heres the code anyhow;
<?php
include ("../database.php");
$result = mysql_query("SELECT * FROM gigs WHERE artisturl='$artistname'");
while($row = mysql_fetch_array($result)){
if (empty($row['gigname'])){echo '<p2>'.$row['artistname']. 'has not posted any gigs yet. Check back later.</p2>';}
else {
echo $row['gigname'].$row['venue'].$row['lineup'].$row['date'].$row['time'].$row['price'].$row[' purchase'].'<br><br>';}}?>
Not sure why this isnt working
You've not stated what your criteria for 'working' are.
Your code doen't make any sense. empty() is not the right function to use here - indeed there is no function which will work here because if there are no matching records then the body of the loop will never execute.
There are lots of ways to deal with the scenario. Here's a simple one:
if (mysql_num_rows($result)) {
while($row = mysql_fetch_array($result)){
echo ....
}
} else {
echo '<p2>'.$row['artistname']. 'has not posted any gigs...'
}
Empty has unexpected results with strings, i'd suggest you read this article.
For example :
$mystring = '0';
if (empty($mystring)) {
// this code will run
// what if this was code to take action when $mystring is undefined?
}
So make sure gigname is not 0.
Consider using is_null($row['gigname']))

Get JSON data FROM a PHP/MySQL query into a html tag using jquery

Hi guys I´m new at stackoverflow and also new at Jquery
Well hope I can make myself understandable. Here is what I want: I have made a query to my MySQL db, using a class with PHP
public function User($id) {
$this->connect_db_web($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='".$id."'");
while ($values = mysql_fetch_array($sql)) {
$arr[]=array(
'id'=>$values['idUsers'],
'name'=>$values['name'],
'name2'=>$values['name2'],
'lname'=>$values['lname'],
'lname2'=>$values['lname2'],
'email'=>$values['email'],
'phone'=>$values['phone'],
'address'=>$values['address'],
'bday'=>$values['bday'],
'password'=>$values['password']
);
}
echo '{"user":'.json_encode($arr).'}';
}
Then I have a php code where I call this function
$name = $user->User($id);
I think this works ok (if I´m wrong please help). Now what I´m really trying to do is getting the values from the JSON array into specific divs, example:
$.getJSON("user.php",function(data){
$.each(data.user, function(i,user){
name = user.name;
$(name).appendTo('#getname');
});
});
And inside my HML i Have a <p id="getname"></p>wich is the tag I want the value to be displayed
But no value is displayed, why?, what am I doing wrong?
Thanks for the help I apreciate it
Your JSON is malformed. You are appending a bunch of objects {.1.}{.2.}{.3.}. Instead, try {"users":[{.1.},{.2.},{.3.}]}.
In PHP you'll do something like this (note that I've changed the response type to JSON-P rather than JSON by adding a callback parameter):
public function User($id) {
$users = array();
$this->connect_db_web($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='".$id."'");
while ($values = mysql_fetch_array($sql)) {
$users[] = array(
'id'=>$values['idUsers'],
'name'=>$values['name']
// etc.
);
}
$obj['users'] = $users;
$callback = (empty($_GET["callback"])) ? 'callback' : $_GET["callback"];
echo $callback . '(' . json_encode($obj) . ');';
}
Then you'll be able to do:
$.getJSON("user.php?callback=",function(data){
$.each(data.users, function(i,user){
$('#getname').append(user.name);
});
});
probably safer to do like this:
echo json_encode(array("user" => $arr));
on the other end you would receive an object which, I would suggest iterating like this:
var k;
for (k in data.user){
$("#getname").append($("<span></span>").html(data.user[k].name));
}
Given that you are fetching information for one user only, following I would suggest
$id = (int) $_GET["id"]; // or wherever you get it from.
if ($r = $db->mysql_fetch_assoc()){
$response = array(
"name" => $r["name"];
);
echo json_encode($response);
} else {
echo json_encode(array("error" => "Could not get name for user " . $id));
}
Then, on front-end, all you need to do is:
if (typeof(data.name) != "undefined"){
$("#getname").html(data.name);
} else if (typeof(data.error) != "undefined"){
$("#getname").html(data.error); //or handle otherwise
}
You've misinterpreted your JSON structure. You're appending your DB rows to an array, and embedding that inside an object. If you'd do a console.log(user) inside your .getJSON call, you'd see you'll have to do:
user[0].name
instead. As well, your code assumes that the user ID exists, and returns data regardless of how many, or how few, rows there actually are in the result set. At minimum your JS code code should check users.length to see if there ARE are any rows to begin with. Beyond that, unless you're doing it in another section of code somewhere, that $id value is probably coming from the web page, which means your query is vulnerable to SQL injection attacks.
OK got it,
was a php code error and JSON structre as marc said, here I´m gonna post what finally I had
PHP Class
public function User() {
$users = array();
$this->connect($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='1'");
$values = mysql_fetch_array($sql);
$users[] = array(
'id'=>$values['id'],
'name'=>$values['name'],
'name2'=>$values['name2'],
'lname'=>$values['lname'],
...//rest of values
);
echo json_encode($users);
}
PHP module to get class
include"class.php";
$user = new Users();
$user->User();
Now how did I got the values using JQuery
$.getJSON('user.php', function(data){
$('wherever_you_want_to_point_at').text(data[0].name);
});
Hope it helps someone,
Thanks again guys, very very helpful
Take care you all

Categories