Odd Mysql issue on insert - php

Hy all,
Not sure what's going on here, but if I run this:
$query = 'INSERT INTO users
(`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`)
VALUES
("'. $user_id . '", "' . $first_name .'", "'. $second_name . '", "' . $date . '", "' . $date . ");';
$result = mysql_query($query);
I get no return, but if I change it to this it's fine:
$query = 'INSERT INTO users (`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`)
VALUES ("21021212", "Joe", "Bloggs", "20090202", "20090202");';
$result = mysql_query($query);
User id = bigint(20)
first name = varchar(30)
second name = varchar(30)
date = int(8)
At first I thought it was a issue with the vars but they are exactly the same and still don't work.
Any help appreciated.

Get into the habit of escaping all database inputs with mysql_real_escape_string- really, you should use some kind of wrapper like PDO or ADODb to help you do this, but here's how you might do it without:
$query = sprintf("INSERT INTO users ".
"(id, first_name, second_name, register_date, lastlogin_date)".
"VALUES('%s','%s','%s','%s','%s')",
mysql_real_escape_string($user_id),
mysql_real_escape_string($first_name),
mysql_real_escape_string($second_name),
mysql_real_escape_string($date),
mysql_real_escape_string($date));
$result = mysql_query($query);
and also check for errors with mysql_error
if (!$result)
{
echo "Error in $query: ".mysql_error();
}

What's the result from "mysql_error()"? Always check this, especially if something doesn't seem to be working.
Also, echo out $query to see what it really looks like. That could be telling.

Maybe the value of $date was "1111'); DELETE FROM users;"?
Seriously though? The problem is that isn't how you interact with your database. You shouldn't be passing in your data with your query. You need to specify the query, the parameters for the query, and pass in the actual parameter values when you execute the query. Anything else is inefficient, insecure and prone to bugs like the one you have.
By using PDO or something that supports parametrized queries, you'll find these kinds of issues go away because you are calling the database property. It is also much more secure and can speed up the database.
$sth = $dbh->prepare("INSERT INTO users (`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`) VALUES (?,?,?,?,?)")
$sth->execute(array($user_id ,$first_name , $second_name , $date, $date ));

In addition to echoing the query and checking mysql_error() as #GoatRider suggests:
Are you escaping your data properly? See mysql_real_escape_string()
You shouldn't end your queries with a semicolon when using mysql_query()

in $query = 'INSERT INTO users (id, first_name, second_name, register_date, lastlogin_date) VALUES ("' . $user_id . '", "' . $first_name . '", "' . $second_name . '", "' . $date . '", "' . $date . '");
are u giving the correct date format?? it might be the issue. otherwise the syntax is all fine.

Related

Trouble specifying my tablename inside query because of dot notation

I'm having trouble specifying my tablename inside the following query.
$sql = "INSERT INTO db269193_crud.posts (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
The tablename is: db269193_crud.posts. I can't specify the table name as 'posts' because of my hostingprovider. They only allow me to specify it in conjunction with my databasename (which is db269193).
So the table name becomes: db269193(dot)posts. This dot however keeps lighting up in my editor as an incorrect syntax.
I need someone's help to tell me if I specified the table name correctly or if I have to use a variable to hide the dot notation like:
$tablename = 'db269193.crud';
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
You can put the entire name in backticks to escape it:
INSERT INTO `db269193_crud.posts` (post_title, description)
VALUES ('" . $title . "', '" . $description . "')
As for the rest of your statement, I would encourage you to use parameters instead of munging the query string. By putting random strings in the query, you are just inviting syntax errors and SQL injection attacks.
I can't specify the table name as 'posts' because of my hostingprovider. They only allow me to specify it in conjunction with my databasename (which is db269193).
I pretty much doubt that as it would require DB changes which simply make no sense. I assume that it's your fault as you did not select DB to use in the first place. Check how you connect and ensure you provide DB name as well or at least you mysqli_select_db() or equivalent.
$tablename = 'db269193.crud';
You can use backticks when name of table or column conflicts or is reserved word:
$tablename = '`db269193.crud`';
or
$tablename = '`db269193`.`crud`';
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
You are complicating simple strings with unnecessary concatentation. This will work and is less error prone:
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('{$title}','{$description}')";
however you are still seem to be vulnerable to sql injection here. I'd recommend switching to PDO.

