I am trying to pass a part of a file name as a parameter in the my sql query in php. My file name is in the form
db_feature_T1..iOXXdrXXcAMEra_092521.txt
from which I want the part except the db_feature and .txt i.e.
T1..iOXXdrXXcAMEra_092521
I want the img_id from the database whose img_path=dressimages/T1..iOXXdrXXcAMEra_092521.jpg
My code is as follows.I was able to seperate the file name but I cannot get any result from the database.
<?php
include('db.php');
if ($handle = opendir('C:\Users\adithi.a\Desktop\db_features')) {
while (false !== ($entry = readdir($handle))) {
$entry=substr($entry,11,-4); //this seperates the file name db_feature_T1..iOXXdrXXcAMEra_092521.txt to T1..iOXXdrXXcAMEra_092521
$image_path='dressimages/'.$entry.'.jpg';//I want to pass the img_path as it is saved in the database in the form of dressimages/T1..iOXXdrXXcAMEra_092521.jpg
$result= mysql_query("select img_id from tbl_image where img_path='$image_path'") or die("Sorry");
echo $result;//I dont get anything as output.
}
}
closedir($handle);
?>
I went to an infinite loop when executing the code above so i tried:
$image_path='dressimages/'.$entry.'.jpg';//I want to pass the img_path as it is saved in the database in the form of dressimages/T1..iOXXdrXXcAMEra_092521.jpg
$sql = "select img_id from tbl_image where img_path=".$image_path;
echo $sql . '<br />';
$result=mysql_query("$sql");
}
while($data=mysql_fetch_assoc($result))
{
echo $data["img_id"];
}
and Now i get the error mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\wamp\www\FashionBonanza\Readfile.php on line 34
Any help
You have to first fetch the data from your result
$data=mysql_fetch_assoc($result); // this is missing
print_r($data); // or
echo $data["img_id"];
and in case there can be multiple results you can do so in a loop
while($data=mysql_fetch_assoc($result))
{
print_r($data); // or
echo $data["img_id"];
}
Because you're dealing with so many files I would try another approach. That would be to store all paths into an array, make a single query and associate id's with path's. I'm not sure this code will work (I haven't tested it), but I hope you get the picture:
<?php
include('db.php');
if ($handle = opendir('C:\Users\adithi.a\Desktop\db_features')) {
//Store all paths into $image_paths array
$image_paths = array();
while (false !== ($entry = readdir($handle))) {
$entry=substr($entry,11,-4); //this seperates the file name db_feature_T1..iOXXdrXXcAMEra_092521.txt to T1..iOXXdrXXcAMEra_092521
if (strlen($entry) !== 0) {
$image_paths[]='dressimages/'.$entry.'.jpg';//I want to pass the img_path as it is saved in the database in the form of dressimages/T1..iOXXdrXXcAMEra_092521}
}
}
closedir($handle);
//Implode paths
$pathQuotesArray = array_map('apply_quotes', $image_paths); //Looks like 'filename1', 'filename2' etc
$pathQuotes = implode(',', $pathQuotesArray);
//Do one query
$result= mysql_query("select img_id from tbl_image WHERE img_path IN ($pathQuotes)") or die(mysql_error());
//Associate id's with paths
while($data=mysql_fetch_assoc($result))
{
$key[$data["img_id"]] = $data["img_path"];
}
echo $key[5]; //If img_id is 5, then it would show correct path (hopefully :-))
function apply_quotes($item)
{
return "'" . mysql_real_escape_string($item) . "'";
}
?>
Try this
$result= mysql_query("select img_id from tbl_image where img_path="$image_path) or die("Sorry");
Just two ideas:
$result= mysql_query("select img_id from tbl_image where img_path='".$image_path."'") or die("Sorry");
Maybe it's better to do it this way. Otherwise set a extra string variable for the SQL-query, so you can track the exact query, which was executed.
$sQry = "select img_id from tbl_image where img_path='".$image_path."'";
var_dump($sQry);
$result= mysql_query($sQry) or die("Sorry");
So you can check, if the variable contains the correct value or not.
Next point is the "echo". You can't echo a result set, use functions like mysql-fetch-array() or mysql_fetch_assoc() - http://php.net/manual/de/function.mysql-fetch-array.php - or other ones.
while ($row = mysql_fetch_assoc($result)) {
echo $row["img_id "];
}
Related
hi i have a backend with php in cpanel and i have a problem with one of jsons . this is part of my php code :
...
}elseif ($work == "dollardate") {
$query3 = "SELECT * FROM tabl_dollar_date";
$result3 = $connect->prepare($query3);
$result3->execute();
$out3 = array();
while ($row3 = $result3->fetch(PDO::FETCH_ASSOC)) {
$record3 = array();
$record3["dollar"] = $row3["dollar"];
$record3["date"] = $row3["date"];
array_push($out3, $record3);
}
echo json_encode($out3);
}
?>
this code show this in json :
[
{
"dollar":"15000",
"date":"1397-12-12"
}
]
how can remove array from json and show the json like this :
{
"dollar":"15000",
"date":"1397-12-12"
}
Easiest way (according his code):
change line
echo json_encode($out3);
to
echo json_encode($out3[0]);
One solution is that if you just want the latest value (in case there are multiple records in the table), then change the SELECT to order by date descending also set LIMIT to 1 to only get the 1 record anyway, and remove the loop to fetch the data and just fetch the 1 record...
$query3 = "SELECT `date`, `dollar`
FROM `tabl_dollar_date`
ORDER BY `date` desc
LIMIT 1";
$result3 = $connect->prepare($query3);
$result3->execute();
$row3 = $result3->fetch(PDO::FETCH_ASSOC);
echo json_encode($row3);
As you know which fields you want from the SELECT, it's good to just fetch those fields rather than always using *. This also means that as the result set only contains the fields your after, you can directly json_encode() the result set rather than extracting the fields from one array to another.
I have actors field in my movie database which is having many actors in one field separated by comma and fetching them using below code. My requirement is to link all fetched actors. on click on each actor will take to the list of their movie.
Since i am having all actors in one field and separated by commas, struggling to link each of them with separate url
<?php
require('connect');
$filmActor=$_GET['filmActor'];
$sql ="SELECT * FROM films WHERE filmActor LIKE '%$filmActor%' LIMIT 0 , 5;";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result))
{
$filmActor=$row['filmActor'];
$filmName=$row['filmName'];
$url=$row['url'];
echo "
<a href='$url.html'>$filmName</a>: $filmActor<br>
";
}
mysqli_free_result($result);
mysqli_close($conn);
?>
Output i am getting like:
Expected:
Want to pass this parameter:
/actor.php?filmActor=Tom_Hanks, /actor.php?filmActor=Emma_Thompson etc will displace each actors film they have worked on.
This script should work. It takes the $row['filmActor'] and split all the actors into an array by ',', and then we print them out one after one.
Just keep in mind that this can be done a better way, but this should work.
Also, I've added a "mysqli_real_escape_string" to the GET input "$_GET['filmActor']" to prevent SQL injections.
<?php
require('connect');
// Escape the input from the user, preventing SQL injections
$filmActor = mysqli_real_escape_string($conn,$_GET['filmActor']);
$sql ="SELECT * FROM films WHERE filmActor LIKE '%$filmActor%' LIMIT 0 , 5;";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result))
{
$filmActor=$row['filmActor'];
$filmName=$row['filmName'];
$url=$row['url'];
echo "<a href='$url.html'>$filmName</a>:";
// Make an array of the actors by splitting them by ','
$actorsArray = explode(',',$filmActor);
// Loop the array
foreach ($actorsArray as $key => $actor)
{
// Just trim the space in front of name in case there is any
$actor = trim($actor);
// Check if the current key is == to the last key in the array
// so it wont make an ',' in the end of the actors.
if ($key == (count($actorsArray)-1))
echo "<a href='/actor.php?filmActor=$actor'>$actor</a>";
else
echo "<a href='/actor.php?filmActor=$actor'>$actor</a>, ";
}
}
mysqli_free_result($result);
mysqli_close($conn);
Let me know how it works out.
And as tadman said in the comments above "NEVER put $_POST or $_GET data directly into a query, it can be very harmful if someone seeks to exploit your mistake."
Hope it helps!
I'm trying to create an online database of the music I locally have on my computer. I already have a table of every song in my library and would like to create a different table with just the song ID's (auto-incremented when I added the songs to my main table) that act as one of my playlists.
From what I can tell, the only 100% certifiable method for matching the songs is by the location on my disk ( C:\Users\username\Music\iTunes\iTunes Media\Music\Jonathan Coulton and GLaDOS\Portal\128 128 Still Alive Duet.mp3 ) as an example. In my PHP code I get the song location into a variable and if I print it relative to the equivalent song location in my MYSql table, they match up exactly but when I try to run a select statement using that, it gives me an error. From what I can tell this is being caused by the backslashes in the location info.
This is the select statement I'm using,
SELECT id FROM itunes WHERE Location=$locationval
where $locationval is the current song's location, id is the autoincremented id in my main table, and itunes is my main table.
Is there any way around this? And as I am a beginner, is the backslashes really the issue?
For reference here is the full code for importing the playlist, its using the DB plugin for PEAR (a PHP extension).
<?php
// define table name
define('TABLE_NAME', 'playlist');
// create database connection
require_once('DB.php');
$dsn = 'mysql://username:password#localhost/itunes';
$DB =& DB::connect($dsn);
if (DB::isError($DB)) {
die($DB->getMessage());
}
$DB->setFetchMode(DB_FETCHMODE_ASSOC);
// load text file
$file = file_get_contents('Portal.txt');
// explode on new line
$file = explode("\r", $file);
set_time_limit(0);
// loop through each line in the file
foreach ($file as $key => $value) {
// explode on tab to get column list
$exploded = explode("\t", $value);
// check for first row, which contains column headers
if ($key == 0) {
}
else{
if(count($exploded)>3)
{
$locationval=$exploded[26];
echo $exploded[26];
echo "<br />";
$result = mysql_query("SELECT id FROM itunes WHERE Location=$locationval");
//$result = mysql_query("SELECT * FROM itunes WHERE id=8292");
set_time_limit(0);
$row = mysql_fetch_row($result);
//test statements to see if the query worked
echo "Test: ";
echo $row['id'];
echo $row['Location'];
echo "<br />";
}
}
}
?>
Which was modified from the code here: http://ericlondon.com/posts/208-exporting-itunes-data-into-mysql-and-creating-sql-to-show-top-rated-albums
If any more info is needed, please let me know.
You need to escape the backslashes when using it in mysql as a string literal, so just replace your following line:
$result = mysql_query("SELECT id FROM itunes WHERE Location=$locationval");
for this one:
$result = mysql_query("SELECT id FROM itunes WHERE Location='". str_replace('\\','\\\\',$locationval) . "'");
that should do what you want.
I'm trying to write a script that gets data from a sql server based on the id of the entry in my data base. when I try to access the page using the link with the id of the entry it returns as if it does not recognize the id. Below is the php code :
<?php
require('includes/config.inc.php');
require_once(MYSQL);
$aid = FALSE;
if (isset($_GET['aid']) && filter_var($_GET['aid'], FILTER_VALIDATE_INT, array('min_range' => 1)) ) {
$aid = $_GET['aid'];
$q = "SELECT aircraft_id, aircraft_name AS name, aircraft_type AS type, tail_number AS tn FROM aircraft USING(aircraft_id) WHERE aircraft_id = $aid";
$r = mysqli_query($dbc, $q);
if (!(mysqli_num_rows($r) > 0)) {
$aid = FALSE;
}
}// end isset tid
if ($aid) {
while ($acdata = mysqli_fetch_array($r, MYSQLI_ASSOC)){
echo'<h2>'. $acdata['tail_number'] .'</h2>';
}
} else {
echo '<p>This pages was accessed in error.</p>';
}
?>
Any hints?
Try to var_dump($q); before $r = mysqli_query($dbc, $q); to inspect your query and then just execute it through phphmyadmin or in MySQL server terminal directly and see what does it return.
Update:
Use var_dump($q);die(); to stop script from executing after dumping.
You are using a field alias in your query, so you must use that in your echo to:
echo'<h2>'. $acdata['tn'] .'</h2>';
Get rid of the USING(aircraft_id), it causes an error and your query doesn't execute.
"SELECT aircraft_id, aircraft_name AS name, aircraft_type AS type, tail_number AS tn FROM aircraft WHERE aircraft_id = $aid"
I guess it's a leftover from a previous version of the query? Using (id) is a shortcut for
FROM
foo
INNER JOIN bar ON foo.id = bar.id
It can be used when the tables to be joined are joined on columns which have the same name. Just shorter to write.
Since you are not joining you have to remove it.
I'm trying to create a dynamic list (5 row results) in php by first getting data from one table then using a resulting var to get the latest uploaded "image_links" (just 1 from each of the 5 artists) from another table -- then echo out.
The code here gives me the only one row with the latest image. When I comment out the "// get the latest image link uploaded ///" section of the code I get the 5 rows of different artists I really want but, of course, w/o images. I tried (among a bunch of things) mysql_result() w/o the while statement but that didn't work.
So what am I missing?
Thanks
Allen
//// first get the artists followed ////////////////
$QUERY= "SELECT * FROM followArtist WHERE user_id = $user_id ";
$res = mysql_query($QUERY);
$num = mysql_num_rows($res);
if($num>0){
while($row = mysql_fetch_array($res)){
$artist_name = $row['artist_name'];
$artist_id = $row['artist_id'];
$date_lastSent = $row['date_lastSent'];
$date_artPosted = $row['date_artPosted'];
$date_notePosted = $row['date_notePosted'];
//// get new notice data /////
if ($date_artPosted >= $date_lastSent) {
$artp = "new artwork posted";
}else{
$artp = "";
}
if ($date_notePosted >= $date_lastSent) {
$notep = "news/announcement posted";
}else{
$notep = "";
}
if ($artp!="" && $notep!="") {
$and = " and<br />";
}else{
$and = "";
}
if ($artp=="" && $notep=="") {
$no = "No new images or news posted since your<br /> last visit, but we'll let you know when there is.";
}else{
$no = "";
}
//////// get the latest image link uploaded ////////////////////////////////////
$QUERY2="SELECT image_link FROM artWork WHERE artist_id ='$artist_id' AND make_avail = '1' ";
//ORDER BY date_submit DESC
$res = mysql_query($QUERY2);
$num = mysql_num_rows($res);
if($num>0 ){
while($row = mysql_fetch_assoc($res)){
mysql_fetch_assoc($res);
$image_link= $row['image_link'];
}
//////// end of get the latest images uploaded ////////////////////////////////
echo "<tr align=\"center\" height=\"115px\">
<td align=\"left\" width=\"15%\"> <a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\">
<img src=slir/w115-h115/$path$image_link /></a></td>
<td align=\"center\" width=\"80%\"
<span class=\"deviceMedLtGrayFont\">$artist_name</span>
<br /><br />
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$artp</a>
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$and$no</a>
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$notep</a>
</td>
</tr>";
} //// end bracket for getting latest image link
} ///loop end for getting followed artist data
} ///end: if ($num>0) clause<code>
If I read your code correctly, I see you looping using data from query1 in the control structure, and a lookup on query2 within each loop. You are reusing the variables in your loop1 control structure for query2 ($num and the query handle ($res)) for the second loop. Probably not desirable within the loop.
You're sharing the variables $num and $res between the two queries ... your original properties will be overwritten when the second query is run. Use different property names for the inner query.
Example of problem:
$result = QueryA();
while( $row = $result->getRow() )
{
// -- You're overwriting the original result here ...
$result = QueryB();
// Next time the loop runs, it will run using the result from QueryB();
}
So change ...
$res = mysql_query($QUERY2);
$num = mysql_num_rows($res);
if($num>0 )
{
while($row = mysql_fetch_assoc($res))
{
mysql_fetch_assoc($res);
$image_link= $row['image_link'];
}
to
$res2 = mysql_query($QUERY2);
$num2 = mysql_num_rows($res2);
if($num2 > 0)
{
while($row2 = mysql_fetch_assoc($res2))
{
$image_link= $row2['image_link'];
}
this is a mess - as others have said you're using the same variables for different purposes.
That you're storing integers which seem to represent enumerations in a char field is bad.
You're iterating through the second result set to find the last record (from an unsorted result set!).
You only need one query - not 2.
SELECT f.artist_name, f.artist_id, f.dateLastSent....
SUBSTR(
MAX(
CONCAT(DATE_FORMAT(date_submit, '%Y%m%d%H%i%s'), a.image_link)
), 15) as img_link
FROM followArtist f
LEFT JOIN artWork a
ON (a.artist_id=f.artist_id AND a.make_avail = '1')
WHERE user_id = $user_id
GROUP BY f.artist_name, f.artist_id, f.dateLastSent....