Writing to mysql database

software development

#1

I am having a problem writing to my database, I am not having any connection problems, but it just won’t write to the database…

here is the php code i am using

$sql="INSERT INTO ‘pictures’ (‘newname’, ‘file’, ‘filename’, ‘catagory’, ‘description’, ‘date’ , ‘ID’) VALUES(’$file_copy’,’$file’,’$filename’,’$category’,’$description’, ‘$date’, ‘’) or die("Could not insert data: “.mysql_error())”;

mysql_query(’$sql’);


#2

I see a few things… first, your table name and columns the way you’ve quoted them are string literals. If you want to use delimiters for your table and column names they should be the right-facing single quote (apologies, I don’t know the proper name) which shares a key with the tilde character.

Second, it looks like you’re trying to use an auto-increment field called ID, since you’re trying to pass an empty string… you can just omit that column altogether.

Third, you’re passing the query as a variable, but since it’s in a single-quoted string, PHP is interpreting your entire string literally, and sending the query “$sql” to MySQL, which is not understood.

Fourth, “or die” is syntax provided by PHP, not MySQL, so you can’t include it in your query. If you want to check for errors, you should do if(!mysql_query($sql)) echo mysql_error();

So, if you make the following changes, it ought to work:

$sql=“INSERT INTO pictures (newname, file, filename, catagory, description, date) VALUES(’$file_copy’,’$file’,’$filename’,’$category’,’$description’, ‘$date’)”;

$result = mysql_query($sql);
if(!$result) echo mysql_error();


#3

Thank you… I am just starting out with mysql. That did work


#4

to make syntax even better…

no need to put quotes around the field types, I think in my experience its misleading…

$sql = “INSERT INTO pictures (newname, file, filename, catagory, description, date)
VALUES(’$file_copy’,’$file’,’$filename’,’$category’,’$description’, ‘$date’)”;

because fields are just names not datatypes. But for the values you would need to asign the datatype accordingly.


#5

You only need to use `` around your column names if they contain a space, which is always a bad idea.

You also don’t need to use ‘’ around the actual values if the column type is a number. So if you was doing an update for example

UPDATE pictures SET newname = ‘file_new_name’ WHERE id = 2;

Just thought I’d contribute :slight_smile:


#6

you only need to use `` around your column names if they contain a space, which is always a bad idea.

You also need to use `` if the names you use are reserved words for mysql, such as order or status


#7

You also need to use `` if the names you use are reserved words for mysql, such as order or status

or data types like date – as in the example above!