Combining two PHP sql statements into one - php

I'm after a little help in the quest for cleaner code...
Current code which is working fine. Wondering if I can make it into one SQL statement as opposed to two...
$sql = "INSERT INTO table_a (1,2,3,4) VALUES ('$1','$2','$3','$4');";
$result = mysql_query($sql,$mysql_link);
$id = mysql_insert_id();
$sql2 = "INSERT INTO table_b (1,2,3,4) VALUES ('$id','$5','$6','$7');";
$result2 = mysql_query($sql2,$mysql_link);
How can I combine these two to work within my current php script?
Thanks!

An insert in two different tables is not possible.
If you want to reduce your query count you may have to reconsider your database structure.

As mentioned above, you can't combine them, because inserts are in 2 different tables, although you could write a stored procedure (with necessary parameters) containing both of these queries and call that procedure in PHP instead of writting those statements... It would help to tell the reason you want to do that, because i can't understand if you want to get more compact (reusable) code, or improve the performance of your DB...

When I see another question of this kind, I am always wondering, why noone asks how to combine ALL sql queries of the script into one. All SELECTs, INSERTS, UPDATES. Wouldn't it be logically?
What's the strange desire to combine? What's the point in it? What's wrong in 2 separate queries?
When you eat, do you mix a salad, a soup, a main dish, a drink into one bowl and then consume it? No? Why do you want to put all the queries into same bowl then?

Related

A column with implanted PHP functionality

Lets say I have this PHP function:
function strlow($string){
strtolower(trim($string));
}
Now lets say I have a table with 2 columns [id - title] and I want to make all titles that are going to be inserted into the table in lowercase, The usual way is
$title = strlow($title);
$query = "INSERT INTO table (title) VALUES ($title);
Is there for example a way to implant in the column itself in the database the function, So instead of doing the strlow() by the PHP, the Database does it?
If yes, I wish for an example built on mine.
You could update your query to handle this if you really wanted (but I would still rather do this in the application layer) using the MySQL TRIM and LOWER commands:
INSERT INTO table (title) VALUES (TRIM(LOWER(($title)))
The reason I say I would rather do this in the application layer is that if you decide to switch database systems in future, you need to remember to port over all your database formatting rules such as these at that time too which although doesn't seem too bad now, trust me, in the future, you will forget.
In addition to this, if you ever want to add further logic to what you are putting in to the database you will likely find your options more limited in MySQL than you will in your application layer.
Also, please for my sanity look up how to use parametrized queries because you are wide open to SQL injection attacks at the moment. There is a great post here that covers this.
$query = "INSERT INTO table (title) VALUES (LCASE($title));

sql update statement where 2 condition apllies

This is quite a basic question, but have not found that much on-line to support.
I need to use a simple update statement in mysql (I know i should use mysqli but not yet ready for this update)
Given That I am working with a database made of a fixed number of items I want that the update apllies only when 2 conditions together are true.
my idea is something like
$sql ="update `members` set `description`='$description[$index]' WHERE id='1' AND fruit = 'banana'";
Is this the proper way of selecting the record to be updated?
Many thanks
Manu
That's how you'd do it more or less, here's a refined one:
$sql ="update `members` set `description`=? WHERE `id`='1' AND `fruit` = 'banana'";
1) See how I put the ? instead of the array? There are smart objects in PHP (read about "Prepared Statements") which allow you to put a parameter "spot" in the query and later have a value instead of it. This makes your query much more secure.
2) I added '`' around your columns. It's not mandatory, but it makes sure that your columns aren't mistaken for something else.
Yes that should work but it's safer to wrap array values in a string in brackets:
$sql ="UPDATE `members` SET `description`='{$description[$index]}' WHERE id='1' AND fruit = 'banana'";
Also make sure $description is somehow filtered or validated, before plugging it directly into the string.
NOTE: Best practice dictates that you use all caps for all SQL keywords, allowing easier differentiation between keywords and your values. Yours has half and half update and set lowercase; WHERE and AND caps, which is worse than going with all lowercase.
[edit] I agree with Daniel Saad that you should be using prepared statements here as well.

php mysql combine queries

