Manage empty result query in MySql with PHP for Android HttpUrlConnection - php

I am working in an Android application that is using an Apache server to recover information from a MySQL database with PHP. I do not know the proper way to manage situations where the request to the database is returning 0 records.
In this case I want to minimize as much as possible the process.
So far I can only figure out two ways:
1.- Return an specific XML format and then it is managed by the client. So when this find a specific tags knows there is not records in the database. I do not like this solution because I would like to catch the issue before I parse the XML. The PHP code for this would be something like this.
<?php
include ("common_function.php");
include("generate_DOM_XML.php");
//Make database connection
connectDB();
//set el cotejamiento
mysqli_query($mysqli,"SET NAME 'utf8'");
//sentence sql
$list_news_sql="SELECT new_title, new_body, new_create_time FROM table_news ORDER BY new_create_time DESC";
//results sql query
$list_news_sql_result = mysqli_query($mysqli, $list_news_sql) or die (mysqli_error($mysqli));
if(mysqli_num_rows($list_news_sql_result) < 1){
$message = "<empty>No records</empty>;
echo $message;
}else{
//First parmenter MUST be send AFTER the request is done
$xml_output = mysql_XML($mysqli,$list_news_sql_result,"news","new");
mysqli_free_result($list_news_sql_result);
closeDB();
echo $xml_output;
}
?>
2- Force the server to send an error message and ctach up it before I parse the xml. To make it I do not know if it is possible to use exit(400) or something like that and the capture the message in the client with HttpUrlConnection.getResponseCode() using a sentence if()....else and take a decission before I start the parsing process

Related

Get null values while trying to download a blob

