Cannot send multiple mysql queries to my database via php - php

I've no idea what is going on here, but I cannot get two mysql statements to add content to my db via the mysql_query. Here is my code:
function sendDataToDB() {
// first send the user to the users table
$audio_survey = new dbclass();
$audio_survey -> connectToDB();
$sql = $_SESSION['user']['sql'];
$audio_survey -> queryTable($sql);
// get the current users' ID number from the table
$sql = "SELECT user_id FROM users WHERE name=\"" . $_SESSION['user']['name'] . "\"";
$result = $audio_survey -> queryTable($sql);
$output = $audio_survey -> getDataFromDB($result);
$user_id = $output['user_id'];
$songs = $_SESSION['songs'];
foreach ($songs as $song) {
$sql .= "INSERT INTO survey (user_id, song, genre, emotion, time_date) VALUES ($user_id, \"" . $song['song'] . "\", \"" . $song['genre'] . "\", \"" . $song['emotion'] . "\", \"" . $song['time_date'] . "\");<br />";
}
$audio_survey -> queryTable($sql);
$audio_survey -> closeDBconnection();
}
Everything works, as in a user gets added to my "users" table, but when the variable $sql is passed into mysql_query then I get this error:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO survey (user_id, song, genre, emotion, time_date) VALUES (3, "one mo' at line 1
I've tried pasting in the statement I have concatenated using the $sqlvariable straight into the sql query box in phpMyAdmin and it works! This is what the foreach loop produces that works in phpMyAdmin, but not the mysql_query function! I've made sure I have allocated enough space for characters, etc.
INSERT INTO survey (user_id, song, genre, emotion, time_date) VALUES (3, "one more time", "dance", "happy", "15:32:21 07-11-14");
INSERT INTO survey (user_id, song, genre, emotion, time_date) VALUES (3, "dance dance dance", "disco", "relaxed", "15:32:28 07-11-14");

http://php.net/manual/en/function.mysql-query.php
mysql_query() sends a unique query (multiple queries are NOT supported)
Docu-cite-service (tm)
You need to either use Nisse's approach, while calling mysql_query() inside the loop - or use something else, that allows to execute multiple queries within one statement rather than the deprecated mysql_query method.
Another option would be to rewrite your concatenation logic, so it generates one query for multiple inserts:
INSERT INTO survey
(user_id, song, genre, emotion, time_date)
VALUES
(3, "one more time", "dance", "happy", "15:32:21 07-11-14"),
(3, "dance dance dance", "disco", "relaxed", "15:32:28 07-11-14"),
...
something like
$sql = "INSERT INTO survey (user_id, song, genre, emotion, time_date) VALUES ";
$atLeastoneInsert = false;
foreach ($songs as $song) {
$atLeastoneInsert = true;
$sql .= "($user_id, \"" . $song['song'] . "\", \"" . $song['genre'] . "\", \"" . $song['emotion'] . "\", \"" . $song['time_date'] . "\"),";
}
$sql = trim($sql,",");
if ($atLeastoneInsert){
$audio_survey -> queryTable($sql);
}

$sql = "SELECT user_id FROM users ...";
...
foreach ($songs as $song) {
$sql .= "INSERT INTO survey ...";
}
You are adding all the queries together using the (.=) string concatenation operator. You need to use normal assignment, and move queryTable($sql) into the loop.
foreach ($songs as $song) {
$sql = "INSERT INTO survey ...";
$audio_survey -> queryTable($sql);
}
Note also that the MySQL extension is deprecated and will be removed in the future. You should use MySQLi or PDO instead.

Related

SQL multiple insert with sleep

Is it possible to insert multiple data with delay kind of thing/sleep for a few second?
for example here, Im going to insert the values (1,2) into my user table. Then after 5 seconds, it will proceed to insert value (3,4) into the same table, wait for 5 seconds and finally insert (5,6) into the table.
INSERT INTO User (col1, col2)
VALUES (1, 2), (3, 4), (5, 6)
Any suggestions are really appreciated!
<?php // da
$array = array(1, 2, 3, 4);
foreach ($array as $data) {
mysqli_query($conn,"INSERT INTO ... SET data='".$data."'");
sleep(1)
}
?>
Something like that? I did not understand very well.
I found the solution. Maybe it's a bit messy but this is what I've come with and solved my problem. Basically I just need to use prepare if I want to reuse the statement.
$stmt = $dbh->prepare("INSERT INTO user (col1, col2) VALUES ('1','2');
$stmt2 = $dbh->prepare("INSERT INTO user (col1, col2) VALUES ('3','4');
$stmt3 = $dbh->prepare("INSERT INTO user (col1, col2) VALUES ('5','6');
{ $stmt->execute();
sleep(5);
$stmt2->execute();
sleep(5);
$stmt3->execute();
}
That's all. Thanks for those who tried to solve this.
So what I do is create the query by concatenating it like this. But if you want to have multiple inserts you can call that function in a loop and remove this sleep put it in the loop outside the function or you can leave it there if the call is not a thread.
<?php
static function insert_table_db($anArra){
$dbconn = mysqli_connect(DB_HOST, DB_USER,DB_PASSWORD, DB_DATABASE) or die('MySQL connection failed!' . mysqli_connect_error());
mysqli_set_charset($dbconn, "utf8");
$query = "INSERT INTO `table`(`col1`, `col2`, `col3`, `col4`, `col5`) VALUES ";
$i = 1;
foreach ($anArray as $item) {
$query = $query . "(" . $item[0]. "," . $item[1]. "," . $item[2] . "," . $item[3] . ",'" . $item[4] . "')";
if (count($anArray) == $i){
$query = $query . ";";
} else {
$query = $query . ",";
}
$i++;
}
// Run query
if($dbconn->query($query) === true) {
$dbconn->close();
} else {
echo "Database Error: " . $dbconn->error;
$dbconn->close();
}
sleep(5);
}
?>
UPDATE: Sorry if some variables don't make sense I stripped it out of a library I have built and there are some extra things that I didn't delete ;D.

using implode to insert values into database table columns

I am using php implode to insert values, fetched from array of input fields, into a database table column. This works fine for me:
$insert_row =mysql_query("INSERT INTO ActivityProduct (Ideal) VALUES (" . implode('),(', $_POST["ideal"]) . ")");
I'd like to now insert values, fetched from two different array of input fields, into two database table columns. The below code produces and error:
$insert_row =mysql_query("INSERT INTO ActivityProduct (AID,Ideal) VALUES (" . implode('),(', $_POST["act"]) . " ," . implode('),(', $_POST["ideal"]) . ")");
i'd like to express the two arrays, in the insert statement, as, e.g: (10,21),(20,31),(30,41) and not (10),(21),(20),(31),(30),(41)
any idea on how to go about this, is highly appreciated.
Use like this it may help you
$ideal=implode('),(', $_POST["ideal"]);
$act=implode('),(', $_POST["act"]);
$insert_row =mysql_query("INSERT INTO ActivityProduct (Ideal) VALUES (" .mysql_real_escape_string($ideal). ")");
$insert_row =mysql_query("INSERT INTO ActivityProduct (AID,Ideal) VALUES (" .mysql_real_escape_string($ideal). " ," .mysql_real_escape_string($act). ")");
and try to use mysqli insted of mysql.
In mysqli
$insert_row = mysqli->prepare("INSERT INTO ActivityProduct (Ideal) VALUES ($ideal)");
$insert_row =mysql_query("INSERT INTO ActivityProduct (AID,Ideal) VALUES ($ideal,$act)");
replace this query with your query its work you
$insert_row =mysql_query("INSERT INTO ActivityProduct (AID,Ideal) VALUES ( '". implode('),(', $_POST["act"]). "' ,'" .implode('),(', $_POST["act"])."')");
Please note that the mysql_query extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
Since a MySQLi example has been given consider if you were to use PDO.
// Build the parameter list
$sql = array(); $params = array();
for ($i=0; isset($_POST['ideal'][$i])&&isset($_POST['act'][$i]); $i++) {
$sql[] = ":act_{$i}, :ideal_{$i}";
$params["ideal_{$i}"] = $_POST['ideal'][$i];
$params["act_{$i}"] = $_POST['act'][$i];
}
// Then run the query safely using PDO
$dbh = new PDO('mysql:host=localhost;dbname=test', "user", "pass");
$stmt = $dbh->prepare("INSERT INTO ActivityProduct (AID, Ideal) VALUES (".implode("), (", $sql).")");
$result = $stmt->execute($params);

What am I missing with php command to INSERT INTO SELECT FROM?

I have a database and it contains four tables (for the sake of security I gave them disney character names) named huey, dewey, lewey and uncledonald.
I would like to have the data from the columns deweysays in the table dewey, hueysays from the table huey and leweysays from the table lewey to show up in thier corresponding columns in the table uncledonald. See attached pic to see visually what I mean.
4 tables
I've tried the following code and get the result I want but only once. After that I get data in the dewey, huey and lewey tables but nothing else in the uncledonald table.
<?php
//Let's see whether the form is submitted
if (isset ($_POST['submit'])) {
$con=mysqli_connect("localhost","root","root","provingground");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO dewey (lot_id, deweysays) VALUES (0, '{$_POST['deweyspeak']}');";
$sql .= "INSERT INTO huey (cust_id, hueysays) VALUES (0, '{$_POST['hueyspeak']}');";
$sql .= "INSERT INTO lewey (personal_id, leweysays) VALUES (0, '{$_POST['leweyspeak']}');";
$sql .= "INSERT INTO uncledonald (deweysays) SELECT deweysays FROM dewey ";
$sql .= "INSERT INTO uncledonald (hueysays) SELECT hueysays FROM huey ";
$sql .= "INSERT INTO uncledonald (leweysays) SELECT leweysays FROM lewey ";
// Execute multi query
if (mysqli_multi_query($con,$sql)){
print '<p> The Ducks Have Spoken.</p>';
} else {
die ('<p>Could not add entry because:<b>' . mysqli_error() . '</b>.</p><p>The query being run was: ' . $sql . '</p>');
}
}
mysqli_close($con);
?>
Is there something missing in my $sql query to uncledonald? Please help!

How to grab an auto incremented variable and insert it into an insert query

I am trying to do a couple of php insert queries into a relational database, but I am running into a bit of an issue. In order for this relation to work I need to grab the autoincremented value from the first query and then insert it into the second query so the relation between the two exists.
I have this:
$query2 = "INSERT into words values ('' ,'$name') ";
-- The first value listed as '' is the auto-incremented primary key --
$query3 = "INSERT into synonyms values ('' , '', $alias') ";
-- The first value listed is the auto incremented pk, the second value needs to be the fk or the pk from the first query, but I don't know how to place it there. --
Is there a way to do this? Any help would be appreciated.
Here an SQL Fiddle to help y'all out:
http://sqlfiddle.com/#!2/47d42
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO words(word) values ('word1')");
$last_id = mysql_insert_id();
mysql_query("INSERT INTO words(synonym_id,synonym) values ($last_id, "synonym1)");
?>
Reference: http://php.net/manual/en/function.mysql-insert-id.php
. . You should consider using PDO in most recent PHP versions for its modern features, such as prepared statements, so that you don't need to worry about SQL Injection or broken escaping functions.
. . Using transactions is also advisable if the follow up queries are mandatory for the record to be useful. Using transactions keeps your database clear of the garbage of any failed second or third queries.
. . Also, you can omit the Auto-Increment field when running the Insert Query if you list the other fields after the table name. I think it's a much more common pattern, like INSERT INTO table (field1, field2) VALUES ("value1", "value2"). I used it in the example below:
$pdo = new PDO('mysql:host=localhost;dbname=database', 'user', 'pass');
$pdo->beginTransaction();
try {
$prepared = $dbh->prepare('INSERT INTO words (fieldName) values (?)');
$prepared->execute(array($name));
$fID = $pdo->lastInsertId();
$prepared = $dbo->prepare('INSERT INTO synonyms (fieldName) Values (?, ?)';
$prepared->execute(array($fID, $alias));
$dbo->commit();
} catch(PDOExecption $e) {
$dbo->rollback();
print 'Error: '. $e->getMessage();
}
. . Note that this will not work with MSSQL as it doesn't support "lastInsertId".
. . Amplexos.
not sure if you're using MySQL native functions or not. If so the answer is to use mysql_last_id(). These functions are deprecated and are not adivsable to use.
EXAMPLE:
//escape your indata
$brand= mysql_real_escape_string($_POST['brand']);
$sql = "INSERT INTO cars(brand) VALUES('{$brand}')";
mysql_query($sql);
//find last id from query above
$id = mysql_last_id();
Try PDO instead:
PDO::lastInsertId
EXAMPLE:
$brand= $_POST['brand'];
$sql = "INSERT INTO cars(brand) VALUES (:brand)";
$query = $conn->prepare($sql);
$query ->execute(array(':brand'=>$brand));
$id = $conn->lastInsertId();
http://www.php.net/manual/en/book.pdo.php

Is there a better way to insert values to MySQL query than just VALUES($var1, $var2, $var3)?

I just have the array of 15 values that all need to be inserted into the table.
And I was just wondering if there is anything like this:
INSERT INTO table VALUES($myarrayofvalues)
Just curious, would be very useful.
Update:
Just one row with 15 columns.
$query = "INSERT INTO table VALUES('" . implode("', '", $myarrayofvalues) . "')";
Edit:
If you haven't done your escaping yet, you can do that in a tiny loop before the above statement, something like:
foreach($myarrayofvalues as $k=>$v)
$myarrayofvalues[$k] = mysql_real_escape_string($v);
While you can do what's show in the answer by Rick, it is open to SQL injection.
There is really no good way to do this without some kind of column mapping. That is something to state element 1 is a string, element 2 is an integer.
As such, I see two choices:
Escape everything
$values = array();
foreach ($myarrayofvalues as $value) {
$column[] .= "'" . mysql_real_escape_string($value) . "'";
}
$sql = "INSERT INTO table VALUES(" . implode(',', $values) . ")";
Write the complete SQL statement
$sql = "INSERT INTO table (column1_string, column2_int, ...)
VALUES ('" . mysql_real_escape_string($myarray[0]) . "', " . (int)$myarray[1] . ", ...)
I prefer #2 because it is more readable and less brittle. Currently if your schema or array changes, your code breaks.

Categories