data from a json object not inserting into mysql in php foreach loop

I am trying to insert the results from a json array into MySQL using
foreach ($feed->items as $item) {
$query = "insert into data(id,url,keyword)values ($item->id, $item->url,$item->kind)";
$result = mysql_query($query);
echo $result;
}
I have confirmed the database details are OK and the $items are correct.
Can anyone point me in the right direction? I am fairly new to PHP so any help is appreciated.
You need to escape the values in the SQL:
$query = "insert into data(id,url,keyword)values ('" . mysql_real_escape_string($item->id) . "', '" . mysql_real_escape_string($item->url) . "' , '". mysql_real_escape_string($item->kind) . "')";
this adds quotation marks ' around the variables so that the SQL can be parsed at all
This prevents SQL injection.
You need to wrap your variabels in your query :
$query = "insert into data(id,url,keyword)values ('{$item->id}', '{$item->url}', '{$item->kind}')";

Unknown Column in 'field list' php mysql

I've looked everywhere but I cant find an answer for this question. I've seen several solutions that have helped people, but when I try it, I see I'm doing everything right and have nothing to fix. I'm making a forum and i'm trying to insert these into a mysql table but every time I try it says:
Unknown column '6c09e4fe82d47011bf9b25b05946307f' in 'field list'.
The long code is a user id for one of the users, and Its supposed to get inserted, but for some reason its looking for a column with that name. I've only gotten up to the first query with an error so the second part might be totally fine, I don't know.
$sql = "INSERT INTO
topics(topic_subject,
topic_date,
topic_cat,
topic_by)
VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "',
NOW(),
" . mysql_real_escape_string($_POST['topic_cat']) . ",
". $_SESSION['userid'] ."
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'You did everything right, yet there is an error. WEIRD RIGHT???<br /><br />' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
//the first query worked, now start the second, posts query
//retrieve the id of the freshly created topic for usage in the posts query
$topicid = mysql_insert_id();
$sql = "INSERT INTO
posts(post_content,
post_date,
post_topic,
post_by)
VALUES
('" . mysql_real_escape_string($_POST['post_content']) . "',
NOW(),
" . $topicid . ",
". $_SESSION['userid'] ."
)";
$result = mysql_query($sql);
You're not quoting the string in the INSERT:
". $_SESSION['userid'] ."
Should be:
'". $_SESSION['userid'] ."'
" . mysql_real_escape_string($_POST['topic_cat']) . ",
needs to be enclosed in quotes
'" . mysql_real_escape_string($_POST['topic_cat']) . ",'
Just echo $sql; and you will see your error.
Also make sure you session_start();

Error: Duplicate entry '1' for key 'r_id'

