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);
Related
can it be combine into 1 query?
this is the query that im trying to combine? or is there a better way to relate these to table?
$insert_row = $mysqli->query("INSERT INTO orderlist
(TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY)
VALUES ('$transactionID','$itemname','$itemnumber', $ItemTotalPrice,'$itemqty')");
$insert_row1 = $mysqli->query("INSERT INTO order
(BuyerName,BuyerEmail,TransactionID)
VALUES ('$buyerName','$buyerEmail','$transactionID')");
when i run these both only one query is functional, so what im trying to do is to make them both works.
im open to any suggestion
The reason why your second query isn't working is because of the use of order and not escaping it; it is a MySQL reserved word:
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
Sidenote: ORDER is used when performing a SELECT... ORDER BY...
https://dev.mysql.com/doc/refman/5.0/en/select.html
Checking for errors would have shown you the syntax error such as:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax near 'order
http://php.net/manual/en/mysqli.error.php
Therefore, wrap it in ticks:
$insert_row1 = $mysqli->query("INSERT INTO `order` ...
or rename your table to something other than a reserved word, say orders for example.
If you wish to combine both queries, you can use multi_query()
http://php.net/manual/en/mysqli.quickstart.multiple-statement.php
Example from the manual:
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";
if (!$mysqli->multi_query($sql)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
do {
if ($res = $mysqli->store_result()) {
var_dump($res->fetch_all(MYSQLI_ASSOC));
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result());
?>
I also need to point out that your present code may be open to SQL injection since I do not know if you are escaping your data.
If not, then use prepared statements, or PDO with prepared statements, they're much safer.
try to add IF statement.
if ($insert_row = $mysqli->query("INSERT INTO orderlist(TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY)VALUES ('$transactionID','$itemname','$itemnumber', $ItemTotalPrice,'$itemqty')"));
{
$insert_row1 = $mysqli->query("INSERT INTO order (BuyerName,BuyerEmail,TransactionID) VALUES ('$buyerName','$buyerEmail','$transactionID')");
}
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.
I am trying to insert the results from a json array into MySQL using
foreach ($feed->items as $item) {
$query = "insert into data(id,url,keyword)values ($item->id, $item->url,$item->kind)";
$result = mysql_query($query);
echo $result;
}
I have confirmed the database details are OK and the $items are correct.
Can anyone point me in the right direction? I am fairly new to PHP so any help is appreciated.
You need to escape the values in the SQL:
$query = "insert into data(id,url,keyword)values ('" . mysql_real_escape_string($item->id) . "', '" . mysql_real_escape_string($item->url) . "' , '". mysql_real_escape_string($item->kind) . "')";
this adds quotation marks ' around the variables so that the SQL can be parsed at all
This prevents SQL injection.
You need to wrap your variabels in your query :
$query = "insert into data(id,url,keyword)values ('{$item->id}', '{$item->url}', '{$item->kind}')";
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
I need the id of the last inserted object. I use prepared statements to avoid sql injection.
But i'm not sure how to obtain the id.
$sql = "INSERT IGNORE INTO faculty (id, term, role, prefix, first_name,
middle_name, last_name, suffix) VALUES (?,?,?,?,?,?,?,?)";
if (!($stmt = $mysqli->prepare($sql)))
echo "Faculty Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
$stmt->bind_param('sissssss',
$faculty['id'],
$faculty['term'],
$faculty['role'],
$faculty->name->prefix,
$faculty->name->first,
$faculty->name->middle,
$faculty->name->last,
$faculty->name->suffix
);
if (!$stmt->execute())
echo "Faculty Execute failed: (" . $mysqli->errno . ") " . $mysqli->error;
$result = $stmt->insert_id;
echo "\n Result:" . $result;
$stmt->close();
The result is 0 always despite there being an entry in the database
Solution
The element was being inserted into the database. The problem was when I had created the table id wasn't an integer it was a varchar which represented an employee id. To fix this, i added the employee id as an additional column in the table and used the default id int auto_increment primary key and it worked.
Try changing $result = $stmt->get_result(); to $result = $stmt->insert_id;
get_result() is more for SELECT queries, rather than INSERTs.
http://php.net/manual/en/mysqli-stmt.get-result.php
http://php.net/manual/en/mysqli-stmt.insert-id.php