Reading from mysql table issue - php

I'm dealing with strange problem.
$result = mysql_query("SELECT link FROM item WHERE item_id='$id2'") or die(mysql_error());
$row = mysql_fetch_assoc($result);
$picture = ''.$row['link'].'';
echo"$picture";
Gives me result http://127.0.0.1/1321426277. without ending, while in column link link is: http://127.0.0.1/1321426277.jpg. Why it cuts ending?

For testing purposes please run
$result = mysql_query("SELECT link, Length(link) as l FROM item WHERE item_id='$id2'") or die(mysql_error());
$row = mysql_fetch_assoc($result);
if ( !$row ) {
echo 'no such record';
}
else {
$l = strlen($row['link']);
var_dump($l, $row['l'], $row['link']);
$picture = $row['link'];
echo "'$picture'";
}
and post the result.

I don't see anything in your code that would cause the link to be truncated. Have you checked to make sure you have the correct data in your table?

It looks like a bug in the data. Print out (and select) the ID at both places (the query in your question and the other place where you use it in img src tag). I bet they will differ. Or, you should check SELECT count(1) FROM item WHERE item_id='xxx'*, where xxx is the ID of the magic record.

Ah now I see = the problem is because you code contains an 'r' after the 'o' rather then before - it is so clear now because you provided such a complete example of the behavior that I replicate on my machine.
WTF

Related

Blank result for some columns when php mysql_query, works in phpmyadmin

