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

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

Related

Errors inserting values (such as URLs) into MySQL database WITH a URL

I am working on my website and I can't access myPhpAdmin right now, so I tried making a script for inserting values for a search thing. However, when I visit the link, website.com/search/create.php?l=link&d=description&t=title, I get an error. This one
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 'link, description, title)' at line 1
Here's what my script looks like.
$link = "https://website.com";
$description = "The homepage of the site";
$title = "Home";
// sql to create table
$sql = "INSERT INTO search (link, description, title) VALUES (".$link.", ".$description.", ".$title.")";
if (mysqli_query($conn, $sql)) {
echo "it's working";
} else {
echo "it's not working?" . mysqli_error($conn);
}
replace
$sql = "INSERT INTO search (link, description, title) VALUES ('".$link."', '".$description."', '".$title."')";
instead of :
$sql = "INSERT INTO search (link, description, title) VALUES (".$link.", ".$description.", ".$title.")";
you are trying to insert a string without '
it seems you are missing single quotation in SQL query, try the following:-
$sql = "INSERT INTO search (link, description, title) VALUES ('".$link.", '".$description."', '".$title."')";
Just Change the Query syntax in your code and check it ... Hope your error should be resolve.
// sql to create table
$sql = "INSERT INTO search (link, description, title) VALUES ('$link', '$description', '$title')";
Your code for inserting data into database table is wrong (assuming you already executed database connection query ($conn) and have 'search' table on database).
$sql = "INSERT INTO search (link, description, title) VALUES ('$link', '$description', '$title')";
You don't have to put concatenate operator ('.') inside your SQL query as you are not concatenating PHP and markup texts.

php variables in sql statements for login

I am fairly inexperienced with php and sql and I am having an issue with php variables in the insert into SQL statement.
I have a SQL Table :
CREATE TABLE users (
userID INT PRIMARY KEY,
username VARCHAR(256),
password VARCHAR(256)
);
This isn't the way I made the table as it was made in phpmyadmin but that is exactly how it is
the PHP is so , there is validation code aswell but it is not necessary:
$userUsername = $_POST["username"];
$userPassword = $_POST["password"];
$sqlinsert = "INSERT INTO users(username,password) VALUES ('$userUsername','$userPassword');";
$insertquery = mysqli_query($conn,$sqlinsert)
or die ("Problem with insert query");
Either you need to assign auto increment to primary key (userID).
Or you have to pass value for it like
$sqlinsert = "INSERT INTO users(userID, username, password) VALUES (1, '$userUsername', '$userPassword');";
if you have Auto Increment in ID then leave a blank first
$sqlinsert = "INSERT INTO users(userID,username,password)
VALUES ('','$userUsername','$userPassword')";
Or fill it with ID if not Auto Increment.
$sqlinsert = "INSERT INTO users(userID,username,password)
VALUES ('1','$userUsername','$userPassword')";
And as already mentioned in comments of your post your code is vulnerable to SQL Injection.
can use PDO Prepare Statement,too not necessarily ofcourse

conditional insert column values

i am having a problem with inserting records to my tables as i want to insert values into specific columns if only the value is not null, my query goes like this
i have tried:
INSERT INTO users(id,name,phone,address) VALUES($userId,$userName,$userPhone,$userAddress);
but it gives me error if on client side one of the parameters is not sent not all the time the client side send all the parameters (id,name,phone,address) i want to have some kind of condition instead of the handle all combinations to the query to go over this problem
You should be using prepared queries, but your immediate problem is that you aren't quoting anything:
$query = "INSERT INTO users(id,name,phone,address) VALUES('$userId', '$userName', '$userPhone', '$userAddress')";
Now, assuming you're doing this properly using a PDO connection, this is how you should be doing it to protect your database:
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$query = "INSERT INTO users (id, name, phone, address) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$result = $stmt->execute(array($userId,$userName,$userPhone,$userAddress));
if ($result) {
//success
} else {
//failure
}
Put ' inside VALUES () like '$userId'.
INSERT INTO users(id,name,phone,address) VALUES('$userId','$userName','$userPhone','$userAddress');
If parameter are not coming, then let it Insert Null in DB Table column. (Allow Null). And, if you don't want to insert NULL in DB Table column, then assign any default value before inserting.

Can't get mysql_insert_id() method to grab value I need

I'm trying to grab SID from the insert into the first table (stories) so I can insert that SID into the writing table in my second insert.
I think the way to do this is with mysql_insert_id(); after the first query, but the primary key that auto-increments is called SID. If mysql_insert_id() could grab that value I'd be all set.
What I am finding from a var_dump is that the $SID = mysql_insert_id(); is just returning the value "0" and I'm not sure why.
There is a column called ID in stores, but if it was grabbing that, the value would be "1". Either way, I wish this method could be written as mysql_insert_SID();
Any idea what I am doing wrong or how I can fix this? And yes, I know this is a deprecated approach, but first I want to figure out how before I worry about converting to PDO.
// Get values from form
$category = $_POST['category'];
$genre = $_POST['genre'];
$story_name = $_POST['story_name'];
$text = $_POST['text'];
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
$result = mysql_query($query);
$SID = mysql_insert_id();
$SID2 = "select stories.SID from stories where stories.SID=$SID";
$query2 = "INSERT INTO writing (ID, SID, text, position, approved)
VALUES('$user_ID', '$SID2', '$text', '1','N')";
$result = mysql_query($query2);
Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
(http://php.net/manual/en/function.mysql-insert-id.php)
But you aren't executing any query (via mysql_query()). You're just assigning your query to a variable. Try following:
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
mysql_query($query);
$SID = mysql_insert_id();
I think you've forgotten to execute the query most probably?
Try
$SID = mysql_insert_id();
after executing the query
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
$result = mysql_query($query); // executing
$SID = mysql_insert_id(); // order of queries is important
If you cannot get the value through mysql_insert_id() then try SELECT LAST_INSERT_ID(). Of course there will be a value if you have executed an insert query with AUTOINCREMENT (which you haven't done yet)

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.

Categories