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();
Related
For example, have a query like this:
<?php
$sql = "INSERT INTO oppgave
(username, besvarelse, modulid)
VALUES
('$username', '$besvarelse', '$modulid');
";
mysql_query($sql, $tilkobling);
?>
How can I do this:
If modulid row is not empty, echo "you have sent this modul before";
Try this:
<?php
$sql = "INSERT INTO oppgave(username, besvarelse, modulid)
select '$username', '$besvarelse', '$modulid'
from dual
where not exists (select modulid from oppgave where modulid='$modulid')";
$result=mysql_query($sql, $tilkobling);
if(mysql_affected_rows()==0){
echo "Failed to insert duplicate modulid";
}else{
echo "inserted";
}
?>
In this SQL Query, it will allow insert only if $modulid isn't already exist in database table. Such situation you can also handle by applying UNIQUE constraint to table column (but remember, it allows NULL value at once)
Best way to do this, is by not allowing duplicates.You can do this with your SQL QUERY.Build your query by this:
$sqlString ="INSERT INTO oppgave('" . $username . "', '" . $besvarelse . "', '" . $modulid . "')
SELECT username, besvarelse, modulid
FROM oppgave
WHERE NOT EXISTS (SELECT *
FROM oppgave
WHERE modulid IS NULL)";
Please check all names and tablenames first ;)
Hope this helps.If this the answer, please mark as answer.
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.
I am trying to inserts some values to the database in my php program but I am getting the error
Parse error: parse error, expecting `T_STRING' or `T_VARIABLE' or `T_NUM_STRING' in C:\wamp\www\php\books.php on line 9
mysql_query..
mysql_query("insert into books values('$_GET["title"]','$_GET["author"]','$_GET["edition"]','$_GET["publish"]','$_GET["isbn"]',)") or die(mysql_error());
get your values in variables like
$title = $_GET["title"];
$author = $_GET["author"];
then use query like this
mysql_query("insert into books values('$title','$author','$edition','$publish','$isbn',)") or die(mysql_error());
you are using nested double quotes
mysql_query("insert into books values('{$_GET["title"]}','{$_GET["author"]}','{$_GET["edition"]}','{$_GET["publish"]}','{$_GET["isbn"]}',)") or die(mysql_error());
or
mysql_query("insert into books values('$_GET[title]','$_GET[author]','$_GET[edition]','$_GET[publish]','$_GET[isbn]',)") or die(mysql_error());
The good query is :
mysql_query("insert into books values('" . $_GET["title"] . "','" . $_GET["author"] . "','" . $_GET["edition"] . "','" . $_GET["publish"] . "','" . $_GET["isbn"] . "')") or die(mysql_error());
There are non escaped quotes but also a comma which has nothing to do here, at the end of the query.
Maybe you should learn PHP and its syntax first.
My sql query when I check manually in phpmyadmin works fine, but when I try to handle it through php mysql_query throw me a syntax error. How to solve this issue?
Error message:
Invalid query:
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 'INSERT INTO scores( user_id ) VALUES (LAST_INSERT_ID( ))' at line 1
Whole query:
INSERT INTO users (id_fb, name, first_name, last_name, email, link, first_login)
VALUES ('1000001010101010', 'Bart Roza', 'Bart', 'Roza', 'lalalala#gmail.com','http://www.facebook.com/profile.php?id=1000001010101010','2011-05-07 11:15:24');
INSERT INTO scores( user_id ) VALUES (LAST_INSERT_ID( ));
My php function:
public function createUser()
{
$time = date("Y-m-d H:i:s");
$insert = "INSERT INTO users (id_fb, name, first_name, last_name, email, link, first_login) VALUES (" .
"'" . $this->me['id'] . "', " .
"'" . $this->me['name'] . "', " .
"'" . $this->me['first_name'] . "', " .
"'" . $this->me['last_name'] . "', " .
"'" . $this->me['email'] . "'," .
"'" . $this->me['link'] . "'," .
"'" . $time . "'); " .
"INSERT INTO scores( user_id ) VALUES (LAST_INSERT_ID( ));";
$result = mysql_query($insert);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $insert;
die($message);
}
}
EDIT:
Thanks for the solution!
Since mysql_query accepts only one query you need to split your query string into 2 separated queries and perform it with 2 mysql_query calls.
You can not run multiple queries in once using mysql_query function. you have to run these two queries with separate mysql_query call
mysql_query() sends a unique query
(multiple queries are not supported)
AS #zerkms and #Shakti said, mysql_query does not support multiple queries. If you want to use such functionality, consider migrating to mysqli. It supports multiple queries in a single packet by mysqli_multi_query
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.