So i recently starting learning PHP, and now im trying to get code into my database.
The data is input from the user through a form.
here is my code:
if(isset($_POST['submit'])) {
$blogtitle = $_POST['blogTitle'];
$blogcategory = $_POST['blogCategory'];
$blogcontent = $_POST['blogContent'];
// aanmaak date van de blog
$blogdate = date("d/m.Y");
// Checkt of alle velden zijn ingevuld
if (!empty($blogtitle) && !empty($blogcategory) && !empty($blogcontent)) {
//echo "je zit nu bij de query";
$addBlogQuery = mysql_query("INSERT INTO blog (blog_ID, blog_title, blog_category, blog_content, blog_date)
VALUES (NULL, $blogtitle, $blogcategory, $blogcontent, blogdate )");
if ($addBlogQuery) {
echo "blog added successfully";
}
else {
echo "something went wrong";
}
}
else {
$this->notFilledErrorAction();
}
}
For some reason it's not adding any data my database. My connection to my database is working properly, and i dont see a mistake in my query.
Does someone see an error in this code? or could help me figure out the problem?
You have a syntax error in your INSERT statement:
$addBlogQuery = mysql_query("INSERT INTO blog (blog_ID, blog_title, blog_category, blog_content, blog_date)
VALUES (NULL, $blogtitle, $blogcategory, $blogcontent, blogdate )");
You are missing a $ here------------------------^
You also need to wrap your variables in ' single quotes:
$addBlogQuery = mysql_query("INSERT INTO blog (blog_ID, blog_title, blog_category, blog_content, blog_date)
VALUES (NULL, '$blogtitle', '$blogcategory', '$blogcontent', '$blogdate' )");
Furthermore, the mysql_* API is now deprecated. Please read the big red box here. You should start using MySQLi or PDO now whilst it is still relatively easy to change.
You need to enclose strings ,date and DATETIME values with single quotes (').
And you have not enclosed in your SQL.
Please modify your SQL as:
$addBlogQuery = mysql_query("INSERT INTO blog (blog_ID, blog_title, blog_category, blog_content, blog_date)
VALUES (NULL, '$blogtitle', '$blogcategory', '$blogcontent', 'blogdate' )");
Mysql support only following date format:
YYYY-mm-dd
but your code has different format
$blogdate = date("d/m.Y");
Try the following:
$blogdate = date("Y-m-d");
And you have passed ID null, i think you have selected ID as primary key. primary key can not be null. if your ID field support auto-increment you don't need to pass anything.
$addBlogQuery = mysql_query("INSERT INTO blog (blog_title, blog_category, blog_content, blog_date)
VALUES ($blogtitle, $blogcategory, $blogcontent, blogdate )");
Hopefully it will work.
See the changes below and try again:
$blogdate = date("Y-m-d");
$addBlogQuery = mysql_query("INSERT INTO `blog` (`blog_title`, `blog_category`, `blog_content`, `blog_date`)
VALUES ('$blogtitle', '$blogcategory', '$blogcontent', '$blogdate' )");
Use more secure way , Use PDO - Stop using MYSQL_* it's deprecated
PDO escapes itself, you doesn't need to use mysql_real_escape_string
<?php
$user="root";
$pass="";
$db = new PDO('mysql:host=hostname;dbname=databasename', $user, $pass); //establish new connection
$sql ="INSERT INTO blog (blog_ID, blog_title, blog_category, blog_content, blog_date)
VALUES (NULL, ?, ?, ?, ?)";
try{
$stmt = $db->prepare($sql);
$stmt->execute(array($a, $b, $c, $d));
if($stmt->rowCount()>0){
//done
}
}catch(PDOException $e){
echo $e->getMessage();
?>
Before inserting into database you should sanitize you data to prevent SQL injection and XSS. Use this function:
function sanitize($data){
$data= htmlentities(strip_tags(trim($data)));
return $data;
}
Try following query there is no need to use php date function mysql has native support to date and time functions
INSERT INTO blog
(`title`, `category`, `content`, `date`, `id`)
VALUES
('Title here', 'category here','blog content here', NOW(), 1);
here is SQL test SQL Fiddle
$addBlogQuery = mysql_query("INSERT INTO blog (blog_title, blog_category, blog_content, blog_date) VALUES ($blogtitle, $blogcategory, $blogcontent, blogdate )");
It seems your mistake is insert the value of blog_id by NULL. blog_id column is the primary key. If you insert blog_id by NULL, then the data can't push to your database. Since blog_id is primary key, you don't need to insert blog_id manually. It will automatically inserted.
Related
I am trying to insert data into a database after the user clicks on a link from file one.php. So file two.php contains the following code:
$retrieve = "SELECT * FROM catalog WHERE id = '$_GET[id]'";
$results = mysqli_query($cnx, $retrieve);
$row = mysqli_fetch_assoc($results);
$count = mysqli_num_rows($results);
So the query above will get the information from the database using $_GET[id] as a reference.
After this is performed, I want to insert the information retrieved in a different table using this code:
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$session = session_id();
if($count > 0) {
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
The first query $retrieve is working but the second $insert is not. Do you have an idea why this is happening? PS: I know I will need to sanitize and use PDO and prepared statements, but I want to test this first and it's not working and I have no idea why. Thanks for your help
You're not executing the query:
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
it needs to use mysqli_query() with the db connection just as you did for the SELECT and make sure you started the session using session_start(); seeing you're using sessions.
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
$results_insert = mysqli_query($cnx, $insert);
basically.
Plus...
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
If that still doesn't work, then MySQL may be complaining about something, so you will need to escape your data and check for errors.
http://php.net/manual/en/mysqli.error.php
Sidenote:
Use mysqli_affected_rows() to check if the INSERT was truly successful.
http://php.net/manual/en/mysqli.affected-rows.php
Here's an example of your query in PDO if you'req planning to use PDO in future.
$sql = $pdo->prepare("INSERT INTO table2 (id, title, price, session_id) VALUES(?, ?, ?, ?");
$sql->bindParam(1, $id);
$sql->bindParam(2, $title);
$sql->bindParam(3, $price);
$sql->bindParam(4, $session_id);
$sql->execute();
That's how we are more safe.
I'm using mysqli in a PHP class.
I have this query to be executed:
INSERT INTO notifications (userid, content, uniq, link) VALUES (48, "[2014-07-30] Nomid has edited the post \"Somepost\"", "934512e1e9314d9c602a02a26114a625", "http://website/somepost")
It fails, showing the error:
You have an error in your query etc. to use near '"[2014-07-30] Nomid has edited the post \"Somepost\"", "934512e1e9314d9"'
But if I look in the DB, the new row is present.
The parameters are escaped using mysqli_real_escape_string():
$msg = $this->escape($msg);
$uniqid = $this->escape($uniqid);
$sql = "INSERT INTO notifications (userid, content, uniq, link) VALUES ($userid, \"$msg\", \"$uniqid\", \"$link\")";
// die($sql);
$this->query($sql);
I tried to check query execution with $mysqli->affected_rows and !$result of mysqli_query().
The fields types are
INT (11) for userid,
TEXT for content,
TINYTEXT for uniq and
TINYTEXT for link.
All of the TEXT fields have collation "utf8_general_ci".
I didn't create the table.
The strange thing is that if I look in the database, the query was successfully executed...
Why is this happening?
you sql should be like
$userid = $this->escape($userid);
$msg = $this->escape($msg);
$uniqid = $this->escape($uniqid);
$link = $this->escape($link);
$sql = "INSERT INTO notifications (userid, content, uniq, link) VALUES ('$userid', '$msg', '$uniqid', '$link')";
I am using to add data into DB. First i get the values from post and then insert it into table. The problem is that there are total 7 values but only 5 values added and 2 of them not inserted into the table. Here is my code
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {
$degree_title = $_POST['degree_title'];
$degree_year = $_POST['degree_year'];
$uni_name = $_POST['uni_name'];
$degree_level = $_POST['degree_level'];
$major_sub = $_POST['major_sub'];
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, $eme_uid, $degree_title, $degree_year, $degree_level, $major_sub, $uni_name)");
}
I echo the all values and all values are coming so why they all not inserted into table any idea. Thank
try:
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, '$eme_uid', '$degree_title', '$degree_year', '$degree_level', '$major_sub', '$uni_name')");
and i would highly recommend:
1) dont use mysql_ its deprecated, use mysqli_*
2) sanitze ALL values in _POST befor using in SQL statements.
if id is autoincrement then you dont need to insert it.
try this
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES ($eme_uid, $degree_title, $degree_year, $degree_level, $major_sub, $uni_name)");
My guess is that $degree_title and $uni_name doesn't get inserted because they are varchars. In that case you will have to put quotes around these values.
Mysql is kind of "forgiving" in the sence that it does not throw an error when using incorrect types in the sql-statement in relation to the actual type of the column.
Try:
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, $eme_uid, '$degree_title', $degree_year, $degree_level, $major_sub, '$uni_name')");
As mentioned before id doesn't have to be included (if id-column is autoincremental) in the insert-statement, and you should really learn mysqli or PDO.
I'm trying to put the time of a post into my database table but i can't get it to work. maybe someone here can explain what i'm doing wrong.
This is my code:
<?php
if (isset($_POST['upload_message'])) {
$message_title = $_POST['message_title'];
$message_content = $_POST['message_content'];
}
$table_name = "posts";
$add_query = "INSERT INTO $table_name (name, content, date) VALUES ('$message_title', '$message_content', 'SELECT NOW()')";
if (mysql_query($add_query)) { //executes query and error check
echo "het artikel staat in de database";
}
else { //error message
echo "fout bij het toevoegen" . "<br />" . mysql_error();
}
?>
and this is a screen shot of my db table : http://gyazo.com/17019f143eab6e5818752c33824bde29
When I run mysql_error is get the following message :
Incorrect datetime value: 'SELECT NOW()' for column 'date' at row 1
You don't have to SELECT NOW(), just NOW()
$add_query = "INSERT INTO $table_name (name, content, date)
VALUES ('$message_title', '$message_content', NOW())";
You should use prepared statements with binded parameters using mysqli_ or PDO.
NOW() is a mysql function, you don't have to "select it" just call it.
Replace the "SELECT NOW()" for just "NOW()".
INSERT INTO $table_name (name, content, date) VALUES ('$message_title', '$message_content', 'NOW()')
Or you can use CURRENT_TIMESTAMP
INSERT INTO $table_name (name, content, date) VALUES ('$message_title', '$message_content', CURRENT_TIMESTAMP);
Mysql_query is deprecated as of PHP 5.5.0.
Use PDO or Mysqli !
And secure your code, we can do injection sql.
i have a recipe table and ingredient table the primary key of both tables are auto increament and primary key of recipe is foreign key in ingredient. i post data from html to php.Note that my ingredient textboxes are generated dynamically and successfully post the data to php script. posted data is correct when i insert this data to table my query working fine but data is not added to mysql table. my code and output is
$sql = "insert into recipe (rec_id, Name, Overview,category, Time, Image) values ('', '$name','$overview','$category','$time','$TARGET_PATH')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
$rec_id = mysql_insert_id();
and for ingredient
$ingredient = $_POST['ingredient'];
$amount = $_POST['amount'];
$integer = 0;
while (count($ingredient)>$integer) {
if (($ingredient[$integer] <> "") && ($amount[$integer] <> "")){
$sql = "INSERT INTO `cafe`.`ingredients` (`ingredient_id`, `ingredient_name`, `ammount`, `rec_id`,)
VALUES ('', '".$ingredient[$integer]."', '".$amount[$integer]."', '$rec_id')";
mysql_query($sql);
echo $sql."";
}
else{
echo "ingredient number ".($integer+1)." is missing values and cannot be inserted.";
}
$integer = ($integer + 1);
}
when i echo the queries the out put is nsert into recipe (rec_id, Name, Overview,category, Time, Image) values ('', 'demo recipe','no overview','meal','10/12/10 : 13:02:33','http://www.localhost/cafe/pics/demo.gif')
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id,) VALUES ('', 'ingredient one', '3gm', '29')
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id,) VALUES ('', 'ingredient two', '3gm', '29')
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id,) VALUES ('', 'ingredient three', '3gm', '29')
but when i see the mysql table or retriew data from ingredient there is no data in ingredient.
You have an extra , after rec_id.
Remove it, so it looks like
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id) VALUES ('', 'ingredient one', '3gm', '29')
And you will be OK
There seems to be a syntax error in your code:
if (($ingredient[$integer] "") && ($amount[$integer] ""))
^^ ^^
Looks like you are missing a comparison operator.
You might want to verify if you are using a BEGIN call and not committing after INSERT. You can refer to http://www.devarticles.com/c/a/MySQL/Using-Transactions-with-MySQL-4.0-and-PHP/
in that scenario.
When insert doesnt throw exceptions and doesnt insert data there are I think a couple of options
1) you use transaction somewhere and rollback it
2) your select query is bad and data is there, but you just dont select it
remove cafe from the query
$sql = "INSERT INTO ingredients (`ingredient_id`, `ingredient_name`, `ammount`, `rec_id`,)
VALUES ('', '".$ingredient[$integer]."', '".$amount[$integer]."', '$rec_id')";