Someone told me that when you are working with PDO, you cannot use "INSERT INTO .... SET" to insert data into database, because it will not work on databases other than MySQL. I'm not sure what exactly he means, maybe he means I should use the other method of inserting like,
INSERT INTO table (column1, column2) VALUES (?, ?)
I tried searching on the internet for this, but I couldn't find anything. Please let me know about this.
Thank you.
You should use the INSERT INTO table (column1, column2) VALUES (?, ?) statement instead of the INSERT INTO table SET column1=? statement, because that's the correct syntax for SQL based database languages. Although MySQL accepts it, others may not.
The INSERT INTO ... SET syntax is not part of the ANSI SQL standard and therefore is not supported as widely across different RDBMS implementations. If you are designing your application such that it is tightly coupled to MySQL, using this syntax would be OK. If you are trying to design such that your application is not tightly coupled with the RDBMS implementation, then you should use the more standard INSERT INTO table (columns) VALUES (values) syntax.
Positional parameters in PHP PDO is just fine. The other option is named parameters. If I remember correctly from what I've seen in the PDO C code, it is PHP and not the DBM that does the replacements.
http://php.net/manual/en/pdo.prepared-statements.php
As stated in this the only metioned difference, b/n mysql driver and others is stated below. Suppose this is the a simple, query:
<?php
$stmt = $db->query('SELECT * FROM table');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';
Now, let's read how the documentation states how/why that query can return count of affected_rows only when the mysql driver
NOTE: Though the documentation says this method is only for returning
affected rows from UPDATE, INSERT, DELETE queries, with the PDO_MYSQL
driver (and this driver only) you can get the row count for SELECT
queries. Keep this in mind when writing code for multiple databases.
This is because MySQL's protocol is one of the very few that give this
information to the client for SELECT statements. Most other database
vendors don't bother divulging this information to the client as it
would incur more overhead in their implementations.
So, there is that little difference, as far as I know.
Related
I'm working on a site in which I have to insert values in different table. so keeping this need in view, is it possible for me that can I use multiple query in single mysql_query in php or not.
for example:
mysql_query("insert into tableA (e-mail, name) values ('xxx', 'xxx'); insert into tableB (xxx, xxx, xxx) values ('value1','value2','value3')")
I want to run multiple queries in single statement. Please suggest some solution.
No, it is not possible. The obsolete mysql_* API only allows for one query to be executed at a time. To do this you need to use the mysqli API and mysqli_multi_query().
A single MySQL "INSERT" statement can support multiple VALUE tuples if they're for the same table.
mysql_query("insert into tableA (e-mail, name) values ('xxx', 'xxx'), ('yyy','yyy')")
However, what you're trying to do is not possible with the mysql_* functions.
Although the mysqli_* API allows you to run multiple queries at once, I recommend you AGAINST doing that for at least 2 reasons:
It's always a good (actually, great) idea to use prepared statements, for security reasons. Prepared statements can be used with the MySQLi API as well as with PDO.
As you can see from the docs for mysqli_multi_query(), getting errors from that function can be cumbersome. The function, indeed, returns only "false" if the first query fails; to get results for other queries you need to call another function.
In general, why would you need to combine multiple queries together? Eventually, the time you'd save would be minimal.
Instead, if your goal is having more than one query executed together, and having the whole set of queries fail if one fails, you can use transactions (which also can speed up inserts in some cases). Both MySQLi and PDO support transactions: see examples here for PDO http://php.net/manual/en/pdo.transactions.php
PS: in general, it's a good idea to avoid using mysql_* functions entirely, as those APIs are deprecated.
Welcome to PDO:
With PDO am able to do something like:
$sql = "
insert into tableA (e_mail, name) values (:e_mail, :name);
insert into tableB (xxx1, xxx2, xxx3) values (:xxx1, :xxx2, :xxx3)
";
Just have the Query Prepared first then VOILA!!
OR Using the Transaction method:
$con->beginTransaction();
$sql1 = "insert into tableA (e_mail, name) values (:e_mail, :name)";
$sql2 = "insert into tableB (xxx, fff) values (:xxx, :fff)";
$sql3 = "insert into tableC (qqq, bbb) values (:qqq, :bbb)";
$con->commit();
I have variable number of forms (name1,name2,name3...etc) and I need to put those data in corresponding colums (name1,name2, name3) so far I came with a this code:
if(isset($_POST["nombreItem"]) && count($_POST['nombreItem'])>0) {
foreach($_POST["ItemID"] as $value) {
$query = "INSERT INTO `inventarioStat` SET `$_POST[ItemID]` = `$_POST[1]` ";
mysql_query($query);
}
}
Whta Im doing wrong?
You aren't connected to a database
The correct INSERT syntax is: INSERT INTO table (column1, column2) VALUES ($val1, $val2)
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Use PDO or MySQLi - this article will help you decide which.
Learn about prepared statements to prevent against SQL injection (your code is vulnerable to this)
Use PDO or mysqli to CRUD your tables.
Use sanitization of inputs received from users in order to avoid SQL INJECTION.
Use PHP sanitize filters in order to increase your databse security, paired with PDO.
Better normalize your tables, it's not a good practice to have many columns but just fill a few of them. A table with NULL fields as a common practice, indicates a mediocre database architecture and poor performance. Maybe it's a better idea to traverse your design and then query by CASE or GROUP_CONCAT in order to get a PIVOT or cross tabuled table.
I am trying to use the zend db profiler to record the queries. I read the documentation from the zend website and it works fine except that I am not able to get the values for the insert and the update queries. I just see the query as below with the ? for values. I tried using the getQueryParams to atleast see if I can get the values in the array and it works only with getLastQueryProfile and not the getQueryProfile to get it for all queries. Can some one please let me know how I can get the "?" with the actual values? I am not concerned about the Array as anyways it doesn't do the purpose.
INSERT INTO `myTable` (`id`, `lname`, `fname`) VALUES (?, ?, ?)
thanks.
I don't think it's possible.
According to php's PDO Manual there's no way to retrieve a query after a prepare() statement. In the examples it's easy to understand because using the PDO manually you know the order of the parameters and have the statement. Looking after Zend clases (Zend_Db_Table_Abstract) i see that the order is maintained and that's the proper way because it uses question mark parameters.
Reading Zend_Db_Adapter_Pdo_* clases you should get it clearer
How to insert data into two or more tables?
Currently I am using this trick. (Let just assume that the syntax is correct)
$Sql1 = "insert into user";
$Sql2 = "insert into files";
$Sql3 = "insert into messages";
query $Sql1
query $$ql2
query $Sql3
So I am using this and I need to optimize.
Also, I think I need to use Foreign key? But I don't know how to do it on phpmyadmin.
and lastly:
This is all I want.
To insert data on the "user" table and then automatically the table "messages" and "files"
will have also an ID which is the same with the user.. That is why I use to 3 queries in my code.
Please help me.
Thanks in ADVANCE!
myb
It is perfectly fine to use multiple queries.
However, you should wrap the 3 queries into one transaction. That is, if one query fails for some reason, the effects of all previous queries (if any) can be rolled back so that your database stays in a consistent state.
Note: Transactions are not possible with MySQL's MyISAM tables. Additionally you have to use PHP's Mysqli (or PDO) to be able to use transactions. (I assume that you're not using some high-level data base abstraction layer.)
As to your question regarding foreign keys: As far as I know, it makes no difference when you're using the MyISAM engine for the tables in your database (which I presume), because MyISAM doesn't even support the explicit modeling of foreign keys. Other table engines like InnoDB, however, can use foreign keys to check certain constraints like "a message must always be associated with an existing person".
Here are some nice examples regarding foreign keys: http://www.postgresql.org/files/documentation/books/aw_pgsql/node131.html
This is the answer, I think : http://dev.mysql.com/doc/refman/5.1/en/example-foreign-keys.html
With mysql u can use LAST_INSERT_ID() or in php mysql_insert_id() function. Checkout this manual entries:
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
http://php.net/manual/en/function.mysql-insert-id.php
I am using mysql database for an application. I get some user details. Once user uses select keyword in his answer, the Insert query causes problems in mysql. I am using nearly 300 insert queries in my over all application. Select keyword makes problem.
How to solve it in easy way?
Thanks in advance
UPDATED:
$query = "INSERT INTO `feedback_entry_mailactivity_log` ( `subject`, `body_text`, `to_mail_id`, `from_mail_id`, `cc_mail_id`, `created_user_id`, `created_date_time`, `last_updated_user_id`, `last_updated_date_time`, `feedback_entry_id`, `feedback_id`, `account_id`, `section_id`)
VALUES ('".$subject."', '".$body_text."','".$to_mail_id."','".$from_mail_id."','".$cc_mail_id."','".$assign_to_userid."', NOW(),'".$assign_to_userid."', NOW(),'".$feedback_entry_id."','".$feedback_id."','".$this->account_id."','".$temp_sectionid."' );";
$this->db->execute($query);
In this case if $subject="select a tag";
Thus when I use keyword select insert query doesn't works
The problem is the use of string-generated SQL statement -- this can lead to incorrect escaping and injection attacks (or mis-behaviors) leading to errors like above. Imagine if one of the input variables -- the one with 'SELECT' in it -- contains the SQL string-escape character such as Wish this would' SELECT FAIL. (This might not be the exact problem in this case and the real problem could lay with some other layer trying to "protect" the use of the bad access method(s).)
To fix this problem correctly use PDO (or similar) and prepared-statements. (Jeremiah Willcock suggested mysqli_prepare).
The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).
Note: Incorrect "solutions" include mysql_real_escape_string and similar. There are very few -- perhaps none for static DQL -- cases when "manual escaping with SQL string-building" approaches like this should be used.
Happy coding.