Here's the table structure
CREATE TABLE IF NOT EXISTS `result` (
`res_id` int(11) NOT NULL AUTO_INCREMENT,
`s_id` int(10) NOT NULL,
`i_id` int(6) NOT NULL,
`r_status` text NOT NULL,
`r_score` decimal(6,0) NOT NULL,
PRIMARY KEY (`res_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
I've searched for a solution and have tried on different occasions, building the table from scratch, drop and import it back, checked the index. As you can see, I've renamed the id to res_id but when I run it on the browser the error still shows r_id.
If it makes a difference, when the id is not set to auto increment, the same error pops up.
Here's the code snippet for the page where I want to insert into the database.
//retrieve existing r_id
$sql_res = "SELECT res_id FROM result ORDER BY res_id DESC LIMIT 1";
$query_res = mysql_query($sql_res) or die("MySQL Error: " . mysql_error());
$data_res = mysql_fetch_assoc($query_res);
$resid_count = $data_res['res_id']+1;
//echo "<br>Result: " . $resid_count;
// insert result to table
$sql_result = "INSERT INTO result (res_id, r_score, s_id, i_id) VALUES ('" . $resid_count . "', '" . $correct . "', '" . $id . "', '" . $ins_id . "')";
mysql_query($sql_result) or die ("Error: " . mysql_error());
EDIT: I changed the code like you guys suggested. Took the res_id out from the INSERT. It still says duplicate entry for r_id. I went ahead for trial and error and created another table 'score' with the same structure to replace 'result'. Was wondering if the same table name was giving it problem (could running the page many times cause this?). Same outcome with the score table.
Any help would be greatly appreciated. I'm stuck here and cannot proceed with my project. Thanks.
Atikah
Since res_idis AUTO_INCREMENTI suggest that you replace your insert query by this:
$sql_result = "INSERT INTO result (r_score, s_id, i_id) VALUES ('". $correct . "', '" . $id . "', '" . $ins_id . "')";
try this
$sql_result = "INSERT INTO result ( r_score, s_id, i_id) VALUES ( '" . $correct . "', '" . $id . "', '" . $ins_id . "')";
res_id will be automatically inserted without your inserting
EDIT.
If you want just insert then you dont need those lines , just remove them, because you are using them for knowing the last res_id . since res_id as i said before its auto_increment. it will increment automatically
$sql_res = "SELECT res_id FROM result ORDER BY res_id DESC LIMIT 1";
$query_res = mysql_query($sql_res) or die("MySQL Error: " . mysql_error());
$data_res = mysql_fetch_assoc($query_res);
$resid_count = $data_res['res_id']+1;
Make sure you don't use apostrophes in your SQL where you use numerics (int). This could cause trouble. And res_id should not be involved at all, because that's the point with having autoincremental columns (You don't have search for the next id in the database with PHP-code, DB takes care of that)
Your code could be translated into two lines:
$sql_result = "INSERT INTO result (r_score, s_id, i_id) VALUES (" . $correct . ", " . $id . ", " . $ins_id . ")";
mysql_query($sql_result) or die ("Error: " . mysql_error());
OR (variables inside quotes gives the actual values)
$sql_result = "INSERT INTO result (r_score, s_id, i_id) VALUES ($correct, $id, $ins_id)";
mysql_query($sql_result) or die ("Error: " . mysql_error());
and of course - don't use mysql_* - functions, cause they're deprecated. Use PDO or Mysqli instead with parameters so you could avoid SQL injection in a safe way. The code you've got is vulnerable to SQL injections.

Best way to write PHP SQL Update Statement

I have this PHP SQL statement:
$updateCategory = "UPDATE category
SET name=".$name.", description=".$description.",
parent=".$parent.", active=".$active."
WHERE id=".$catID."";
What is the best way to write this?
Thanks,
Chris.
I suggest you use prepared statements instead of concatenating the query string together:
$sql = 'UPDATE
category
SET
name=:name,
description=:description,
parent=:parent,
active=:active
WHERE
id=:catID';
if you are using PDO, which I strongly suggest, you would then call it like this:
$params = array(
':name' => $name,
':description' => $description,
':parent' => $parent,
':active' => $active,
':catID' => $catID
);
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
You might ask, "why all this hassle?" The advantages of this approach are quite overwhelming:
You don't have to care about SQL injection, since the database driver now handles the correct transformation of the input parameters
You don't have to care about escaping special characters, but you can concentrate on what you want to achieve rather than on how to achieve it :-)
You could format it like this to make it more readable.
$updateCategory = "
UPDATE
category
SET
`name` = '" . $name . "',
`description` = '" . $description . "',
`parent` = '" . $parent . "',
`active` = '" . $active . "'
WHERE
`id` = '" . $catID . "'";
I find that concatenating queries causes me major headaches with syntax errors-- all those quotes and dots sprinked around like pepper. Here's how I would write the query:
$updateCategory = "
UPDATE category
SET catname = '$name', description = '$description',
parent = '$parent', active = '$active'
WHERE id = '$catID'";
Note that "name" is a reserved word and should not be used as a column name. Also if id is an integer, $catID doesn't need to be quoted.
You can try:
$update = "update table_name SET name = '$name', email = '$email', password = '$password', phoneno = '$phoneno' WHERE id = '$id'";

Categories