how can we insert multiple values in same query [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have many records in my table
I want to know that how can i use loop to insert all record in a single query.
e.g
DATABASE TABLE:
invoice_id___ Product_1____Price_1___Product_2____Price_2_____Product_3____Price_3
similarly there are 10 products i want to insert them against same invoice id(primary key.)
how can I do this please help. thanks

From the mySQL Manual
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
Here is the documentation link http://dev.mysql.com/doc/refman/5.6/en/insert.html

The problem is the database design. It's broken because it's not normalized. This makes it hard (to the point of being practically unfeasible) to write inserts, query, or establish DRI.
Instead the tables should look something like the following. Note that the InvoicedProducts table establishes a Many-to-Many relationship.
Invoices
--
invoiceNumber
invoiceDate
Products
--
productName
productPrice -- current product price
InvoicedProducts
--
Invoice (FK) -- the Invoice and Product FKs create a compound PK
Product (FK)
invoicedProductPrice -- product purchased at price (in case the price changes)
Then you simply insert the into the InvoicedProducts like ..
INSERT INTO InvoiceProducts (invoiceId, productId, invoidedProductPrice)
VALUES(.., .., ..)
.. the appropriate number of times (or, once per Invoice/Product pair). Use separate INSERT statements, but a single transaction.

try this
$con=mysqli_connect(hostname,username,password,databasename);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO table_name (a,b,c)
VALUES ('Peter', 'Griffin'),('absss','avdss','advas'),(7,8,9)");

Syntax is similar as below
-- INSERT INTO TABLE_NAME(COLUMN1, COLUMN2) VALUES(VALUE1,VALUE2),(VALUE3,VALUE4)....
But if you have multiple places to insert/update/delete, check the database design. You may need to normalize it.

Related

Perform multiple SQL queries with PHP [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a web form that should store data into two different tables in the database. In my includes, I have a php file that performs the necessary queries. The web form should store two pieces of information: The xp value being submitted from the form into the users table, and the article id into the completed_quests table. Individually, the queries work exactly as they should. However, if I try to perform both queries together, only the first query is performed and the second one is ignored. How do I make it so that both queries run once the user hits the submit button?
(edit) I have updated the code. To clarify, there is other code in my php file that defines the variables used in these queries. These are simply the two queries I was trying to run and I needed to know how to run both queries as it seemed to be ignoring the second one (the update). It is now working, however I am running into an issue of the INSERT query creating duplicate entries.
(edit) I have updated the code again. I used an ON DUPLICATE KEY UPDATE to avoid duplicate entries in the table. I made sure that the user id was the primary key in the table and it is now functioning perfectly.
mysql_select_db("questroot_joomla", $con);
mysql_query("INSERT INTO arp2i_completed_quests (user_id, content_id) Values ($userId, $currentArticle)
ON DUPLICATE KEY UPDATE content_id=$currentArticle");
mysql_query( "UPDATE arp2i_users"
. " SET userxp= $userXp"
. " WHERE id = $userId");
mysql_close($con);
$sql = "INSERT INTO `arp2i_completed_quests` (`user_id`, `content_id`) Values ('$_POST[current_user]', '$_POST[current_article]')";
/* it's not in $sql ->> */ "UPDATE `arp2i_users`
SET `userxp`= '$_POST[xpValue]'
WHERE `id` = '$_POST[current_user]'";
Try this:
$sql = "INSERT INTO `arp2i_completed_quests` (`user_id`, `content_id`) Values
('$_POST[current_user]', '$_POST[current_article]');
UPDATE `arp2i_users`
SET `userxp`= '$_POST[xpValue]'
WHERE `id` = '$_POST[current_user]'";
A lot of people here are just answering as though you are using PHP and not a framework that already is designed to handle all this stuff for you and do it safely, including checking for injection etc. You use a framework to make it simpler and avoid doing unsafe things. The combination of JForm, JDatabaseQuery and other parts of the API will handle updating multiple tables just fine, you can see that all over the core. How you would do it depends on what you are doing, such as is it more like updating the profile table when you are saving user data or is it more like updating the assets table or creating a new tag when saving content. What you should do though is stop fighting the API and start using it to your advantage.
You can simply add many mysqli_* queries as you want :
mysqli_query($link, "INSERT INTO `arp2i_completed_quests` (`user_id`, `content_id`) Values ('".$_POST['current_user']."', '".$_POST['current_article']."')";
mysqli_query($link, "UPDATE `arp2i_users` SET `userxp`= '".$_POST['xpValue']."' WHERE `id` = '".$_POST['current_user']."'");

How to search in all columns of a table [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I would like to know how I can search a substring in all columns of a table when I do not know the names of the columns? Is there a foreach-loop-functionallity I do not know?
If I understand you correctly then this may work, brute forces a search through all the results.
Here is a PDO-based example:
$stmt = $dbh->prepare("SELECT * FROM table");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
foreach($row as $column){
if(strpos($column, "find me") !== false)
echo $match."found in:".$column."<br />";;
}
}
I am also lazy. I am also a ColdFusion programmer, not php. However programming logic is the same no matter what the language. I would do this:
Step 1 - Run this query and output the results somewhere
select *
from mytable
where 1 = 2
The outputted results will include the field names. Copy and paste then into your source code as a comment. Delete the ones that you are not going to query. Convert the remaining ones to a list variable. In ColdFusion, that list would look something like this:
listOfFields = "field2,field3,field8,etc";
Fields 1,4,5,6, and 7 were intentionally excluded. We are then going to loop through the list in our query. In ColdFusion, this would be the syntax
<cfquery>
select somefields
from sometables
where 1 = 2
<cfloop list="#listOfFields#" index = "thisField">
or #thisField# = something
</cfloop>
This meets the laziness criteria because you only have to get the field names once. Whether it's better or worse than getting the columns from the system tables and looping through them depends. Doing it this way will make your own app run faster because you don't have to query the system tables every time. However, if a new column is added to your table, you'll have to modify your source code to include it in your search.
If you do decide to query the system tables, make sure you only select char and varchar fields.
Adapt the sample query given at https://stackoverflow.com/a/1054988/1967396
SELECT *
FROM Northwind.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'Customers'
to get the names of the columns. Then loop over those names to search the table one column at a time for the specific strings. This takes advantage of the efficiency of SQL search and prevents you making a copy of the entire database just to search it (slowly) with nested foreach loops (as in #Silver89's answer).

MySQL solution for multiple column totals [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I am retrieving multiple records from a table in MySQL. Is there a way that I can retrieve one row which totals each of the columns from this query? I was hoping that there might be an SQL solution, as I'll be repeating the process for many tables as it's being used for a dynamic report.
If there is no SQL solution, is there a way to easily add together all the nested arrays inside of an array? This would achieve the same result, but in PHP.
I can't seem to find any information on either approach.
You can do this using using aggregation. You don't give much guidance on what your query looks like, but something like:
select sum(col1) as sumcol1, sum(col2) as sumcol2, . . .
from t;
Without the group by clause, this returns one row, which is a summary of everything in t.
I am not sure what you exactly want to achieve by reading your question as you did not provide any codes or data. Try the following:
SELECT id, col_1, col_2, col_3, col_4, sum(t.Col)
FROM
(SELECT id, col_1, col_2, col_3, col_4,
SUM(col_1+col_2+col_3+col_4)
AS Col
FROM datas
WHERE id = '1'
GROUP BY id)t
You can see the fiddle here

tag system using PHP MySql [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to create tag system for my article. now I have this input with comma separated :
trance, house, electronica, dubstep, club
now I need to INSERT this tags To Tags Table Like This:
ID NAME ArticleId
1 trance 10
2 house 10
3 electronica 10
4 dubstep 10
5 garage 10
And How to Fetch, INSERT, DELETE , UPDATE This tags?!
For FETCH using Group Contact
SELECT GROUP_CONCAT(NAME) As tags FROM table_name WHERE ArticleId= 10;
will return like
trance, house, electronica, dubstep, club
for DELETE use simple delete query
DELETE FROM table_name WHERE name = 'trance'
Also for UPDATE query you can use like below
UPDATE table_name SET name = 'trance' WHERE ID = 1
EDIT
Use INSERT query
foreach($tag as $each_tag) {
INSERT INTO table_name (ID, NAME, ArticleId)
VALUES (1, '.$each_tag.', 10);
}
above is just skeleton map with your original code.
hope this will sure help you.

Why is this insertion query failing? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
mysql_query("
INSERT INTO `LMS`.`Presentation`
('Pre_Name' ,'Path' ,'PLec_ID' ,'pdatein' ,'pdesc','PSems_ID')
values
('$fname','$newname','$com',NOW(),'$filedesc','$semes')"
) or die("failed");
Dear All,
I have a table named presentation and I am going to enter value to it, it is mentionable that $com and $sems are comboboxs value, but the query show failed, anyone could help please,
thanks in advance
You're using quotes when you should be using backticks:
mysql_query("INSERT INTO `LMS`.`Presentation` (`Pre_Name`, `Path`, ...
Or simply don't use any special character. The backtick is only necessary if you do something silly like use a reserved word as a column name and I would hope people would choose their column names to be more readable.
In other words, date and in and select are silly names for columns, you should be using expiry_date, isInLocation and selectionStatus.
change or die("failed") into or die(mysql_error()) and you'll know why.
btw, consider changing from mysql functions to mysqli functions. And use parameterized queries. Otherwise you will be open to SQL injection.
mysql_query("
INSERT INTO table
(column1, column2, column3, column4 .... columnX)
VALUES(column1Data,column2Data, column3Data, column4Data ... columnXdata)
") or die(mysql_error());
> rove on this example and if there isnt a alias for a table then could not use a alias.
everything hiddends on details..

Categories