sql query misses out two columns within the database - php

Ok Hi I have a slightly weird problem that I cannot figure out mysql query posts the uniq_id in the title column instead of its own and the title, blurb and uniq_id end up empty.
to start off with i create a uniq_id in php and then assign this to be a value within a hidden field within a form this is the code:
$uid = uniqid();
/*echo $uid;*/
echo " <input type=\"hidden\" value=\"$uid\" name=\"Uniq_id\"/>";
this is then posted using the form submit button,
then on the next page $_POST catches all of the values and turns them into variables this is the code for that:
$Title = $_POST['Title'];
$Blurb = $_POST['Blurb'];
$Subject = $_POST['cat'];
$Section = $_POST['typ'];
$Principle = $_POST['princ'];
$Verify = $_POST['verification'];
$Career = $_POST['career'];
$Job = $_POST['job'];
$Uniq_id = $_POST['Uniq_id'];
the variables are then used within this page within the sql query bellow which is ment to post these values into the database the function below is the one that is run when you click the submit button
public function addNewRecord($Subject, $Section, $Principle, $Job, $Career, $Title, $Blurb, $Uniq_id)
{
$sql = "INSERT INTO `careersintheclassroom`.`media` (`media_id`, `subject_id`, `section_id`, `principle_id`, `title`, `blurb`, `verified`, `media_uniqid`)
VALUES (NULL, '".$Subject."', '".$Section."', '".$Principle."', '".$Title."', '".$Blurb."', '0', '".$Uniq_id."')"; // sql query
return mysql_query($sql, $this->conn); // connection to database and also getting the results from query
}
when it posts the values to the page with this function it prints the values on a page showing me all the values this is one of them.
INSERT INTO `careersintheclassroom`.`media` (`media_id`, `subject_id`, `section_id`, `principle_id`, `jobrole_id`, `career_id`, `title`, `blurb`, `verified`, `media_uniqid`)
VALUES (NULL, '1', '1', '1', '2', '2', 'Title1', 'Blurb1', '0', '532061df6b80d');File is valid, and was successfully uploaded.
Now in the database it does something strange it posts in the first 4 values correctly then it inserts the Uniq_id into the title doesn't insert anything into blurb then put the correct value into verified and then leave the last column blank to,

What is the type of the verified field?
Try this, notice the quotes around 0:
VALUES (NULL, '".$Subject."', '".$Section."', '".$Principle."', '".$Title."', '".$Blurb."', '"0"', '".$Uniq_id."')"; // sql query

Hi Guys thanks for all of the answers I have figured out what the problem is I have figured out that my syntax for the mysql query was wrong I used phpmyadmin to create the php code and then altered it to fit the functions but this was wrong the code i was using was:
$sql = "INSERT INTO `careersintheclassroom`.`media` (`media_id`, `subject_id`, `section_id`, `principle_id`, `title`, `blurb`, `verified`, `media_uniqid`)
VALUES (NULL, '".$SUBJECT."', '".$SECTION."', '".$Principle."', '".$Title."', '".$Blurb."', '0', '".$Uniq_id."')";
instead the correct code that it should be is
$sql = "INSERT INTO media (media_id, subject_id, section_id, principle_id, title, blurb, verified, media_uniqid)
VALUES ('NULL', '".$Subject."', '".$Section."', '".$Principle."', '".$Title."', '".$Blurb."', '0', '".$Uniq_id."')";
As you can see the columns have got `` around them this is wrong so removing them inserts the details correctly into the columns
Thanks for everything guys you have helped a lot.

Is it possible that the "title" column is configured to insert a guid for every row insert. Check the column definition for title. Also did you verify that the Blurb and media_uniqueid columns values passed on to the function to be inserted are not null/blank for some reason.. Just checking..

Related

SQL INSERT fails even if the new row is in the DB?

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')";

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.

PHP : how to insert (into an Sql table) a variable and concatenate it with the date function

i've been trying to insert a row into an Sql database table , and that row's last column is supposed to contain a variable and i can't figure out how to concatenate that variable with a date function. The problem becomes the single quote marks
$SQL = "INSERT INTO news VALUES (NULL, '$user', '$text'.'date('Y-m-d H:i:s')')";
That $text is supposed to have a "date now" function called right after it so that i would have the date that it was inserted into the table...
Thanks
Try this:
$sql = "INSERT INTO news VALUES (NULL, '$user', '$text<br>".date('Y-m-d H:i:s')."')";
You can try this
$SQL = "INSERT INTO news VALUES (NULL, '$user', '".$text." now()')";

Insert query does't insert data to mysql database table

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')";

Categories