I have a table of checkboxes and values, if a user selects a checkbox they select the value of the id in an array called checkedHW for simplicity sake this is what code looks like:
$ids = implode(',',arrayofids);
$sql = "insert into table(id, type) values($ids,type);
$db->query($sql);
echo query for testing:
"insert into table('id1,id2','type')
I figured that if I loop through this query I could hypothetically do this:
"insert into table('id1','type');"
"insert into table('id2','type');"
but I'm not exactly quite sure how to do, any help would be wonderful :)
I actually solved it using:
for($i=0;$i<count(arrayofids); $i++){
$sql = "insert into table(id,type) values(array[$i], 'type'";
$db->query($sql);}
I hope that helps someone and thank you guys for the help!
You could do something like this:
$base = 'INSERT INTO table (id, type) VALUES (';
$array = array(1, 2, 3, 4);
$values = implode(", 'type'), (", $array);
$query = $base . $values . ", 'type')";
$db->query($query);
This is what would be getting submitted:
INSERT INTO table (id, type) VALUES (1, 'type'), (2, 'type'), (3, 'type'), (4, 'type')
Both query are completely different
insert into table('id1,id2','type') will insert single row
id1,id2 | type
whereas
insert into table('id1','type');"
insert into table('id2','type');"
will insert two rows
id1 | type
id2 | type
so if your id column is int type then you cant run first query
If you have a series of checkboxes, and wanting to insert the values into your table, you could loop through them like this:
<?php
$values = array();
foreach ($_POST['field_name'] as $i => $value) {
$values[] = sprintf('(%d)', $value);
}
$values = implode(',', $values);
$sql = "INSERT INTO `table_name` (`column_name`) VALUES $values";
This will give you a SQL query similar to:
INSERT INTO `table_name` (`column_name`) VALUES (1),(2),(3),(4)
Hope this help.
Related
I have two mysql queries to insert the data into two different tables. the result of the queries are as follows:
INSERT INTO table1 (ans1,ans2,ans3,ans4,ans5) VALUES (0,0,0,0,0),(1,1,1,0,0),(0,0,0,0,0)
INSERT INTO table2 (uid,cid,sid) VALUES (1,abc,123),(2,def,456),(3,ghi,789)
How can I concatenate these two results so that the output would look like
INSERT INTO table3 (uid,cid,sid,ans1,ans2,ans3,ans4,ans5)
VALUES
(1,abc,123,0,0,0,0,0),
(2,def,456,1,1,1,0,0),
(3,ghi,789,0,0,0,0,0)
I think something as this:
<?php
//First we need connect to database
$server = "localhost";
$Userdb = "admin";
$Passworddb = "password";
$database = "db";
$conn = mysqli_connect($server, $Userdb, $Passworddb, $database);
mysqli_set_charset($conn, "utf8");
//Getting values - for this example it is static
//For concate we need values as array => explode()
$colums1 = "ans1,ans2,ans3,ans4,ans5";
$values1 = explode("),(", substr("(0,0,0,0,0),(1,1,1,0,0),(0,0,0,0,0)", 1, -1));
$colums2 = "uid,cid,sid";
$values2 = explode("),(", substr("(1,abc,123),(2,def,456),(3,ghi,789)", 1, -1));
//Query for table1
$command = "INSERT INTO table1 (".$colums1.") VALUES ".$values1;
mysqli_query($conn, $command) or die(mysqli_error($conn));
//Query for table2
$command = "INSERT INTO table2 (".$colums2.") VALUES ".$values2;
mysqli_query($conn, $command) or die(mysqli_error($conn));
//We need to concate values so =>
//=> For every index of $values1 add at same index into $values3 concated $values1 and $values2
$values3 = array();
for ($x = 0; $x <= count($values1); $x++) {
$values3[$x] = "(".$values2[x].",".$values1[$x].")";
}
//Query for table3
$command = "INSERT INTO table3 (".$colums2.",".$colums1.") VALUES (".implode("),(", $values3).")";
mysqli_query($conn, $command) or die(mysqli_error($conn));
?>
I think that this SHOULD works (one never knows :) )
I am inserting multiple rows in a table with single insert query using the following format:
INSERT INTO $table (field1,field2) VALUES (value1,value2),(values3,values4);
The number of rows varies. Is there a way to use Perl's prepare statement for this kind of queries ?
For example, if I am inserting only one row I can do like the below:
$query = "INSERT INTO $table (field1,field2) VALUES (?,?)";
$sth = $dbh->prepare($query);
$sth->execute('value1','value2');
However, I want to do something like the below:
$values = '(value1,value2),(values3,values4),(values5,values6)';
$query = "INSERT INTO $table (field1,field2) VALUES ?";
$sth = $dbh->prepare($query);
$sth->execute($values);
Is this possible? or any other ways to achieve this ?
You can build up a query that can do what you want. Assuming that your records are in an array like this.
my #records = ( ['value1', 'value2'], ...) ;
Then you can create a query dynamically and execute it.
my $values = join ", ", ("( ?, ? )") x #records;
my $query = "INSERT INTO $table (field1,field2) VALUES $values";
my $sth = $dbh->prepare($query);
$sth->execute(map { #$_ } #$records);
Also in your example you are using string interpolation on the table name. Be careful with that as it can lead to database injections.
Put each record in its own array, then make an array of those:
my #records = ( [ 'value1', 'value2' ], [ 'value3', 'value4' ], [ 'value5', 'value6' ] );
Then prepare your INSERT statement:
my $query = "INSERT INTO $table (field1,field2) VALUES (?,?)";
my $sth = $dbh->prepare($query);
Then loop over your records and execute your statement handle for each one:
foreach my $rec ( #records ) {
$sth->execute( #$rec );
}
I want to insert the data I have in my grid in table 'quote' in my database, when I put this code in the trigger on ProcessMaker.
when I tried with a normal form it worked but if the grid it works I think it's a problem of syntax or foreach gridsizerows n is not, can someone please help me:
here is the code
$i=0 foreach ($i < $gridsizerows) {
$i = i +1;
$id = #mygrid [$i]['id'];
$quantity = #mygrid[$i]['quantity'];
$pu = #mygrid[$i]['possible'];
$pt = #mygrid[$i]['pt'];
$to = #mygrid [$i]['designation'];
$sql = "INSERT INTO quotes (id, designation, quantity, pu, pt) VALUES ($id, $from, $pu, $pt, $amount)";
$tmp_db = executeQuery($sql, '90911865253a802b030e577077431812');
}
Your code looks good, 2 possible changes you might want to do are as given below..
Instead of this:
$sql = "INSERT INTO quotes (id, designation, quantity, pu, pt) VALUES ($id, $from, $pu, $pt, $amount)";
Use this:
$sql = "INSERT INTO quotes (id, designation, quantity, pu, pt) VALUES ('$id', '$from', '$pu', '$pt', '$amount')";
and Instead of this:
$tmp_db = executeQuery($sql, '90911865253a802b030e577077431812');
Use this:
$dbConn = '90911865253a802b030e577077431812';
$tmp_db = executeQuery($sql, $dbConn);
I'm trying to do something that may be too complicated for MySQL
If a row exists i'd like it to update a counter and if not insert the row...I did a search and found this...
$query = "insert into TABLE
(`id`, `item`, `count`, `option1`, `option2`)
values
('$cartName', '$sku', 1, '$option1', '$option2')
on duplicate key
update count = count + 1";
but I don't have a key in the table so the "on duplicate key" won't work, the query needs multiple ANDs to check the row based on the id, item, and 2 option values.
an added thing is to have mySQL return a count of all count values based on the item
This is what I have currently (modified from search :), does anyone know how to reduce this into a single query?
option1 and option2 are variable and could be null so that's why the 2 if statements and is called from AJAX so the $message is used to update the javascript client side.
$query = "update TABLENAME set count=count+1 where item='$item'";
if($option1) $query .= " AND option1='$option1'";
if($option2) $query .= " AND option2='$option2'";
$result = mysql_query($query) or die("Error:".mysql_error() );
if (mysql_affected_rows()==0) {
$query = "insert into $table11 (`id`, `item`, `count`, `option1`, `option2`) values ('$id', '$item', 1, '$option1', '$option2');";
$result = mysql_query($query) or die("Error:".mysql_error() );
}
//total count for all items with specific id
$query = "SELECT SUM(count) FROM TABLENAME WHERE id='$cartName'";
$result = mysql_fetch_row(mysql_query($query)) or die("Error:".mysql_error() );
$message = $result[0];
I know I am doing this completely wrong, but current I have:
$genre0 = addslashes(strip_tags($movieInfo[genres][0][name]));
$genreid0 = addslashes(strip_tags($movieInfo[genres][0][id]));
...
$genre4 = addslashes(strip_tags($movieInfo[genres][4][name]));
$genreid4 = addslashes(strip_tags($movieInfo[genres][4][id]));
Then
mysql_query($query = "INSERT INTO tblMovies (movie_id, genre_id, genre_name) VALUES ($movie_id , $genreid0, $genre0");
...
mysql_query($query = "INSERT INTO tblMovies (movie_id, genre_id, genre_name) VALUES ($movie_id , $genreid4, $genre4");
I know this is extremely repetitive, but it is the only way I can figure out that works. I have tried a ton of for each statements to no avail. I have tried following this one insert multiple rows via a php array into mysql and a few others, but cannot seem to figure it out.
This is embedded in a SELECT/WHILE statement that runs through a list of movies...
Any tips or suggestions would be greatly appreciated!
Thanks!
You can use prepared statements for handy execution of your query:
$stmt = $dbh->prepare("INSERT INTO tblMovies (movie_id, genre_id, genre_name)
VALUES (:movie_id , :genreid, :genre")");
$stmt->bindParam(':movie_id ', $movie_id);
$stmt->bindParam(':genreid', $genreid);
$stmt->bindParam(':genre', $genre);
for($i=0; $i < count($movieInfo['genres']); $i++){
$movie_id = i;
$genreid = addslashes(strip_tags($movieInfo['genres'][i]['id']));
$genre = addslashes(strip_tags($movieInfo['genres'][i]['name']));
$stmt->execute();
}
If you insist on using mysql_XXX:
foreach ($movieInfo['genres'] as $genre) {
$genre = mysql_real_escape_string(strip_tags($genre['name']));
$genreid = mysql_real_escape_string(strip_tags($genre['id']));
mysql_query("INSERT INTO tblMovies (movie_id, genre_id, genre_name) VALUES ($movie_id , '$genreid', '$genre'");
}
I would insist that insert multiple records in database by firing single query instead of firing seperate query for each record.
E.g.:
INSERT INTO tblMovies
(genre_id, genre_name)
VALUES
('Name 1', 'Value 1'),
('Name 2', 'Value 2'),
('Name 3', 'Value 3'),
('Name 4', 'Value 4');
//Prepare the entire query using foreach and then fire single query.
foreach ($movieInfo['genres'] as $genre) {
$genre = mysql_real_escape_string(strip_tags($genre['name']));
$genreid = mysql_real_escape_string(strip_tags($genre['id']));
$parts[] = "('.$genreid.', '.$genre.')";
}
$str = implode("," $parts);
$query = "INSERT INTO tblMovies (genre_id, genre_name) VALUES ".$str.";";
mysql_query($query) or die(mysql_error());
Note: I have used mysql as you have mentioned in question but it is recommended to switch to mysqli or PDO. Also, from the question you have mentioned, I assume that $movie_id is auto-increment.