Entering an array into my database using mySQL - mysql

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.

Related

SQL IF EXIST UPDATE ELSE INSERT prepared statement

I'm breaking my brains over this, i would realy appriciate help!
This is the code i have so far..
$conn = db_connect();
$sql = "INSERT INTO measurements
(`date`, `weight`, `waist`, `id`) VALUES (?,?,?,?)";
$stmt = $conn-> prepare($sql);
$stmt ->bind_param("sddi", $date, $_POST['weight'], $_POST['waist'], $user_id);
$stmt->execute();
$stmt->close();
$conn->close();
Its a prepared statement for an sql insert. Now i want to change it to a IF EXIST THEN UPDATE ELSE insert the way i am doing right now. something like this but then with a prepared statement:
IF EXISTS
(SELECT * FROM measurements WHERE user_id=’4’)
UPDATE measurements SET (`weight`=40, `waist`=45) WHERE user_id=’4’
ELSE
INSERT INTO measurements
VALUES (`date`='week 1', `weight`= 40, `waist`=45, `id`=4)
I found some articles on stackoverflow about the if EXIST then update else insert but i did not find it with a prepared statement in it that worked for me.
Thanks a thousand!
UPDATE:
i've changed it to dublicate key style.
$sql = "
INSERT INTO measurements (uniqueID, date, weight, waist)
VALUES ('$uniqueID', '$date', '$weight', '$waist')
ON DUPLICATE KEY UPDATE weight= '$weight', waist= '$waist'";
$conn->query($sql);
Now the second part of the question, how do i make this a prepared statement?
To implement Mr. Jones' solution as a mysqli prepared statement, you would code it thus:
$sql = "INSERT INTO measurements
(`uniqueID`, `date`, weight, waist)
VALUES
(?, ?, ?, ?)
ON DUPLICATE KEY
UPDATE weight = ?, waist = ?";
$stmt = $conn->prepare($sql);
$stmt ->bind_param("isdddd", $user_id, $date, $_POST['weight'], $_POST['waist'], $_POST['weight'], $_POST['waist']);
$stmt->execute();
A slightly cleaner implementation would be to use PDO:
$sql = "INSERT INTO measurements
(`uniqueID`, `date`, weight, waist)
VALUES
(:uniqueId, :date, :weight, :waist)
ON DUPLICATE KEY
UPDATE weight = :weight, waist = :waist";
/* $conn is a PDO object */
$stmt = $conn->prepare($sql);
$stmt->execute(array(':uniqueId' => $user_id, ':date' => $date, ':weight' => $_POST['weight'], ':waist' => $_POST['waist']));
Note that with named placeholders, you can use the same name in more than one place and only need to assign the value once.
MySQL's approach to this is INSERT ... ON DUPLICATE KEY UPDATE .... It works well; in particular it avoids race conditions if more than one database connection tries to hit the same row.
This requires the table that's the target of your UPSERT to have a meaningful unique index or primary key. It looks like your id is that key.
You can absolutely use parameter binding to present data to this.
You can read about it here. http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html

need to insert from grid to mysql database

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);

mysql, if row exists incrament value else insert row without key

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];

Insert multiple values in one column mysql?

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.

MYSQL INSERT problem

$body = $_POST['post'];
$submit = $_POST['submit'];
$date = date("Y-m-d");
require('php/connect.php');
if($submit)
{
$query = mysql_query("INSERT INTO news (`id`, `body`, `date`) VALUES (NULL, '".$body."', '".$date."')");
header("Location: index.php");
}
I do not understand why this isn't working, I took the query straight from PHP my admin after writing a line simular myself before hand and it still isn't working, can someone hep?
you definitely should escape your input values using mysql_real_escape_string
With mysql_error you can print out an error message but you need the connection identifier as a parameter.
I just suggest to handle mysql error
$query = mysql_query("INSERT INTO news (`id`, `body`, `date`) VALUES (NULL, '".$body."', '".$date."')")
or trigger_error(mysql_error());
and if id is primary key that can not be null
you should escape user input using mysql_real_escape_string function.
What happen if I put "that's it " value in your $body input, your query will fail.
Comment out your header("Location: index.php"); and append or die(mysql_error()); at the end of your query code that will show you what went wrong. You should also "mysql_real_escape_string" your user input before inserting it into your database.
$body = mysql_real_escape_string($_POST['post']);
$submit = $_POST['submit'];
$date = date("Y-m-d");
require('php/connect.php');
if($submit)
{
$query = mysql_query("INSERT INTO news (`id`, `body`, `date`) VALUES (NULL, '$body', '$date')") or die(mysql_error());
//header("Location: index.php");
}