If I have 2 mysql_query commands in a single php file, is their a way to combine them?
For example, I have:
$a=mysql_query(SELECT * FROM table1);
$b=mysql_query(SELECT id FROM table3);
but I want to combine them into a single mysql_query, would this be more efficient? would it be faster?
multiple queries are not supported in mysql_query as descripted on php manual, so you can't combine both query in php mysql_query way
Here is another good reference from php manual notes:
Executed with multiple queries at
once, the mysql_query function will
return a result only for the first
query. The other queries will be
executed as well, but you won't have a
result for them.
UNION should work (MySQL Manual)
SELECT id FROM table1 UNION SELECT id FROM table3;
Edit:
I see: You want all ("*") from table1. This is a little bit more difficult, but UNION may help also. However, you are really sure you want to do this? Is there any relationship beetween those two tables, or should this just be a kind of micro optimization?

SQL query to get data from a large list of strings

I have a large list of strings (1500 email addresses to be more specific) and I need to look up a piece of data in a very large DB table for each of the strings (e.g. the primary key, mydataitem). How can I do it efficiently?
For example, this is way too slow (amongst other problems):
$stringArray = ('foo','bar','baz',..., 'for 1000s of items');
foreach($stringArray as $mystring) {
$res = mysql_query("select mydataitem,blah FROM users WHERE blah = '$mystring'");
$info=mysql_fetch_assoc($res);
...
}
Things I want to avoid:
I don't want to loop over the list and do a SELECT for each item. i.e. 1500 queries (as in example above)
I don't want to read the whole table into an array in one query and do the lookup in code because it would take too much memory. The DB table has 100k+ rows.
I don't want to build a massive query with 1499 ORs because the query would be too big. (for example "select mydataitem FROM users WHERE blah = 'aaa' OR blah = 'bbb' OR ...")
Note: I'm using MySql v5.0.45
Update: Thanks everyone - for some reason I thought IN was just for Integer ID lists - now I know better.
mysql_query("select mydataitem,blah FROM users WHERE blah IN ('"
.implode("','",array_map('mysql_real_escape_string',$stringArray)."')';
Better yet, use mysqli or PDO which can use prepared statements:
$stmt = $PDO->prepare('select mydataitem,blah FROM users WHERE blah IN ('
.implode(',',array_fill(0,count($stringArray),'?')).')';
$stmt->execute($stringArray);
WHERE blah IN ('aaa','bbb',...)
But it's still not efficient.
If you explain why you need to retrieve so many records, we might perhaps be able to come up with a more efficient logic.
EDIT
Create a temporary table holding these values, and use a join to that temp table in your select query
I think what you want is
SELECT mydataitem FROM users WHERE blah IN ('foo', 'bar', 'baz', ...)
If you use a prepared statement, you can prepare it outside of your loop and then use it within your loop. That should run more quickly than a new mysql_query call each time.
I don't know what you mean by a query being "too big". Try it and see how slow it is.
Add a key on the email field if you don't already have one.
This doesn't sound like the kind of code that would be running often, so I would guess it's okay if it takes a second. If not, maybe you can explain the goal of this code and we can help you figure out a better way of accomplishing that goal.
Unless this needs to but lightning fast I would just use a MySQL in clause
turn the array into a string:
$emails = array("abc#def.com", "123#456.net", "me#google.com");
$list = "(\"". implode("\", \"", $balls) . "\")";
then just use it in your sql
$sql = "select mydataitem FROM users WHERE blah in {$list}";

Insert into MySQL tables with JOIN?

I have these tables: My final mysql db, could someone check if the tables are correctly made?
How can I make an Insertion of an ad here?
Is join used on insert also?
Thanks
Clarification: I need to insert values into multiple tables here, and don't know how to do it else than using multiple INSERT INTO statements.
So I wonder if there is anyway to make just ONE statement (one line) and use JOIN to INSERT?
As far as I'm aware of, you can't INSERT data into multiple tables Within one plain SQL statement.
There are many database abstraction frameworks out there which can do something like that (DOCTRINE TO THE RESCUE!!) but thats a whole other story.
SQL for it self it not capable of such things.
No it's not possible with an INSERT statement to insert into multiple tables. But you could use a stored procedure that would nicely batch the various inserts, and the application would have only one SQL command to emit.
I don't understand your first question about the ads. As for the second, JOIN will not be used on a standard table unless you are using it in an INSERT...SELECT statement, which you very likely aren't.

Categories