insert with multiple select statements and php variables - php

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

Related

Get ID of an inserted row in sql

I am creating a forum service ( https://www.orbitrondev.com/forum/ )
When someone creates a new thread it will execute:
// Example values
$UserID = 23123;
$ForumID = 1;
$ThreadName = 'Example title';
$sQuery = 'INSERT INTO threads (user_id, board_id, topic, time, lastPostUserId, lastPostTime)
VALUES ("' . $UserID . '", "' . $ForumID . '", "' . $ThreadName . '", "' . $time . '", "' . $UserID . '", "' . $time . '")';
The ID is in the column thread_id
Now I have to get the ID (thread_id) of the inserted row. So I can create a post, and to create a post I need the ID.
I thought about getting the last inserted thread id an adding 1 so I have the id, but SQL looks finer :P
How can I know the thread_id value for the newly inserted row?
You should use mysqli::$insert_id.
Where $mysqli is your connection;
$result = $mysqli->query($sQuery);
$lastid = $mysqli->insert_id;
Although you should use prepared statements when inserting data into the database.
Note: You need to have an auto incremented ID field in the database for this to work.
You have;
$oResult = $Database->query($sQuery);
$ThreadID = $oResult->insert_id;
which will not work.
You should use the connection to find the last inserted ID, like this;
$oResult = $Database->query($sQuery);
$ThreadID = $Database->insert_id;
Hope this helps.
You can retrieve the most recent AUTO_INCREMENT value with the
LAST_INSERT_ID() SQL function or the mysql_insert_id() C API function.
These functions are connection-specific, so their return values are
not affected by another connection which is also performing inserts
http://dev.mysql.com/doc/refman/5.1/en/example-auto-increment.html
mysqli::$insert_id -- mysqli_insert_id — Returns the auto generated id
used in the last query
http://php.net/manual/en/mysqli.insert-id.php

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.

Escaping a string being inserted into Mysql

I have tried all combinations of single quotes, double quotes etc but the following code keeps erroring with sql syntax error. The en and cy are paragraphs of text. I think I must be missing something obvious but I cant see it. Any suggestions?
$insert_dana = mysql_query("UPDATE Contributor (Summary_en,Summary_cy) VALUES ('" . mysql_real_escape_string($insert[en][0]) . "','" . mysql_real_escape_string($insert[cy][0]) . "') WHERE id='$insert[id]'");
You mixed insert and update statement syntax. Use this one
$insert_dana = mysql_query("UPDATE Contributor set Summary_en = '" . mysql_real_escape_string($insert[en][0]) . "', Summary_cy = '" . mysql_real_escape_string($insert[cy][0]) . "' WHERE id='$insert[id]'");
you're confusing the UPDATE- and the INSERT-syntax. for UPDATE, it's like:
UPDATE
table
SET
field = 'value'
WHERE
...
while an INSERT looks like:
INSERT INTO
table
(field)
VALUES
('value')
you can't write an UPDATE with (field) VALUES ('value')-syntax.

MySQL - Delete a row, how?

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.

Odd Mysql issue on insert

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.

Categories