Get null values while trying to download a blob - php

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...... "

Related

Failed to connect to MySQL: Access denied for user 'root'#'localhost' (using password: YES)

I was told by someone else that input this url https://beachbumbookworm.com/service.php into their browser it works. However, when I place the url in my google browser it will not work.
I have been working from a tutorial at this site https://codewithchris.com/iphone-app-connect-to-mysql-database/#app at 3.2 in the tutorial. There is a service.php file below that I pasted into text editor on my MacBook Air. I have made a table named locations in phpmyadmin, I have given proper permissions for the username and password. There aren't any characters in the password that would warrant a denial. I am using exactly what the tutorial is using, which includes a wordpress + Bluehost environment. From the bluehost there is a control panel I have access to and there, I have accessed phpmyadmin and mysqldatabases. After the service.php file was edited by me, I uploaded it into php per the article. I'm not sure what's wrong, please help.
<?php
// Create connection
$con=mysqli_connect("localhost","username","password","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 * FROM Locations";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
Here is an image of the database table created
It doesn't matter what browser do you use in that case, because MySQL connection creates at the backend before sending the response;
At the line with mysqli_connect("localhost","username","password","dbname"); code try to replace credentials with that one, which you have used in PhpMyAdmin;
Check your MySQL credentials with your MacOS terminal. Use this command: mysql -u root -p

MySQL Returns different number of rows on localhost vs live server for the same code

I have a simple form that needs a list of stops in the textarea and returns an id for each on the right hand side. This is my screenshot on localhost...I have the same table names, column names, number of records on both localhost and live server.
Here's the screenshot of the same page with same query on live server...
Here's the code I am using on both pages
$conn = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass);
if(isset($_POST["busnumber"], $_POST["busroute"])){
$stops = explode(PHP_EOL, $_POST["busroute"]);
$sql = 'SELECT * FROM stops WHERE stop_name LIKE :stop';
$statement = $conn->prepare($sql);
$statement->setFetchMode(PDO::FETCH_ASSOC);
foreach($stops as $stop){
$statement->bindValue(':stop', $stop);
$statement->execute();
$results = $statement->fetchAll();
foreach($results as $result){
echo $result['stop_id'].' '.$result['stop_name']."</br>";
}
}
}
As you can see, it returns the ID of the last row only on the live server. Can someone please tell me how this is possible and what I am missing?
EDIT 1
Notice what happens when I reverse the data entered in the text area
The localhost shows both the ids now
Guess what the server shows after reversing? Only the LAST ROW!
You don't need setFetchMode(). In the time I've used PDO I always had the best results with just using bindParam() and fetch() with the most default setup of PDO, which means just setting the errormode to exception and charset to utf8 like this:
try
{
$con = new PDO("mysql:host=".$host.";dbname=".$db_name, $user, $password);
}
catch(PDOException $e){
die("ERROR ". $e->getMessage());
}
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->exec("SET NAMES utf8");
Fetching any results like this
while($r = $statement->fetch())
{
echo $r['id'];
}
Any time when someone has used a different set up, I've noticed they've faced problems.
Try this, perhaps.
This is very simple. Please check your live db via phpmyadmin if you have access and from phpmyadmin run your queries like you are running it from php code. May be you have some restrictions of mysql or php on live. And also check your db versions on localhost and live with php versions too. Let me know the results of phpmyadmin queries thanks!
Just guessing the problem. I don't really think if this answer is correct. So please pardon me in advance.
PDOStatement::fetchAll() returns an array that consists of all the rows returned by the query. From this fact we can make two conclusions:
This function should not be used, if many rows has been selected. In
such a case conventional while loop ave to be used, fetching rows
one by one instead of getting them all into array at once. "Many"
means more than it is suitable to be shown on the average web page.
This function is mostly useful in a modern web application that
never outputs data right away during fetching, but rather passes it
to template.
Source: PDO Tutorial
I FIXED the error. I have answered it in detail on a different post and I am linking to that post from HERE Thank you all for your time and answers

Manage empty result query in MySql with PHP for Android HttpUrlConnection

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

PHP and MySQL INSERT INTO does not work -- No error and no new lines in DB

This my first post on this site. I will do my best to include all the needed information. I have read many of the answers regarding this same problem. I have tried many combinations and none of them work. The following is the one that gets me the closest to my very simple goal --> Write a line to my database. This code is in a password protected portion of my site.
<?php
//Connect to database
include("../ConfigFiles/ConnectDB_live.php");
echo "<br> I am still alive? <br>";
//Can I read from DB --- This worked on live
$strSQL = "SELECT * FROM invoicelist_table";
$rs = mysql_query($strSQL);
while($row = mysql_fetch_array($rs))
{
echo $row['FileName'] . "<br>";
}
//Can I write to the DB --- Live
//Lets mix a few ideas together
mysql_query($bdd,"INSERT INTO `invoicelist_table` (`InvoiceNo`, `FileName`, `FilePath`) VALUES ('9999', 'MyName', 'MyPath')") ;
echo mysql_error();
//or die(mysql_error());
echo "I wrote something to the DB successfully <br>";
// Close the database connection
mysql_close();
echo "The connection to DB is closed";
?>
Note that I can read the database just fine but I can't seem to write to it. I have also tried the recommended mysqli version but that does not work either. I have tried various ways of trapping an error and I get nothing... literally nothing! I have tried at least a dozen syntax variations. I am ready to throw up!
I am new to web programming and find most of my answers online. I think I am doing pretty good for my limited knowledge. This one is blowing my mind. None of the recommendations I read about work or make sense to me. So please answer me like I am a 5-yr old!
Thanks in advance.
Move your connection as the second parameter or remove it if you didnt close the connection
mysql_query("INSERT INTO `invoicelist_table` (`InvoiceNo`, `FileName`, `FilePath`) VALUES ('9999', 'MyName', 'MyPath')") ;
Docs

Using php/pdo to display sql data on website, no luck

I know this is probably something simple, but I have searched for hours the past few days and I'm ready to jump out of my one-story building.
Have a basic site for testing, literally nothing on it but opening/closing html tags.
A very basic table in a data base, using phpmyadmin to access it.
Trying to get table contents to display on the basic website.
Was using mysqli_ or mysql_ style in the php to access the data for a while with no luck.. Have since been reading about PDO and found numerous tutorials on how to use it. I feel like what I'm trying to do should be so simple but I've tried copying what I've found on this site and other tutorials to the T and the site still does not display the data.
try {
$conn = new PDO("mysql:host=$hostname; dbname=$userdb", $username, $password);
$conn->exec("SET CHARACTER SET utf8");
$sql = "SELECT * FROM Monday";
$result = $conn->query($sql);
while($row = $result->fetchAll(PDO::FETCH_ASSOC)) {
echo $row['Name'] . '<br />';
}
$conn = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
Basically the website will display everything after the first -> in this case after the $conn-> but none of the actual table data.
I've tried about 50 different ways at least from numerous sites and I'm just lost now I guess..
Side note: I do have php forms on the same site that when submitted successfully insert data into the table, so I know I am able to connect to the db and table and INSERT, its just the issue of SELECT I can't get.
Thanks for any help
EDITED: to add fetchAll
You are using the method fetch() in your loop, which only fetches the next single row of your results. Replace it with fetchAll() and it should work.
More information about the fetchAll() method:
http://php.net/manual/en/pdostatement.fetchall.php
And for testing purposes you could set the PDO error mode to PDO::ERRMODE_EXCEPTION. See: http://php.net/manual/en/pdo.error-handling.php
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
Should be;
while($row = $result->fetchAll(PDO::FETCH_ASSOC)) {

Categories