I want to insert similar strings in a page in to the database at once! for example, I want to insert each line in to a table row:
$flag = 'AD.png'; $title = 'Andorra';
$flag = 'AE.png'; $title = 'United Arab Emirates';
$flag = 'AF.png'; $title = 'Afghanistan';
$flag = 'AG.png'; $title = 'Antigua and Barbuda';
$flag = 'AI.png'; $title = 'Anguilla';
$flag = 'AL.png'; $title = 'Albania';
$flag = 'AM.png'; $title = 'Armenia';
$flag = 'AN.png'; $title = 'Netherlands Antilles';
My database rows are:
`flag_Id` int(11) NOT NULL AUTO_INCREMENT,
`flag_Title` varchar(250) NOT NULL,
`flag_ImageId` varchar(250) NOT NULL,
PRIMARY KEY (`flag_Id`)
How should I do that?!
You can insert multiple records in one query:
INSERT INTO tablename (flag_ImageId, flag_Title) VALUES
('AD.png', 'Andorra'),
('AI.png', 'Anguilla),
...
('US.png', 'USA');
this foreach item:
insert into tablename flag_Title, flag_ImageId values ('AD.png', 'Andorra');
If you want to do it in 1 transaction add START TRANSACTION; and COMMIT; like:
START TRANSACTION;
insert into tablename flag_Title, flag_ImageId values ('AD.png', 'Andorra');
insert into tablename flag_Title, flag_ImageId values ('AD.png', 'Andorra');
COMMIT;
Related
This question already has answers here:
What is the best way to insert multiple rows in PHP PDO MYSQL?
(4 answers)
Closed last year.
I would like through pdo insert multiple (bulk) rows with same value, only diffent is the user_id
I'm passing a array with userIds but i have no idea how to bind them.
<?php
require_once("db.php");
$usersId = $jsonData["usersId"];
$text = $jsonData["text"];
// Try to fetch the user from the database
$query = "INSERT INTO posts (user_id, text) VALUES (:usersId, :text)";
$stmt = $db->prepare($query);
// Bind value
$stmt->bindValue(":userId", $userId);
$stmt->bindValue(":text", $text, PDO::PARAM_STR);
// Execute
$result = $stmt->execute();
?>
My Tables:
CREATE TABLE users(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255)
);
INSERT INTO users (name)
VALUES ("Gregor"),
("Liza"),
("Matt"),
("Bob");
CREATE TABLE posts(
id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT,
text VARCHAR(255)
);
You need a loop:
require_once("db.php");
$text = $jsonData["text"];
// Try to fetch the user from the database
$query = "INSERT INTO posts (user_id, text) VALUES (:usersId, :text)";
$stmt = $db->prepare($query);
// Bind value
$stmt->bindParam(":userId", $userId);
$stmt->bindValue(":text", $text, PDO::PARAM_STR);
// Execute
foreach ($jsonData["usersId"] as $userId) {
$result = $stmt->execute();
}
Use bindParam() so it binds to a reference to the variable. That allows you to reassign the variable each time through the loop without re-binding.
the problem that its a huge amount the query would be like
DELETE FROM `members` WHERE `membership` = 'C' AND (`id` != '1' AND `id` !='2' AND ...... thousands of ids );
how I can do that ?
I did also WHERE id NOT IN ("1","2"); but also did not work
can I use loop or something like that
the IDs that I want to keep and do not delete comes from another table contains a field holds the user ID that I don't want to delete I used PHP script to help me to generate the SQL query
like
<?php
require_once("inc.php");
$realty_uids = $db->query("SELECT `uid` from `realty2` ORDER BY `uid`");
$r = $db->fetch_assoc($realty_uids);
while($r = $db->fetch_assoc($realty_uids)){
$array[] = $r['uid'];
}
$input = array_unique($array);
echo "DELETE from `members` WHERE `membership` = 'C' ";
foreach($input as $key => $value){
echo " AND `id` != '".$value."' <br>";
}
echo ";";
DELETE FROM `members` WHERE `membership` = 'C' AND NOT EXISTS (SELECT at.uid FROM `realty2` at WHERE at.uid = `members`.id);
This way worked good thanks for every one tried :)
i am trying to add a default value in Xampp.
i set it as in the picture, but when i add 1 more product, if i left i in blank, it will be blank, i mean it will not have a value as default.
Do you have any idea.
my code is:
if (isset($_POST["add"])) {
//lấy thông tin từ các form bằng phương thức POST
$tennsx = $_POST["tennsx"];
$diachi = $_POST["diachi"];
$sdt = $_POST["sdt"];
$mieuta = $_POST["mieuta"];
if ($tennsx == "" || $diachi == "" || $sdt == "" ) {
echo '<h4 align=center style="color: red;">Vui lòng nhập đầy đủ thông tin</h4>';
}else{
//thực hiện việc lưu trữ dữ liệu vào db
$sql = "INSERT INTO nhasx(
tennsx,
diachi,
sdt,
mieuta
) VALUES (
'$tennsx',
'$diachi',
'$sdt',
'$mieuta'
)";
// thực thi câu $sql với biến conn lấy từ file connection.php
mysqli_query($conn,$sql);
header('Location:manu_management.php');
}
}
This is because the Mysql assume you want to insert the empty values instead of default values. You need to omit the field with default values if no value at all to insert, see following code :
// simply check if variable $mieuta is empty
// goes here
if ( $mieuta === "" ) {
$sql = "INSERT INTO nhasx(
tennsx,
diachi,
sdt
) VALUES (
'$tennsx',
'$diachi',
'$sdt'
)";
}
else {
$sql = "INSERT INTO nhasx(
tennsx,
diachi,
sdt,
mieuta
) VALUES (
'$tennsx',
'$diachi',
'$sdt',
'$mieuta'
)";
}
Default values should work if you omit the field name and value from query string. This kind of method come in handy when we want to insert default date created column.
For better approach use this :
$sql = "INSERT INTO nhasx(
tennsx,
diachi,
sdt,
mieuta
) VALUES (
'$tennsx',
'$diachi',
'$sdt',
'".($mieuta ==='') ? 'MY DEFAULT VALUE' : $mieuta."'
)";
In your code you have set mieuta = $mieuta while inserting a new record so as per priority it would insert value from $mieuta. please remove and try again as of like below code.
if (isset($_POST["add"])) {
//lấy thông tin từ các form bằng phương thức POST
$tennsx = $_POST["tennsx"];
$diachi = $_POST["diachi"];
$sdt = $_POST["sdt"];
$mieuta = $_POST["mieuta"];
if ($tennsx == "" || $diachi == "" || $sdt == "" ) {
echo '<h4 align=center style="color: red;">Vui lòng nhập đầy đủ thông tin</h4>';
}else{
//thực hiện việc lưu trữ dữ liệu vào db
$sql = "INSERT INTO nhasx(
tennsx,
diachi,
sdt
) VALUES (
'$tennsx',
'$diachi',
'$sdt'
)";
// thực thi câu $sql với biến conn lấy từ file connection.php
mysqli_query($conn,$sql);
header('Location:manu_management.php');
}
}
CREATE TABLE IF NOT EXISTS `xxxx` ( `username` varchar(15) NOT NULL default 'abc')
try MySQL like this.
Example:
CREATE TABLE IF NOT EXISTS `test` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(10) NOT NULL DEFAULT 'abc', `test` varchar(12) NOT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;INSERT INTO `dbName`.`test` (`id` ,`test`)VALUES (NULL , '1');
I am parsing currency rates from a rss.xml feed that all works great. I am now trying to insert that data into a database called rates with a table called tblRates. I keep getting this error and do not know why. Here is the function in the model I am using to try to batch insert into the database.
function addIQDRates($Data){
if($this->db->insert_batch('tblRates', $Data, 'Currency'))
{
return $this->db->affected_rows();
}else{
return FALSE;
}
}
Also here is the foreach statement I am using in my controller to sort the data from the xml file and to insert it into the database.
$Data = array();
$Data = array();
$Count = 0;
foreach ($xml->channel->item as $currencyInfo) {
$Data[$Count]['Currency'] = trim(str_replace("/USD", "", $currencyInfo->title)); // UNIQUE
$Data[$Count]['PubDate'] = date('Y-m-d H:i:s', strtotime(trim($currencyInfo->pubDate)));
$Data['CXRate'] = trim(preg_replace("/[^0-9,.]/", "", str_replace("1 United States Dollar = ", "", $currencyInfo->description)));
$Data[$Count]['DateCreated'] = date('Y-m-d H:i:s');
$Count++;
}
$TotalRows = $this->mycron_model->addIQDRates($Data);
Also here is my Create Table statement
CREATE TABLE IF NOT EXISTS `tblRates` (
`RateID` int(11) NOT NULL AUTO_INCREMENT,
`Currency` varchar(50) NOT NULL,
`PubDate` datetime NOT NULL,
`CXRate` int(11) NOT NULL,
`DateCreated` datetime NOT NULL,
PRIMARY KEY (`RateID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
all help greatly appreciated.
I am not sure, you might have written $Data['CXRate'] instead of $Data[$Count]['CXRate'].
So the loop should like like below:
foreach ($xml->channel->item as $currencyInfo) {
$Data[$Count]['Currency'] = trim(str_replace("/USD", "", $currencyInfo->title)); // UNIQUE
$Data[$Count]['PubDate'] = date('Y-m-d H:i:s', strtotime(trim($currencyInfo->pubDate)));
$Data[$Count]['CXRate'] = trim(preg_replace("/[^0-9,.]/", "", str_replace("1 United States Dollar = ", "", $currencyInfo->description)));
$Data[$Count]['DateCreated'] = date('Y-m-d H:i:s');
$Count++;
}
session_start();
if(!$_SESSION['user_id'])
{
$_SESSION['user_id'] = rand(1, 1000000);
include 'database_connect.php';
mysql_query('INSERT INTO product_views (user_session_id)
VALUES
('.$_SESSION['user_id'].')');
}
$productid = $_GET['name'];
$query = 'SELECT * FROM product_views WHERE user_session_id = '.$_SESSION['user_id'].'';
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
mysql_query('UPDATE product_views SET modelNumber="'.$productid.'" WHERE user_session_id="'.$_SESSION['user_id'].'"');
}
My field modelNumber is set to null, and I am performing an Update via the last query.
Do you think that since the default value is null, it is therefore not allowing an insertion?
My table structure:
CREATE TABLE `product_views` (
`id` int(10) DEFAULT NULL,
`user_session_id` int(11) DEFAULT NULL,
`product_id` varchar(100) DEFAULT NULL,
`view_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`modelNumber` varchar(...
I'm confused:
$query = 'SELECT * FROM product_views WHERE user_session_id = '.$_SESSION['user_id'].'';
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
mysql_query('UPDATE product_views SET modelNumber="'.$productid.'" WHERE user_session_id="'.$_SESSION['user_id'].'"');
}
Why are you looping through this result set if you're not even using $row?
Edit: I think this is what you're really trying to do:
session_start();
if(!$_SESSION['user_id'])
{
// Get the user ID
$_SESSION['user_id'] = rand(1, 1000000);
require_once('database_connect.php');
// Get the model number and escape it to prevent SQL injection
$model_number = mysql_real_escape_string($_GET['name']);
// Insert a row that associates the user_id with the model number
mysql_query("INSERT INTO product_views (user_session_id,modelNumber) VALUES('{$_SESSION['user_id']}', '$model_number')");
}