views:

35

answers:

4

According to this question i successed to create upload image , but now i need to store the image_id to another table called articles , i do not know if this is correct , but i tried to select the image_id from table image like this

$select_image=mysql_query("select image_id from image where image_name = $fileName") or die(mysql_error());

and fetch the result to my article insert query like this

$fetch=mysql_fetch_array($select_image);

$qeuery=mysql_query("insert into articles (article_name,article_category,article_subcategory,article_body,article_summary,article_tags,article_photo,article_timedate) values ('$article_title','$CategoryID','$ProductID','$article_body','$article_summary','$fetch[image_id]','$time')") or die ('Error, Query Faild'.mysql_error());

is this correct ? the mysql_error keeps saying " Unknown column 'Penguins.jpg' in 'where clause'"

A: 

You need to put $fileName in quotes in your first query, i.e. '$fileName'

Matt Ellen
+3  A: 

This is mysql syntax related question. All data goes directly into the query must be prepared using 2 rules:
1. data must be escaped using mysql_real_escape_string() function
2. enclosed in quotes

So, the code must be

$fileName=mysql_real_escape_string($fileName);
$select_image=mysql_query("select image_id from image where image_name = '$fileName'") or die(mysql_error()); 

Also, if you inserted your image right before this query, no need to select it's id. you can use mysql_insert_id() function

Col. Shrapnel
+2  A: 

The problem is that your filename is not quoted, so your MySQL server is trying to process the query:

select image_id from image where image_name = Penguins.jpg

What's worse is that someone uploaded a file called

1; EVIL MYSQL QUERY HERE

they would be able to execute arbitrary MySQL on your server. This is known as an SQL injection attack.

Check out the PHP manual page that covers this.

Dancrumb
I'd say this is not the scaring injection issue, but just wrong syntax issue :)
Col. Shrapnel
+1  A: 

you can select the last inserted id by calling

SELECT LAST_INSERT_ID()

instead of

select image_id from image where image_name = $fileName
Nexum
how should i fetch this one in another select query ?
Bader
just replace select image_id ... with SELECT LAST_INSERT_ID() there is no need to select the actual row just to get the primary key (id) i assume you DO use auto_increment for your id fields :) only if you do this will work
Nexum
thank you it worked :)
Bader
@Bader you don't need any query as PHP has already a function for you. Better to read a PHP manual than not so smart SO answers
Col. Shrapnel