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.
Related
I want to insert record in product table from two tables i.e adminlogin and product_category and with few php variables.my query is not working giving syntax error..please help
$sSQL4 =
"INSERT INTO product(user_id,category_id,product_id,title,price,product_img,product_status) Select admin_id from adminlogin where username='" .$user_name. "',
SELECT category_id,'',
'" .$title. "',
'" .$price. "',
'" .$file_name1. "',
'pending' from product_category WHERE category_name='" .$category. "'";
$result4= mysql_query($sSQL4);
The reason you're getting a syntax error is because you're not using valid SQL. The INSERT INTO ... SELECT syntax only works with a SINGLE select query.
Currently, you're basically linking 2 completely random queries, and mysql hasn't the slightest clue how to link them (even if it were possible).
What you want instead, is either to do 2 queries:
1. A query to get the username
2. The query to insert... select, while adding the username as a static string yourself.
Alternatively, you can use a sub-query to add the username. However, since the subquery is repeated for every single row inserted, this is actually a lot slower(!).
With a subquery, your query would look like:
$sSQL4 = "INSERT INTO product(user_id,category_id,product_id,title,price,product_img,product_status) SELECT (SELECT admin_id from adminlogin WHERE username='" .$user_name. "'), category_id,'','" .$title. "','" .$price. "','" .$file_name1. "','pending' FROM product_category WHERE category_name='" .$category. "'";
$result4 = mysql_query($sSQL4);
With 2 queries, you would get something like:
$q = mysql_query("SELECT admin_id FROM adminlogin WHERE username='" . $user_name . "'");
$adminId = mysql_fetch_object($q)->admin_id;
$sSQL4 = "INSERT INTO product(user_id,category_id,product_id,title,price,product_img,product_status) SELECT '".$adminId."', category_id,'','" .$title. "','" .$price. "','" .$file_name1. "','pending' FROM product_category WHERE category_name='" .$category. "'";
You are using wrong syntax. Use 'INSERT INTO(col1,col2) Values(val1,val2)'
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();
mysql_query("INSERT INTO questions (question_no)
VALUES ('" . mysql_real_escape_string($i) . "')
WHERE question_text LIKE ('" . mysql_real_escape_string($val) . "')")
or die('Error, insert query failed');
I'm getting the "Error, insert query failed" :(
You cannot use WHERE clause in INSERT.
What did you want to achieve with your WHERE clause?
Update:
If you want to update an existing record, use this:
UPDATE questions
SET question_no = 'mysql_real_escape_string($i)'
WHERE question_text LIKE 'mysql_real_escape_string($val)'
( quote the query for PHP appropriately, of course )
mysql_query("insert into questions (question_no) VALUES ('" . mysql_real_escape_string($i) . "') ")or die('Error, insert query failed');
no need to add where clause in insert query.
Or use update query to make change in existing records
mysql_query("updat questions set question_no = '" . mysql_real_escape_string($i) . "' where question_text like '" . mysql_real_escape_string($val) . "' ")or die('Error, update query failed');
You should change it to:
mysql_query("insert into questions (question_no)
VALUES ('" . mysql_real_escape_string($i) . "') ")
or die('Error, insert query failed');
Note, that where clause in insert values statement is senseless.
Take a look at mysql doc regarding inserting a rows. Construction You were trying to use is invalid.
Can anyone show me a query in MySQL that would delete rows from all available columns.
I use this to insert rows:
$sql = "INSERT INTO " . KEYS . " // KEYS is a constant
(key, user_id, time, approved)
VALUES ('" . $randkey . "', '" . $user_id . "', '" . $time . "', '0')";
I need the opposite of this now, delete created rows.
delete from <table> where ....
Keep in mind that the delete statement is always for an entire row.
Using similar syntax sql = "DELETE FROM " . KEYS . " WHERE 1=1";
Replace 1=1 with the conditions for the row you want to delete or it will delete all rows.
Also, it's good to get out of the habit of just dropping variables into SQL as soon as possible, because it will open your code up to SQL Injection attacks. Look into using parameterized queries.
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.