I have a problem to download images stored in my Mysql database as a blob.
I tried already a lot of solutions which I found in other posts but the result is every time the same:
"[{"image":null},{"image":null},{"image":null}]"
I reduced my code more and more to get the spot as small as possible but nothing.
This is my last try which is actually a copy of this post :Empty PHP output from MySQL database for a longblob
<?php
// Create connection
$con=mysqli_connect("Server","User","Pw","DBName");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT CAST(engineerSignature as CHAR(1000000) CHARACTER SET utf8) as engineerSignature FROM tblservreport";
if ($result = mysqli_query($con, $sql)){
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
mysqli_close($con);
?>
but it also didn’t work.
Do I look on a wrong place?
I’m sure that the images are OK because I have another program on a Windows PC and on that I download it directly without the way through PHP and it works fine.
I read a lot of answers about why it’s not a good way to store an image in a DB like this but this is not my choice I have to follow this way.
I hope someone else can see what I am missing or has an idea what I can try.
you must Encode the binary data as "base64" before you generate the "JSON".
$obj = base64_encode($resultArray);
$obj_Json = json_encode($obj);
var_dump($obj_Json);
You can also try this steps to find out the errors.
instead of use echo use var_dump($resultArray) to see whats going on in that array.
upload your image then go to your mysql admin panel and see that whether file is uploaded successfully and showing as blob in the database. If not you have problem in upload files
make sure your sql query is correct.
and also your Question is not clear, so I have given you some basic tip.
OK now I know var_dump, Thank you for the hint.
I tried as already written var_dump($obj_Json)
and got "string(4)"NULL""
but if I try var_dump($row)
then i got "object(stdClass)#3 (1) { ["Image"]=> string(22004) "�PNG IHDR\�ho��sRGB���gAMA�� �a pHYs���o...... "

How to fetch parameters from POST call in python web service

I am a python developer who is completely new to web development. I wish to develop a web service in python which authenticates user and returns a token.
I was able to do that using PHP (thanks to all the blogs available online). But soon realized that I want to do that in python.
Where I am stuck is that-
I don't understand how to fetch the parameters from POST request, like I was fetching in PHP (see code).
How to return a string or code (in PHP it's echo, should I user return?)
// include db connect class
require_once('veggieking_connect.php');
// connecting to db
$db = new VEGGIEKING_CONNECT();
// set mysql_query for utf8
mysql_query ("set character_set_results='utf8'");
$emp_id = $_POST["mEmpID"];
$emp_pwd = $_POST["mPassword"];
$result = mysql_query("select * from empdata where emp_id like '$emp_id' and emp_pwd like '$emp_pwd'") or die(mysql_error());
if(mysql_num_rows($result) > 0) {
while($row = mysql_fetch_assoc($result)) {
echo $row['emp_email'];
}
}
else {
echo "Fail";
}
?>
Just like in PHP, emp_id and emp_pwd are fetched, how to do that in python web serice when I call using the same POST request in android.
I understand it's a simple question, but I can't find any good python web services examples which explains what's happening in the code. If you are aware of where I can learn these, please share the url's also, it would be really helpful.
Thanks.
From your php code i understand bit that you want to retrieve and then fetch data in database. For this purpose in python use "psycopg2" module.
psycopg2 python Documentation
Using this Module you can do any operations related to database from python code.
I hope this will help you.

Maximum amount of data a PHP script can send to a MySQL TEXT field?

So I'm having the same problem as the folks here:
Problem inserting a long text in database column MYSQL PHP
Unable to save large text in mysql thru php
But I didn't see any genuine solutions to the problem besides the hack the guy posted in the first one to split the text up. The scripts have been tested and save to the database fine when it's a small amount of text, and the php script can save the largetext to a txt file fine as well. So the problem is somewhere on the Database side.
EDIT: The field I am posting to is already set to LONGTEXT
Here are my scripts:
post.php
<?php
$data=$_POST["SData"]; //Around 76kb of text
$rName=$_POST["regName"];
include_once './db_functions.php';
$db = new DB_Functions();
$db->insertText($rName, $data);
?>
db_functions.php
//Insert Text Data into DB
public function insertText($regId, $sdata) {
try {
mysql_query("UPDATE users SET textdata = '$sdata' WHERE id = '$regId'");
}
catch (PDOException $e) {
$output = 'Error performing update: ' . $e->getMessage();
}
}
I have the following questions:
What is the maximum datasize(amount of characters?) that I can send via PHP to a MySQL database? All the text i'm attempting to post is not necessary, so I could potentially limit it before I POST it. (But the more, the better)
Is there an actual solution where I could send large datachunks over PHP?
Potentially using 'the mysqli_stmt::send_long_data' found here: http://php.net/manual/en/mysqli-stmt.send-long-data.php ?
Are there any examples of this being used that aren't just in the manual?
Any help would be greatly appreciated, thanks!!
If you're using the obsolete mysql extension, you need to escape the data:
$sdata = mysql_real_escape_string($_POST['SData']);
It would be better to use PDO or mysqli and use prepared statements.
Check your max_allowed_packet paramter on your MySQL server, it will be the max value in bytes what MySQL will receive in query.
PHP has memory_limit configuration parameter as well.

connecting to a database using HostMonster

I'm using HostMonster as my web host and I'm trying connect to a database I created using MySQL inside of HostMonster. In order to call that database in my website do I need to use PHP? Or is there a way to create a javascript OnClick function that can call the database. I'm not using ASP.Net so it's not quite as simple as I would like it. Just curious if the best solution is PHP, if so I guess I should go learn it.
what are you planning to do with the database, other than just 'calling it'? You will need some language like PHP to connect to the DB to retrieve, insert, update or delete data in the DB.
here is a code for connection MySQL from PHP using MYSQLI extension
<?php
$dba_host='localhost';
$dba_name='root';
$dba_pass='';
$dba_db='sn';
$con=mysqli_connect($dba_host,$dba_name,$dba_pass,$dba_db) or die('Connection Refused !');
$stmt=mysqli_prepare($con,"SELECT UID FROM Main");
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $value);
while(mysqli_stmt_fetch($stmt))
$result[] = $value;
mysqli_stmt_close($stmt);
mysqli_close($con);
?>
Your javascript onClick function is running on the client side (in the browser) and the database is running on the server-side. You will need a server-side language to get the information from the database and send it to the browser.
You do not HAVE to use PHP to connect to a MYSQL database. Also, you can't connect to your database using only client-side javascript (ie. an onClick() function). You need to use a server side language, PHP is one choice.
To connect to a MYSQL database on hostmonster using PHP you will need to know your credentials that use to log into phpMyAdmin from your cpanel. Once you have made the connection you can then select the MYSQL database that you created. Once the database is selected you can query it using the "mysql_query" function in PHP. The following code does all of that and stores the results of the MYSQL query in a PHP variable called $result.
<?php
$con = mysql_connect("www.yourdomain.com","phpMyAdmin_username","phpMyAdmin_password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mysql_database_name", $con);
$query = "SELECT * FROM TableName"
$result = mysql_query($query);
?>
Now you've got the results of the query inside the PHP variable $result and you can use it anyway you like.
If you put this in your 'public_html' folder and named it 'index.php' or 'index.html' this would automatically be run when someone went to www.yourdomain.com.
You can find a great tutorial series on PHP here http://thenewboston.org/list.php?cat=11.

Can't access the SQLite database with MAMP and PHP

I have been learning how to program websites lately and the time has come for me to add a database. I have in fact already successfully created a MySQL database and interacted with it with PHP.
My problem is I can't seem to access a SQLite database file with it. I am using MAMP to host locally for now. Here is a snippet of the code I am using to access the db and find and print out a value stored on it.
<?php
$dbhandle = sqlite_open('/Applications/MAMP/db/sqlite/Users');
if ($dbhandle == false) die ('Unable to open database');
$dbquery = "SELECT * FROM usernames WHERE username=trevor";
$dbresult = sqlite_query($dbhandle, $dbquery);
echo sqlite_fetch_single($dbresult);
sqlite_close($dbhandle);
?>
As you have access to the database (your code doesn't die), I'd say there's got to be an error later ;-)
Looking at your SQL query, I see this :
SELECT * FROM usernames WHERE username=trevor
Are you sure you don't need to put quotes arround that string ?
Like this :
SELECT * FROM usernames WHERE username='trevor'
Also, notice that sqlite_fetch_single will only fetch the first row of your data -- which means you might need to use sqlite_fetch_array or sqlite_fetch_object if you want to access all the fields of your resulset.

Categories