i am trying to concatenate sql queries and run later after loop. how is that possible? this is my vision:
for($i=1;$i<=10;$i++){
$item_.$i = "value_".$i;
sql = sql . " insert into table (`item`) values ('$item_'.$i.'')";
// this should be but an array
}
and save into db:
for($j=0;$j<sqlarray.length;$j++){
$sql_done = mysql_query($sqlarray[$j]);
}
i didnot try anything yet, because the database is big and i am afraid of destroying something important with my code..
thanks a lot
Use mysqli and bindings
see http://www.php.net/manual/en/mysqli.prepare.php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
// define your query
$query = "INSERT INTO tablename (column1,column2) VALUES (:col1,:col2)";
if ($stmt = $mysqli->prepare($query)) {
// loop of insert
for($i=0;$i<10;$i++){
$stmt->bind_param("col1", $i);
$stmt->bind_param("col2", 'test'.$i);
$stmt->execute();
}
$stmt->close();
}else{
throw new Exception("unable to prepare query");
}
$mysqli->close();
Binding will avoid a lot of security issue, no one should use something else then binding ever.
Even better put everything in a transaction and in case of error your database remains unchanged.
see: http://www.php.net/manual/en/mysqli.commit.php for more info
and here is a proposal with commit or rollback
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if (mysqli_connect_errno()) {
throw new Exception("Unable to connect");
}else{
try{
$mysqli->autocommit(FALSE);
// define your query
$query = "INSERT INTO tablename (column1,column2) VALUES (:col1,:col2)";
if ($stmt = $mysqli->prepare($query)) {
// loop of insert
for($i=0;$i<10;$i++){
$stmt->bind_param("col1", $i);
$stmt->bind_param("col2", 'test'.$i);
$stmt->execute();
}
$stmt->close();
}else{
throw new Exception("unable to prepare query");
}
$mysqli->commit();
}catch(Exception $e){
$mysqli->rollback();
}
$mysqli->close();
}
I did not try it but we should be near a good (best practice?) solution.
I hope this could help you.
For insert query you can write code like below:
$sql .= " insert into table (`item`) values ";
for($i=1;$i<=10;$i++){
$item_.$i = "value_".$i;
$sql = $sql . " ('$item_'.$i.''),";
}
mysqli_query( substr($sql ,0,-1) );
The above will concatenate all the insert data in a single string and execute at once.
I hope you were looking for this
$query = "insert into table_name values";
for($i=0;$i<4;$i++) {
$data1 = "test_".$i;
$data2 = "new_".$i;
$query .= "('','$data1','$data2'),";
}
$query = substr($query,0,-1);
echo $query;
Let me know
try below code
$sql="":
for($i=1;$i<=10;$i++)
{
$item_.$i = "value_".$i;
$sql.=" insert into table (`item`) values ('$item_'.$i.'')";
// this should be but an array
}
mysql_query($sql);
Related
Just changed my previous question to reflect PDO changes everyone told me to make. Am I doing this right? Error reporting right? Is everything secure?
Just changed my previous question to reflect PDO changes everyone told me to make. Am I doing this right? Error reporting right? Is everything secure?
try{
$connection = new PDO('mysql:host=supertopsecret;dbname=supertopsecret;charset=utf8mb4',
'supertopsecret', 'supertopsecret');
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
//Query 1 - Insert Provider's Name
//if(isset($_POST['submit'])){ delete this? do I still use this? halp
$stmt1 = $connection->prepare("INSERT INTO
`providers`(provider_first_name,provider_last_name,date_added)
VALUES (:providerfirstname, :providerlastname, NOW())");
//bind parameters:
$stmt1->bindParam(':providerfirstname', $providerfirstname);
$stmt1->bindParam(':providerlastname', $providerlastname);
//insert row
$providerfirstname = $_POST['providerfirstname'];
$providerlastname = $_POST['providerlastname'];
$stmt1->execute();
//Query 2 - Insert Practices
$prov_id = $connection->lastInsertId();
/*Get all values of practice_name[]:*/
$practicename = $_POST['practice_name'];
for ($i = 0; $i < count($practicename); $i++) {
if ($practicename[$i]) {
$practice_name_data = $practicename[$i];
$stmt2 = $connection->prepare("INSERT INTO
practices(prov_id,practice_name) VALUES (:prov_id,:practice_name)");
$stmt2->bindParam(':prov_id', $prov_id);
$stmt2->bindParam(':practice_name', $practice_name_data);
$stmt2->execute();
}
}
echo '<center><h3><br><br><br>Thank you! Your provider has
successfully been submitted to the database!</center></h3></br>';
} catch(PDOException $e){
echo "Sorry, there was an problem submitting your provider to the
database. Please try again or copy and paste the error code below to
the \"Report a Problem\" page and we will try to correct the problem.
</b></br></br> Error: " . $e->getMessage();
die();
}
$connection = null;
You should use prepared statements instead of escaping yourself, see How can I prevent SQL injection in PHP?. But it's probably '$practicename[$i]'. It would be '{$practicename[$i]}', but easier:
foreach($practicename as $value){
if($value!=""){
$value = mysqli_real_escape_string($connection, $value);
$query2 = mysqli_query($connection,
"INSERT INTO `practices`(prov_id,practice_name)
VALUES ('$prov_id','$value')");
}
}
But again, abandon this and use Prepared Statements!
Check this it may help you. Use PDO for insert.
$connection = new PDO("mysql:host=xxxx;dbname=xxxx;", "xxxx", "xxxx"); //database connection
for ($i = 0; $i < count($practicename); $i++) {
if ($practicename[$i]) {
$practice_name_data = $practicename[$i];
$statement = $connection->prepare('INSERT INTO practices(prov_id,practice_name) VALUES (:prov_id,:practice_name)');
$statement->bindParam(':prov_id', $prov_id);
$statement->bindParam(':practice_name', $practice_name_data);
// etc.
$statement->execute();
}
}
The first example will add data to mysql database without any issue. The second block of code - where I try to use variables wont. Can someone please explain where I am going wrong?
<?php
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES ('Edit me',4,1)";
$result = mysqli_query($connection, $query);
Problem CODE:
<?php
$menu_name = "TEST";
$position = 5;
$visible = 1;
$query = "INSERT INTO subjects (menu_name,position,visible)
VALUES ('{menu_name}',{position}, {visible})";
$result = mysqli_query($connection, $query);
*Answer updated with MySQLi prepare statement, thanks #h2ooooooo
<?php
//Open a new connection to the MySQL server
$db = new mysqli('host','username','password','database_name');
//Output connection errors
if ($db->connect_error) {
die('Error : ('. $db->connect_errno .') '. $db->connect_error);
}
$sql = "INSERT INTO subjects (menu_name, position, visible) VALUES (?, ?, ?)";
if (!$stmt = $db->prepare($sql)) {
echo 'Database prepare error';
exit;
}
$stmt->bind_param('sss', $menu_name, $position, $visible);
if (!$stmt->execute()) {
echo 'Database execute error';
exit;
}
$stmt->close();
I'd say for you to take a look in the many tutorials thorugh net, like these:
http://markonphp.com/simple-insert-mysqli/ and
http://www.sanwebe.com/2013/03/basic-php-mysqli-usage
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES
('".$menu_name."','".$position."', '".$visible."')";
try this
I have been troubleshooting this code for awhile, but it won't work and I can't find out why. Does anyone see an error? Also, I'm aware that there is no WHERE statement, I intentionally want to update all records.
<?php
// Connect to database
$link = mysqli_connect('*****', '*****', '*****');
if (!$link) {
die('Could not connect: ' . mysqli_connect_error());
}
mysqli_select_db(bullseye);
// Varaible setting
$header = $_POST['header'];
$video = $_POST['video'];
$m_title = $_POST['m_title'];
$m_sub = $_POST['m_sub'];
$w_title = $_POST['w_title'];
$w_sub = $_POST['w_sub'];
$w_t1 = $_POST['w_t1'];
$w_t2 = $_POST['w_t2'];
$w_t3 = $_POST['w_t3'];
$w_d1 = $_POST['w_d1'];
$w_d2 = $_POST['w_d2'];
$w_d3 = $_POST['w_d3'];
$p_title = $_POST['p_title'];
$p_sub = $_POST['p_sub'];
mysqli_query($link, "UPDATE tbl_name SET
header=$header,
video=$video,
mtitle=$m_title,
msub=$m_sub,
wtitle=$w_title,
wsub=$w_sub,
wt1=$w_t1,
wt2=$w_t2,
wt3=$w_t3,
wd1=$w_d1
wd2=$w_d2,
wd3=$w_d3,
ptitle=$p_title,
psub=$p_sub");
?>
EDIT:
mysqli_query($link, "UPDATE about SET
header='$header',
video='$video',
mtitle='$m_title',
msub='$m_sub',
wtitle='$w_title',
wsub='$w_sub',
wt1='$w_t1',
wt2='$w_t2',
wt3='$w_t3',
wd1='$w_d1',
wd2='$w_d2',
wd3='$w_d3',
ptitle='$p_title',
psub='$p_sub'");
First off, you should prepare it using MySQLi as to protect yourself from MySQL injection:
$mysqli = new mysqli("localhost", "my_user", "my_password", "bullseye");
$query = $mysqli->prepare("UPDATE tbl_name SET
header=?,
video=?,
mtitle=?,
msub=?,
wtitle=?,
wsub=?,
wt1=?,
wt2=?,
wt3=?,
wd1=?
wd2=?,
wd3=?,
ptitle=?,
psub=?");
$query->bind_param("ssssssssssssss, $header, $video, $m_title, $m_sub, $w_title, $w_t1, $w_t2, $w_t3, $w_d1, $w_d2, $w_d3, $p_title, $p_sub");
$query->execute();
$query->close();
$mysqli->close();
This code should work. If it doesn't please post the error.
It looks you need to concat your query with your variables. And not just a big string.
You should use the following to chose your database:
mysqli_select_db($link, "bullseye");
So I am having a difficult time getting a variable using a mysql search command and then using it in the same script in an insert command. What am I doing wrong?
<?php
$usto= $_GET["usto"];
$itena= "item";
$sql = 'SELECT sname FROM login';
$hostname_Database = "blocked";
$database_Database = "blocked";
$username_Database = "blocked";
$password_Database = "blocked";
$mysqli = new mysqli($hostname_Database, $username_Database, $password_Database, $database_Database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli->query($sql);
if ($result) {
$row = $result->fetch_assoc();
$sql = "INSERT INTO pon(mis, take)
VALUES({$row['snake']}, '" . $usto . "')"; //Here, I am trying to use the result from the previous select statement for the variable
$result = $mysqli->query($sql);
if ($result) {
...etc.
}
}
?>
You are vulnerable to SQL injection attacks. Read up about those and fix your code FIRST.
After that, realize that ->query() calls return a result HANDLE, not the actual field(s) you'd requested in your query. You have to FETCH a row of data first:
$result = $mysqli->query($sql);
$row = $result->fetch_assoc();
$sql = ".... VALUES ({$row['name_of_field']} ...)";
Note that this is STILL vulnerable to SQL injection.. it's purely to illustrate the query/fetch/insert process.
I am trying to use mysqli for the first time because i have some problems with multiple Query's in one php file. for start im just trying to retrieve data from the stored procedure and print it. but it looks like the code get's stuck somewhere it printed 'succesfull localhost' but it never get's to the code under it. The data never get printed neither the failed.
<?php
$link = mysqli_init();
if (!$link) {
die('mysqli_init failed');
}
if (!mysqli_options($link, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}
if (!mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}
if (!mysqli_real_connect($link, 'localhost', 'root', '', 'fabiola')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . mysqli_get_host_info($link) . "\n";
//require 'header.php';
$resID = mysqli_real_escape_string($_REQUEST['resID']);
$materialen_id = mysqli_real_escape_string($_REQUEST['materialen_id']);
$aantal = mysqli_real_escape_string($_REQUEST['aantal']);
$effectief_gebruikt = mysqli_real_escape_string($_REQUEST['effectief_gebruikt']);
$opmerking = mysqli_real_escape_string($_REQUEST['opmerking']);
$datum_van = $_REQUEST['datum_van'];
$datum_tot = $_REQUEST['datum_tot'];
$sqm = "CALL aantal_besch_mat_van_tot($datum_van,$datum_tot,$materialen_id,$resID)";
//$result = $mysqli->query($sqm) or die('Query Failed!');
/* Select queries return a resultset */
if ($result = $mysqli->query($sqm)) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* free result set */
mysqli_free_result($result);
}else{
echo 'failed';
}
mysqli_close($link);
?>
Where is $mysqli set or initialized?
There should be something like:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
but I can't see it.
btw it's weird that you're mixing the function calling convention 'mysqli_real_escape_string(...)' with the object-orientated functions '$mysqli->query(...)' I'm not sure it's safe to do both.
Also, you will save yourself a lot of heartache by using the MySQLi prepared statements rather than trying to make all your input safe by hand e.g.
$query = "CALL aantal_besch_mat_van_tot(?, ?, ?, ?);";
$statement = $mysqli->prepareStatement($query);
$statement->bind_param('iiii', $datum_van, $datum_tot, $materialen_id, $resID);
$statement->execute();
//get the results.
$statement->close();
$mysqli->close();
It's just so much easier, and more secure to use prepared statements (at the cost of a few percent of performance) that really you should almost always use them.