echo json_encode after mysql_query failure - php

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

Related

Php postgresql error, prepared statement already exists

Am getting an error of prepared statement "my_query7" already exists, i call this function each time a user tries to update table leader_info in the database, i have gone through the documentation for pg_prepare and i don't understand what is meant by it should only be run once. code snippets will be of help. Thanks.
function add_leader_country($user_id,$l_country)
{
global $connection;
$query = pg_prepare($connection,"my_query7","update leader_info set l_country = $1 where user_id = $2 and status < 9");
$result = pg_execute($connection,"my_query7",array($l_country,$user_id));
if(!$result)
{
echo pg_last_error($connection);
}
else
{
echo "Records created successfully\n";
}
$row = pg_affected_rows($result);
return $row;
}
Prepare execute does not permit duplicate naming, so that is your error.
A query should only be prepared once, for example, in a cycle for the preparation state must be set out of the for and its execution in the for.
$result=$pg_prepare($connection,"my_query7",$query);
for($id=1;$id<3;$id++){
$result=pg_execute($connection,"my_query7",array($l_country,$user_id));
...
}
In your case using a functio that use the prepare and execute multiple times it's a problem.
What are you trying to accomplish with this function dispatches more code like where you are calling the function. This way I might be able to help you.
If you want to use functions I would use this method
Exemple from https://secure.php.net
<?php
function requestToDB($connection,$request){
if(!$result=pg_query($connection,$request)){
return False;
}
$combined=array();
while ($row = pg_fetch_assoc($result)) {
$combined[]=$row;
}
return $combined;
}
?>
<?php
$conn = pg_pconnect("dbname=mydatabase");
$results=requestToDB($connect,"select * from mytable");
//You can now access a "cell" of your table like this:
$rownumber=0;
$columname="mycolumn";
$mycell=$results[$rownumber][$columname];
var_dump($mycell);
If you whant to use preaper and execute functions try to create a function that creates the preparations only once in a session. Do not forget to give different names so that the same error does not occur. I tried to find something of the genre and did not find. If you find a form presented here for others to learn. If in the meantime I find a way I present it.

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.

json encoding not working in mysql fetch array

$return_arr = array();
$fetch = mysql_query("select `menu_item_name` from menu_option");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['id'] = $row['menu_item_name'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
Change this:
From
array_push($return_arr,$row_array);
To
$return_arr = array_push($return_arr,$row_array);
Run your SQL first and ensure that what you're getting back is in fact a result.
This can be done by either running
select menu_item_name from menu_option
manually in mysql shell or through something like MySQL Workbench.
Also, a print_r($return_arr) won't hurt to debug the issue you're having as the code itself should work fine. JSON_ENCODE works. The problem you're having is that you don't have an array.
Side note: It's better to use some form of ORM instead of writing low-level SQL for yourself. Have a look into Doctrine, Propel or Redbean, and save yourself some headaches.

How to make query into arrays?

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.

Passing PHP MySQL Result Object to Function

I'm trying to take a MySQL result row and pass it to a function for processing but the row isn't getting passed. I'm assuming this is because the actual row comes back as a object and objects can't get passed to function?
E.G
function ProcessResult($TestID,$Row){
global $ResultArray;
$ResultArray["Sub" . $TestID] = $Row["Foo"] - $Row["Bar"];
$ResultArray["Add" . $TestID] = $Row["Foo"] + $Row["Bar"];
}
$SQL = "SELECT TestID,Foo,Bar FROM TestResults WHERE TestDate !='0000-00-00 00:00:00'";
$Result= mysql_query($SQL$con);
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
$nRows = mysql_num_rows($Result);
for ($i=0;$i<$nRows;$i++)
{
$Row = mysql_fetch_assoc($Result);
$TestID = $Row[TestID];
ProcessResult($TestID,$Row);
}
}
What I need is $ResultArray populated with a load of data from the MySQL query. This isn't my actual application (I know there's no need to do this for what's shown) but the principle of passing the result to a function is the same.
Is this actually possible to do some how?
Dan
mysql_query($SQL$con); should be mysql_query($SQL,$con); The first is a syntax error. Not sure if this affects your program or if it was just a typo on here.
I would recommend putting quotes around your array keys. $row[TestID] should be $row["TestID"]
The rest looks like it should work, although there are some strange ideas going on here.
Also you can do this to make your code a little cleaner.
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
while($Row = mysql_fetch_assoc($Result))
{
$TestID = $Row['TestID'];
ProcessResult($TestID,$Row);
}
}
mysql_fetch_assoc() returns an associative array - see more
If you need an object, try mysql_fetch_object() function - see more
Both array and object can be passed to a function. Thus, your code seems to be correct, except for one line. It should be:
$Result= mysql_query($SQL, $con);
or just:
$Result= mysql_query($SQL);

Categories