How can I insert Multiple array value in mysql table at same time?
I can handle single value Insertion.
Eg:
$product = json_decode($_POST['product']); // (1,2)
$sub_product = json_decode($_POST['sub_product']); // (3,4)
$plan = json_decode($_POST['plan']);// (5,6)
$months = json_decode($_POST['months']); // (7,8)
I want to insert value with same index in mysql
Something like:
+----+---------+-------------+------+--------+
| id | product | sub_product | plan | months |
+----+---------+-------------+------+--------+
| 1 | 1 | 3 | 5 | 7 |
+----+---------+-------------+------+--------+
| 2 | 2 | 4 | 6 | 8 |
+----+---------+-------------+------+--------+
I've tried Insertion for single column and it works perfectly.
for ($i = 0; $i < count($product); $i++) {
$product = mysql_real_escape_string($product[$i]);
mysql_query("INSERT INTO i_product(product) VALUES('$product')");
}
you can execute multiple INSERT operations in the following format,
INSERT INTO tbl_name
(a,b,c)
VALUES
(d,e,f),
(g,h,i),
(j,k,l);
Here's the reference:
INSERT Syntax
Since you're getting the data as an array, your INSERT operation should be like this:
// your code
mysql_query("INSERT INTO i_product(product, sub_product, plan, months)
VALUES
('" . mysql_real_escape_string($product[0]) . "', '" .
mysql_real_escape_string($sub_product[0]) . "', '" .
mysql_real_escape_string($plan[0]) . "', '" .
mysql_real_escape_string($months[0]) . "'),
('" . mysql_real_escape_string($product[1]) . "', '" .
mysql_real_escape_string($sub_product[1]) . "', '" .
mysql_real_escape_string($plan[1]) . "', '" .
mysql_real_escape_string($months[1]) . "')");
Sidenote: Please don't use mysql_ database extensions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7. Use mysqli or PDO instead.
Related
Table 1 (Which needs to be updated)
+-----------------+
|name |qty |
+-----------------+
|area | 1 |
|length | 2 |
|breadth | 3 |
|width | 4 |
+-----------------+
Table Which needs to be fetched for what values and rows have to be update
+-------------------------------------+
|name | upd_qty | Cart_id | cid |
+-------------------------------------+
|area | 6 | 12 | 1 |
|length | 8 | 20 | 2 |
|breadth | 11 | 34 | 3 |
+-------------------------------------+
How can i do this using php. Help me with this please.
this is the code i have used for my original work. Table 1 & Table 2 have name in common and conditions are
1 . UPDATE should done for the rows which are fetched from table to with where condition.
2. Table 2 upd_qty will be updated in table 1 qty while fetching data from table 2 where condition.
$con=mysqli_connect("localhost","root","","medical");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
error_reporting(E_ALL ^ E_NOTICE);
$query = "SELECT * FROM cart WHERE cid='$id' AND 'cart'='$cart_id'";
$result = $con->query($query);
while($row = $result->fetch_assoc()) {
$mediname = $row['name'];
$mediqty = $row['upd_qty'];
for($i=0;$i<$count;$i++){
$sql="UPDATE stock SET qty='$mediqty' WHERE name='$mediname' AND
'cart'='$cart_id'";
if (!mysqli_query($con,$sql))
{
die('Error: Failed' . mysqli_error($con));
}
I don't think you need this line:
for($i=0;$i<$count;$i++){
There's already a "while fetch" loop.
Also, don't use single quotes around identifiers, use backticks if the identifier needs to be escaped.
With this:
... AND 'cart' = ...
'cart' will be evaluated a string literal, not a column reference.
With this
... AND `cart` = ...
cart is an identifier, a reference to a column.
Also, if we can't use prepared statements with bind placeholders, at a minimum, we use mysqli_real_escape_string to mitigate SQL Injection vulnerabilities
Also, there's a confusing mix of procedural style and objected oriented style calls...
procedural style
mysqli_query($con,$sql)
mysqli_error($con)
object oriented style
$con->query($query)
$result->fetch_assoc()
I recommend you choose one style or the other, and stick to that pattern.
$query = "SELECT * FROM cart WHERE `cid` = '"
. $con->real_escape_string($id)
. "' AND `cart` = '"
. $con->real_escape_string($cart_id)
. "'";
$result = $con->query($query);
if( !$result ) {
die('Error: ' . $con->error());
}
while( $row = $result->fetch_assoc() ) {
$mediname = $row['name'];
$mediqty = $row['upd_qty'];
$sql="UPDATE stock SET `qty` = '"
. $con->real_escape_string($mediqty)
. "' WHERE `name` = '"
. $con->real_escape_string($mediname)
. "' AND `cart` = '"
. $con->real_escape_string($cart_id)
."'";
if(!$con->query($sql) ) {
die('Error: Failed' . $con->error());
}
}
EDIT
If there's not a specific reason for the loop, if the goal is just to perform the UPDATE operation and there is not other logic or conditions, we can do the UPDATE in one statement, without a need for multiple query executions:
UPDATE cart c
JOIN stock s
ON s.cart = c.cart
AND s.name = c.name
SET s.qty = c.upd_qty
WHERE c.cid = ?
AND c.cart = ?
Personally, I would just do the one UPDATE statement using a prepared statement
// connect to mysql
$con = new mysqli(...)
if( $con->connect_error ) {
die( 'Connect error: ' . $con->connect_error );
}
// update statement
$sql = '
UPDATE cart c
JOIN stock s
ON s.cart = c.cart
AND s.name = c.name
SET s.qty = c.upd_qty
WHERE c.cid = ?
AND c.cart = ? ';
$sth = $con->prepare($sql);
if(!$sth) {
die( 'Prepare error: ' . $con->error() );
}
$sth->bind_param('ii',$id,$cart_id);
if(!$sth->execute()) {
die( 'Execute error: ' . $con->error() );
}
Code worked for me for what i want exactly is :
$con=mysqli_connect("localhost","root","","medical");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
error_reporting(E_ALL ^ E_NOTICE);
$query = "SELECT * FROM cart WHERE cid='$id' AND cart='$cart_id'";
$result = $con->query($query);
while($row1 = $result->fetch_assoc())
foreach ($result as $row1){
$sql="UPDATE stock SET qty='$row1[upd_qty]' WHERE name='$row1[name]'";
if (!mysqli_query($con,$sql))
{
die('Error: Failed' . mysqli_error($con));
}
}
I have two tables in a database. In reports I am storing info for reports and in report_roles I am assigning which user can access the report.
reports
+--+-----------+---------------+
|id|report_name|report_filename|
+--+-----------+---------------+
|13|Report 1 |reportname1 |
|14|Report 2 |reportname2 |
|15|Report 3 |reportname3 |
+--+-----------+---------------+
report_roles
+---------+-------+
|report_id|user_id|
+---------+-------+
|14 |1 |
|13 |1 |
|14 |2 |
|13 |2 |
+---------+-------+
I want to display all the reports from table reports with checkboxes and check only those which are added in the report_roles associated with the user id. This is the code I am running:
$id = $_POST['user_id'];
$query = "SELECT * FROM reports LEFT JOIN report_roles ON report_roles.report_id = reports.id";
$sql = mysqli_query($mysqli, $query);
if (!$sql) {
printf("Error: %s\n", mysqli_error($mysqli));
exit();
}
while($row = mysqli_fetch_array($sql, MYSQLI_ASSOC) ) {
if ($row['user_id'] == $id) {
echo "<input type='checkbox' name='" . ($row['id']) . "'" . "id='" . ($row['id']) . "'" . "value='yes'" . ($row['user_id'] == $id ? 'checked' : '') .">";
echo $row['report_name'];
} else {
echo "<input type='checkbox' name='" . ($row['id']) . "'" . "id='" . ($row['id']) . "'" . "value='yes'" . ">";
echo $row['report_name'];
}
}
If $id = 1 I am receiving this:
|checked| Report2 |checked| Report 1 |unchecked| Report2 |unchecked| Report 1 |unchecked| Report3
Which is completely right based on the code I wrote. I cannot figure out how to display all the reports without duplicates from reports table and check only those which are available in report_roles, something like this:
|checked| Report2 |checked| Report 1 |unchecked| Report3
I am sure I have to change my query with the join. Tried to do accomplish this task with two separate queries without joins but with no luck. Hope someone can help.
Actually I was just missing a statement in my query and thanks to Bernd Buffed I realized that I have to add one AND at the end of the query and it should look like this:
$query = "SELECT * FROM reports LEFT JOIN report_roles ON report_roles.report_id = reports.id AND user_id = $id";
Till now I was adding WHERE user_id = $id and was receiving only those reports which exists in report_roles. With the AND I am receiving all reports from reports table and my script can check only those which are in report_roles based on a simple php check.
Having a query that draws multiple lines from a DB, each with an ID, a path and another ID. Is it possible to pass the path by the filesize() function and mark if two or more lines have the same file size?
Here's my code:
$q2 = "SELECT idMultimedia, pathURLMult, Type_idType FROM Multimedia";
$e2 = mysqli_query( $conn, $q2 );
while( $r2 = mysqli_fetch_array($e2) ){
list($width, $height) = getimagesize($r2["pathURLMult"]);
$size = filesize($r2["pathURLMult"]);
echo $r2["idMultimedia"] . " | " . $r2["pathURLMult"] . " | " . $width. " | " . $height. " | " . $size . "<br>";
}
Example of a possible Database output:
1 | randomguy1.jpg | 2
2 | A-GUY.jpg | 3
3 | lol.jpg | 2
4 | randomguy2.jpg | 1
randomguy1.jpg & randomguy2.jpg have the same file size... I need to show that for both pics! How can I do this?
Any help? Thanks in advance!
I bought an iPhone wallpaper gallery PHP script a year ago, and it has been running great. I've been slowly learning PHP and MySQL by doing little tweaks here and there.
To view a category, the URL is www.example.com/index.php?catid=27, and I want to change it to www.example.com/index.php?catid=apple for SEO reasons. I know I can futher tidy up the URL with .htaccess but I just want to get this word slug to begin with.
This is the code (inside index.php) that I think generates the category pages:
if (($_REQUEST['catid']) && ($_REQUEST['catid'] > 1)) {
$catid = $_REQUEST['catid'];
if (is_numeric($catid)) {
$tempitemarray = $myitems->getItemsByCategory($catid);
$catnav = "&catid=" . $catid;
$tempcat = new Category();
$tempcat->getCategory($catid);
$maintitle = "<h1>" . $tempcat->getCategoryName() . " " . $itemplural . "</h1>";
}
That code calls another PHP page called itemList.php, and inside that page I found this code:
public function getItemsByCategory($catid) {
$this->retrieveSQL = "select * from items i, item_category_lookup l where livedate < '" . $this->currentdate . "' and i.active = " . $this->showApproved . " and l.categoryid = $catid and i.id = l.itemid order by i.livedate desc limit " . $this->startRow . "," . $this->numRows;
$this->countSQL = "select * from items i, item_category_lookup l where livedate < '" . $this->currentdate . "' and i.active = " . $this->showApproved . " and l.categoryid = $catid and i.id = l.itemid";
$this->retrieveItems();
return $this->items;
}
This is the 'items' table:
id | itemname | itemdec | itemkeywords | createdate | viewcount | active | rating | livedate | sourcedesc | sourceurl
-----------------------------------
64 | Apple Logo
This is the 'item_category_lookup' table:
categoryid | itemid
-------------------------
27 | 64
This is the 'category' table below. It's not called in the query above but does have the actual category names. How would I implement it?
id | categoryid
------------------
27 | Apple
You might change the SQL of $this->retrieveSQL = ... into
if (!is_number($catid)) {
$this->retrieveSQL = "select * from items i, item_category_lookup l, category j where livedate < '" . $this->currentdate . "' and i.active = " . $this->showApproved . " and i.id = l.itemid and j.id = l.categroyid and j.categoryid = "$catid" order by i.livedate desc limit " . $this->startRow . "," . $this->numRows;
}
Try this:
URL example: www.example.com/index.php?catid=27-apple
if ( isset( $_REQUEST['catid'] ) ) {
$catSEO = explode( '-', $_REQUEST['catid'] );
}
$catid = is_numeric( $catSEO[0] ) ? $catSEO:0;
I am fetching data from some tables & storing it in a variable like below-:
$result = mysql_query("SELECT * FROM sample where column=mysql_insert_id()");
while($row=mysql_fetch_array($result))
{
$str = "'". $row["name"] . "',". "'" . $row[quantity] . "'," . "'" . $row["id"];
}
So in my variable $str, suppose I have following values-:
shirt,10,1,pant,50,2....i.e. it will store values in a comma separated format.
Now I want to insert these values in another table say test-:
$qry = "INSERT INTO test(name,quantity,id)values(".$str.");
Now I want to store values in test table in two rows like-:
shirt 10 1
pant 50 2
So how to do the same for Mysql & Oracle tables?
Plz help
See my below query-:
$query2 = "SELECT sfoi.name, sfoi.sku, sfoi.qty_ordered, sfoi.price, sfoi.row_total, sfo.base_subtotal, sfo.base_shipping_amount, sfo.base_grand_total,
(select mso.order_primary from mysql_sales_order mso where mso.increment_id =sfo.increment_id)
FROM sales_flat_order sfo
JOIN sales_flat_order_item sfoi
ON sfoi.order_id = sfo.entity_id
WHERE sfo.increment_id = ". $order_id ;
$result_query2 = mysql_query($query2);
So for one order id i.e. for one order may contain more than 1 products i.e. many name,sku,quantity ordered etc. So at the time of mysql_fetch_array(), I want all product data in a single variable...my code for fetching is like this-:
while($row = mysql_fetch_array($result_query2))
{
$string = "'". $row["name"] . "',". "'" . $row["sku"] . "'," . "'" . $row["qty_ordered"] . "',". "'" . $row["price"] . "'," . "'" . $row["row_total"] . "'," . "'" . $row["base_subtotal"]. "'," . "'" . $row["base_shipping_amount"] . "'," . "'" . $row["base_grand_total"] ."'," . $row["prod_foreign"];
$query3 = "INSERT into mysql_sales_product(name, sku, qty_ordered, price, row_total, base_subtotal,base_shipping_amount,base_grand_total,prod_foreign) VALUES(".$string.")";
}
$result_query_product_outbound = mysql_query($query3);
Here I want to store result of mysql_ fetch_array in variable in such a way that if there are multiple rows I can still able to pass those rows using variable$string. e.g-:
name sku qty_ordered price row_total subtotal shipping_amnt grand_total prod_foreign
nokia nk 2 500 1000 1000 300 1300 11
sansung sam 3 400 1200 1200 500 1700 30
sony sny 4 200 800 800 200 1000 45
For Oracle, like below :
INSERT ALL
INTO your_table(column1,column2,column3) VALUES('values1.1', 'values1.2', 'values1.3')
INTO your_table(column1,column2,column3) VALUES('values2.1', 'values2.2', 'values2.3')
SELECT * FROM dual;
Easier than doing a PHP loop, you can do this directly in MySQL. I'm not sure this is an option for you, since you didn't told us what the matter with Oracle...
Anyway, here is what I would do in your case:
INSERT INTO test(name,quantity,id)
SELECT name, quantity, id FROM sample where id=<your id here>
Or, if you have multiple ids,
INSERT INTO test(name,quantity,id)
SELECT name, quantity, id FROM sample where id in (<your ids here as comma separated list>)