I've run into a problem that is making me go a bit crazy. I have imported some csv data into a table in my phpadmin database and am now using a php script with mysql_query() to run a simple select query on the database and convert the result into json format - e.g. SELECT clients FROM TABLE 29.
Basically, some of the columns in the table result in a json string after passing them through mysql_query() but others simply return a blank. I have fiddled for hours now and can't figure out why this is. The last bit of my code looks like this:
$myquery = "SELECT `clients` FROM `TABLE 29`";
$query = mysql_query($myquery) or die(mysql_error());
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
Any help would be greatly appreciated. Could it be something about the data in the table? I'm at a loss.
thank you!
UPDATE: the length of the strings in the column clients seems to be having an effect. When I replace all the text with something shorter (e.g. aaa instead of something like company name 111 - 045 - project name - currency - etc) it works. However, I need it to be able to handle long strings as I want it to just take whatever users happen to import into it... what am I doing wrong?
No, its not about the table, its about how you loop them. Example:
$data = array();
while($row = mysql_fetch_assoc($query)) { // While a row of data exists, put that row in $row as an associative array
$data[] = $row;
}
echo json_encode($data);
mysql_close($server);
exit;
Note: mysql is depreacted and no longer maintained. Use the improved version of the mysql extension which is mysqli or use PDO instead.
After checking all the rows of the data I discovered that the source of the problem was a 'é' - yes, an 'e' with an accent. Once I replaced it with a regular 'e' the problem went away. So much lost time for something so tiny :(

How can I pull a random image from MySQL with PHP?

I'm learning PHP/MySQL while working on a web app. Part of this app calls for echoing out a random image from an image directory titled 'htdocs/full'. The database is holding the path to each image in a column titled 'image_path' in addition to columns for 'first_name' 'last_name'.
I'm able to make it call a random row from the database and I can make it display literal data from the 'first_name' and 'last_name' columns. But I'm struggling to make it take the path from the 'image_path' column and converting it into an image rather than a literal.
I've been experimenting with a number of methods over the last 24 hours, but most everything else I've been seeing on Stack and Google is for pulling an image straight out of the directory without using the database row (which is needed due to the corresponding 'first_name' and 'last_name').
Here is what I have so far (although I also have many different variations, this I think is the closest I've come):
<?php
$username="root";$password="*********";$database="offenders";
mysql_connect('localhost',$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$sSQLQuery = "SELECT image_path FROM offenders ORDER BY RAND() LIMIT 1";
$aResult = mysql_query($sSQLQuery);
WHILE($aRow = mysql_fetch_array($aResult)):
{
header("Content-Type:image/jpeg");
echo "<img src='php/imgView.php?imgId=".$aRow['image_path']."' />";
}
ENDWHILE;
?>
It produces a page with a tiny broken image at the top left. I've tried this with echoing $aRow as well as $aRow['image_path'] as seen above and a number of other tweaks that seems to cause error. Any ideas what I'm doing wrong?
Thanks a lot!
Updated code:
<?php
$username="root";$password="*******";$database="offenders";
mysql_connect('localhost',$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$src="full/";
//if you have any problem in the solution check this line,
//means weather you are providing right path for your files or not.
$sSQLQuery = "SELECT image_path FROM offenders ORDER BY RAND() LIMIT 1";
$aResult = mysql_query($sSQLQuery);
$aRow = mysql_fetch_array($aResult);
$file_path=$src.$aRow["image_path"];
//echo "<a href='php/imgView.php?imgId=".$aRow['image_path']."'>"."<img src=".$file_path." />"."</a>".'<br/>';
echo "<img src=".$file_path." />".'<br/>';
//echo "<img src=full/1b2ba2f9a8b8ee9c062b09767535d69bd954e125.jpg>";
/* if(isset($_GET['imgId']))
{
//i am query only first_name but you can add for field as you want
//and i also used $_get['imgId']; in the query which is not safe but you can make it for //secure.
$sSQLQuery = "SELECT first_name FROM offenders where image_path='".$_GET['imgId']."'";
$aResult = mysql_query($sSQLQuery);
WHILE($aRow = mysql_fetch_array($aResult)):
{
echo $aRow['first_name'];
}
ENDWHILE;
}
*/
?>
There are several things wrong here.
You have your database output in a loop. Instead of
WHILE($aRow = mysql_fetch_array($aResult)):
{
...
}
ENDWHILE;
use:
$aRow = mysql_fetch_array($aResult);
...
You are returning what looks like HTML, but you have a content type of JPG. Either return HTML and use an appropriate content type or return a JPG, and return that.
If you want to return the JPG itself (and not the HTML), use CURL to grab the write image and return it.
In my view i dont know why you are running the while loop because in your query you have limit of one so you dont have to run the while loop.
lets say you have your images in the folder name php/image/than your images comes
I am writing my solution on the assumption that your images are in the image folder, if they are not you can simply change the $src value in the solution.
and i am also thinking you want to use these images as a link, so you can get the first_name, and last_name when some one click on the image, reason i am thinking like this, that you try to give id in the img src="",
any way i am writing two solution see which one work for you. first one gonna make them link and second one only gonna pull the images from the database.
First one on the assumption you want to pull the first_name and last_name, from the database, when some one click on the image.
<?php
$username="root";$password="";$database="offenders";
mysql_connect('localhost',$username,$password);
mysql_se
lect_db($database) or die( "Unable to select database");
$src="php/image/";//if you have any problem in the solution check this line,
//means weather you are providing right path for your files or not.
$sSQLQuery = "SELECT image_path FROM offenders ORDER BY RAND() LIMIT 1";
$aResult = mysql_query($sSQLQuery);
$aRow = mysql_fetch_array($aResult);
$file_path=$src.$aRow["image_path"];
echo "<a href='php/imgView.php?imgId=".$aRow['image_path']."'>"."<img src=".$file_path." />"."</a>".'<br/>';
if(isset($_GET['imgId']))
{
//i am query only first_name but you can add for field as you want
//and i also used $_get['imgId']; in the query which is not safe but you can make it for //secure.
$sSQLQuery = "SELECT first_name FROM offenders where image_path='".$_GET['imgId']."'";
$aResult = mysql_query($sSQLQuery);
WHILE($aRow = mysql_fetch_array($aResult)):
{
echo $aRow['first_name'];
}
ENDWHILE;
}
?>
Second solution only pull the images from the database
remove the isset condition and while loop in the isset condition.
and change this line
echo "<a href='php/imgView.php?imgId=".$aRow['image_path']."'>"."<img src=".$file_path." />"."</a>".'<br/>';
To
echo "<img src=".$file_path." />".'<br/>';
//if you notice the only different is this that i
//remove the <a> tag in its path, so not it gonna pull images
// from the database but you cant use them as link.
Thanks
this solution work fine if it does not please post your folder structure, means where you have images and this file imgView. and second note i removed your while loop from the solution,
//

php array to string not working online server

I have a problem. I have an array of values from database, when I try to pass it to a string with commas, it works fine on my localhost, but when I upload it to my online server, the string doesn't show any values. For example: select from table where in (,,) only shows the commas and in my xampp server it works excellent. Any ideas what this can be?
Here's the code:
<?php
$sql = "select id from users where gid = 1";
$result = mysql_query( $sql);
$cat_titles=array();
while( $row=mysql_fetch_assoc($result) )
{
$cat_titles[] = $row['id '];
// do stuff with other column
// data if we want
}
mysql_free_result( $result );
echo "<p>\n";
foreach($cat_titles as $v)
{
$cat_titles[]= $row['id'];
}
echo "</p>\n";
$cat_titles = implode(',',$cat_titles);
$cat_titles = substr($cat_titles,0,-2);
echo $cat_titles;
echo "select * from users where IN (".$cat_titles.")";
?>
A number of potential issues here:
You are not handling error conditions around you database access, so if you are having issue with your queries you would never know.
Your second select query doesn't specify a field in the WHERE clause, so it will never work
This section of code does absolutely nothing and is in fact where you problem likely lies.
foreach($cat_titles as $v)
{
$cat_titles[]= $row['id'];
}
Here $row['id'] won't have a value, so you are basically looping throguh your existing array and appending empty value to new indexes.
In all likelihood you could do this with a single query, it might help if you explain what you are actually trying to do.
You should not be using mysql_* functions. They are deprecated. Use mysqli or PDO instead.

php get specific data from the same column in all row

i have a php question,
how can i get all the data from the same column from all row in a mysql table.
Table name : user
Here's my table structure:
name
url
How can i use php to get all the data in URL column from each row?
(P/S i have my connection to database established , just not sure the musql query for this)
Thanks and have a nice day.
This really is extremely basic stuff and you could have found this anywhere, it's even in the PHP manual. But alas, here you go.
$result = mysql_query("SELECT url FROM user");
while($row=mysql_fetch_assoc($result){
echo $row['url'].'\n';
}
Please read up on some basic stuff to avoid asking these kind of questions: http://www.freewebmasterhelp.com/tutorials/phpmysql
$query = "select url from user";
$result = mysql_query($query);
while( $row = mysql_fetch_assoc($result)){
echo $row['url'] . '<br>';
}

Save image URLs in MySQL?

I actually have a few questions here: My end goal is to write a script that will automatically display all the images that i have saved inside my database(If i add new images to my database(image URLs), each time i refresh the page i would like those "new" images to be instantly displayed as well).
What is the proper way to save an image URL inside MySQL? Currently i set my input type to VARCHAR; is that okay for image URLs?
Also, at the moment i'm working with WAMP server just to test how the site is working; so i put an image inside the www folder(within the same folder as my php script) and inside the database table i simply put the URL as follows: image.png is this the correct way to enter an image URL inside my database?
What is the best way to display these images in a sequence? The following code is what i have so far:(the image widths will take up about 70% of the page so the images will not be next to each other; they will be in a column form.)
<?php
$db_host="host";
$db_user="user";
$db_pass="pass";
$db_name="name";
$db_table="table";
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());
$query = mysql_query("SELECT * FROM tablename");
$result = mysql_query($query);
$num = mysql_num_rows($result);
for($count = 0; $count < $num; $count++)
{
//output the rows one by one(the actual images, not the URLs)
mysql_fetch_row($result);
echo("<br/>");
}
?>
I don't know if i should be using mysql_fetch_row in there..
I want my images to have some space in between; i was thinking the best way to accomplish that would be to add a "br" tag at the end of my loop so that every time a new image is displayed, a line break will be added to the end of the page.. Is that the best way to do it?
Thanks a bunch in advance!
To your first question, yes. To your second, also yes, if all your images are stored in the same directory. Mostly it's a matter of preference though.
Your for loop should look like this:
for($count = 0; $count < $num; $count++) {
$row = mysql_fetch_assoc($result);
echo "<img src='". htmlspecialchars($row["image"]) ."' alt='image' />";
}
br tags would probably be a bad idea. Set the images' display property to block in your CSS file. There are plenty of CSS manuals online.
With
$query = mysql_query("SELECT * FROM tablename");
$result = mysql_query($query);
$num = mysql_num_rows($result);
you do some things twice. You do not want $query to be the result of a mysql_query() call and then apply mysql_query() again.
In this case, the second call would happen with a resource object instead of a string - you got informed about it. By putting "" around, you turn it into a string again, but one which doesn't make sense to mysql.
To verify that, try to put or die(mysql_error()) to the problematic calls.
And to fix that, you can try
$query = "SELECT * FROM tablename";
$result = mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($result);
BTW: you don't need $num when you replace the for loop with
while ($row = mysql_fetch_row($result))
// do stuff with $row
}
I've done a previous project based on image storage in a SQL database. the best way to store the images would be as a link, ie, '/stored_images/imagefilename.png'. When you need to reference the images just get the images into a while loop for each row in the table.
ie.
to get the images
<?php
$query = mysql_query("SELECT * FROM tablename");
while ($row = mysql_fetch_array($query)) {
echo '<img src="' . $row['column of url storage in SQL'] . '" />';
}
That will output all the images in the database, just change 'column of url storage in SQL' with the actual column name that you store in the SQL DB. also replace 'tablename' in the SQL query with the name of the table the images are being stored in.

Categories