MY sql query not working fully - php

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.

Related

php insert mysql_query get id

In PHP 4, how can I easily get the last id after an insert in db?
For example:
$queryInsert = "INSERT INTO `table` (`id`, `info`) VALUES (NULL, '".$INFO_VAR."');";
mysql_query($queryInsert) or die (mysql_error());
use mysql_insert_id();, you find the doc here

MySql connect. What to do?

I am really new to php and I am trying to use simple insert to my mysql database from the form.
I know that this mysql connection/insertion is dangerous and not used anymore. so can anyone please help me with this simple thing? I tried to google, but nothing is working so far :/
<?
$text=$_POST['name'];
$text=$_POST['surename'];
mysql_connect("localhost", "db_name", "pass") or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$result = mysql_query("INSERT INTO `table` (name, surename)
VALUES (NOW(), '".mysql_real_escape_string($name)."', '".mysql_real_escape_string($surename)."')");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
Maybe change
$text=$_POST['name'];
$text=$_POST['surename'];
to
$name = $_POST['name'];
$surename = $_POST['surename'];
PS: And also your column names don't match your values. Your query, after inserting params
"INSERT INTO `table` (name, surename) VALUES (NOW(), '".mysql_real_escape_string($name)."', '".mysql_real_escape_string($surename)."')"
will probably look like this
INSERT INTO `table` (name, surename) VALUES (NOW(), 'Jhon', 'Wick')
As you can see there's name, surename (which probably should be surname) and (NOW(), 'Jhon', 'Wick'). So either add a column (if you have that column in your database):
INSERT INTO `table` (created_at, name, surename) VALUES (NOW(), 'Jhon', 'Wick')
or remove NOW() from your values
INSERT INTO `table` (name, surename) VALUES ('Jhon', 'Wick')

INSERT INTO runs only 1 time?

Here's my code:
$con=mysqli_connect("localhost","name","pass","bird") ;
$result = mysqli_query($con,"SELECT * FROM bird");
mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values (0,'d','cwer','73')");
the first time, I could see the the values were added but when I reloaded, it didn't do any more, is it supposed to be like this ?
So if I want it to run every time I reload, how can I do that?
You probably have a unique constraint against your id column (or another column in that query) and when you try to add a second row using the same ID it is rejected by MySQL.
You should be doing error checking in your code. You should be checking to see how many rows were affected by your insert (using mysqli_affected_rows()) and, if the number is zero, getting the error message from MySQL (using mysqli_error()).
$result = mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values (0,'d','cwer','73')");
if (mysqli_affected_rows() === 0) {
echo mysqli_error($con);
}
#DaveChen's comment above is a good solution to your (potential) problem. If it isn't already, make your id column auto increment and then leave it out of your query.
mysqli_query($con,"INSERT INTO 'bird' (`name`, `latin`, `number`) values ('d','cwer','73')");
If your id column is aut_increment and unique: change your code to:
$con=mysqli_connect("localhost","name","pass","bird") ;
$result = mysqli_query($con,"SELECT * FROM bird");
mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values ('','d','cwer','73')");

Query not working - INSERT INTO

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.

Wrong SQL Syntax? [duplicate]

This question already has answers here:
MySQL, safely using reserved word in query [duplicate]
(2 answers)
Closed 9 years ago.
I am building a small Twitter clone for personal use, and I have so trouble with it.
Fist, I want to show you my SQL structure of the table "poke_history":
http://puu.sh/3Sci0.png
This is the command I use to insert the values into a table (in PHP):
$insert = "INSERT INTO poke_history (id, from, time, reason) VALUES ('".$to_id."', '".$from_id."', '".$time."', '".$reason."')";
mysql_query($insert) or die(mysql_error());
This is the annoying error that I am getting:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from, time, reason) VALUES ( '1'' at line 3.
Let me clarify some things.
$to_id is a number.
$from_id is a number.
$time is a number (coming from PHP's time()).
$reason is a text string.
I am using MySQL and PHP5.
Try to quote your column identifiers like
INSERT INTO poke_history (`id`, `from`, `time`, `reason`) ...
Everything inside `` is considered to be a "identifier" not a language keyword. From the SQL-syntax it should be clear that after INSERT INTO tablename cannot come a FROM, but the MySQL sometimes needs this kind of guidance (and other sql parsers, too).
credit to mario as well:
from is a reserved keyword. Use backticks to escape them.
for example
`from`
INSERT INTO table (`from`) ....
So your code would like this:
$insert = "INSERT INTO poke_history (`id`, `from`, `time`, `reason`) VALUES ('".$to_id."', '".$from_id."', '".$time."', '".$reason."')";
mysql_query($insert) or die(mysql_error());
$insert = "INSERT INTO poke_history (`id`, `from`, `time`, `reason`) VALUES (".$to_id.", ".$from_id.", ".$time.", '".$reason."')";
mysql_query($insert) or die(mysql_error());
Numbers don't need to be quoted. Only strings.
Also don't use mysql, it's deprecated. Better use PDO, with prepared statements, to avoid issues like this.
You should try to use prepared statements to prevent SQL injection.
$query = "
INSERT INTO
poke_history (`id`, `from`, `time`, `reason`)
VALUES
(:id, :from, :time, :reason)";
$db = new PDO("mssql:host=sqlserver;dbname=database", "username", "password");
$statement = $db->prepare($query);
$parameters = array(
":id" => $name,
":from" => $from,
":time" => $time,
":reason" => $reason
);
$statement->execute($parameters);
I think that you forgot to add * in between INSERT and INTO, here is the fixed script:
$insert = "INSERT * INTO poke_history (id, from, time, reason) VALUES ('".$to_id."', '".$from_id."', '".$time."', '".$reason."')";
mysql_query($insert) or die(mysql_error());
The reason why you are getting the error is because you are trying to use a built in function name for one of your columns. Say you have the following CREATE TABLE...
CREATE TABLE customers
(
name varchar(80),
streetAddr varchar(160),
"from" varchar(60),
);
Notice that to create the table I had to put the column from in quotes. Now if you wanted to insert a row into this table, your insert statement should look like the following:
INSERT INTO ShoppingFun.dbo.customers
(
name,
streetAddr,
"from"
)
VALUES
(
'MRBubbleGum',
'1061 SW BubbleGumVillage St',
'yourmom'
)

Categories