Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query INSERT not working inserting values into my DB [duplicate]

I'm trying to insert some values into my DB but it's not working, i'm trying to figure out why it's not working but I'm an amateur php coder,

This is the code I'm using:

$insert = mysql_query
    ("
    INSERT INTO news(id,title,body,date,by)
    VALUES ('NULL','".$title."','".$body."','".$date."','".$by."')
    ");
    mysql_close($connect);

And the rows i'm trying to insert into are: id,title,body,date,by
but it's not showing up in the database or on my news page.

Can someone please help me?

like image 408
Aiden Ryan Avatar asked Mar 02 '11 18:03

Aiden Ryan


3 Answers

by is a special keyword. Try wrapping the column names in tick marks:

INSERT INTO news(`id`,`title`,`body`,`date`,`by`)
like image 125
mellamokb Avatar answered Oct 16 '22 02:10

mellamokb


I would expect id to be your primary key. It should not allow a null value. If it is auto incrementing you might try this:

$insert = mysql_query
    ("
    INSERT INTO news(title,body,date, by)
    VALUES ('".$title."','".$body."','".$date."','".$by."')
    ");

Others have noted by is a reserved word so you will need to quote it. It is best to avoid naming database objects using reserved words. Consider renaming the by column to author.

You should consider making changing the query into a prepared statement. See How can I prevent SQL injection in PHP?.

like image 2
BillThor Avatar answered Oct 16 '22 02:10

BillThor


Try calling mysql_error() to get the error message: http://php.net/manual/en/function.mysql-error.php

like image 1
markshep Avatar answered Oct 16 '22 03:10

markshep