How to create sql insert query dynamically in mysql - php

I am creating an application where I am generating pins dynamically based on user's input and storing them into mySql database.
$sql = "INSERT INTO tblpin ('pinId', 'ownerId', 'usedby', 'status')
VALUES
for($i=0;$i<$npin;$i++)
{
('$pin[$i]','$ownerid', 'Free', '1');
}
;";
how can I do that?

$s = $pdo->prepare("INSERT INTO xy (a,b,c,d) VALUES (?,?,?,?)");
foreach ($pins as $i) {
$s->execute($i,$ownerID,"free",1);
}

Try this:
$sql = "INSERT INTO tblpin ('pinId', 'ownerId', 'usedby', 'status') VALUES ";
for($i=0; $i<sizeof($pin); $i++) {
if ($i>0)
$sql .= ", ";
$sql .= "('$pin[$i]', '$ownerid', 'Free', '1')";
}
Of course you need to escape the values of $pin in case they contain any characters which could mess with the SQL query.

Something like
$sql = sprintf( "INSERT INTO `tblpin` (`pinId`, `ownerId`, `usedby`, `status`) VALUES ('%s', '%s', '%s', '%s')",
generatePIN($pin),
mysql_real_escape_string($ownerId),
mysql_real_escape_string($usedBy),
mysql_real_escape_string( $status) );
or (edited for Conspicuous Compiler)
$pins = generatePINS($user); // ? however they're generated
foreach( $pins as $pin) {
$sql = sprintf( "INSERT INTO `tblpin` (`pinId`, `ownerId`, `usedby`, `status`) VALUES ('%s', '%s', '%s', '%s')",
$pin,
mysql_real_escape_string($ownerId),
mysql_real_escape_string($usedBy),
mysql_real_escape_string( $status) );
$result = mysql_query($sql);
}
where generatePIN is your function to make your pin based on whatever the heck you're basing it off of. or generatePINS returns an array of them

Related

SQL syntax error MariaDB server version for the right syntax to use near ('$fname', '$lname')

require('config.php');
$sql = sprintf(
"INSERT INTO users (fname,lname,email,contact,pwd,isTeacher ) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')",
$conn->real_escape_string($fname),
$conn->real_escape_string($lname),
$conn->real_escape_string($email),
$conn->real_escape_string($contact),
$conn->real_escape_string($pwd),
$isTeacher );
$conn->query($sql);
// $sql = "INSERT INTO users (fname, lname, email, contact, pwd, isTeacher) VALUES ('$fname, '$lname', '$email', '$contact, '$pwd', '$isTeacher')";
// $conn->query($sql);
if($conn=='true') { echo "Registered successfully";}
else{ echo "Issue entereing data" . $conn->error; }
}
I am trying to add data in users table. if I add data using sprintf, it works and adds just fine. but when I add using commented out syntax, it says check MariaDb syntax to use near '$fname'. What am I doing wrong in the second syntax. why do i have to use sprintf always.

PHP Can't get the ID of Last Record Inserted

I'm trying to get the ID of the last record inserted in my phpMyAdmin table, but I only get 0's so far.
I have tried almost everything (for example the solution on this answer: a link or what this page recommend : a link ) but I can't get it working.
My table has a column id that is the primary key and is marked as AUTO_INCREMENT.
I use a function query that make the connection to the database and then execute the queries:
function query($sql) {
$conn = mysqli_connect ( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
// Check connection
if (mysqli_connect_errno ()) {
echo 'connection failed: ' . mysqli_connect_error ();
}
// Check if the server is alive
if (mysqli_ping ( $conn )) {
// echo 'Connection is ok';
} else {
echo 'Error: ' . mysqli_error ( $dbc );
}
$sql = mysqli_query ( $conn, $sql );
$last_id = mysqli_insert_id( $conn );
$num_rows = mysqli_num_rows ( $sql );
$result = mysqli_fetch_assoc ( $sql );
return array (
"num_rows" => $num_rows,
"result" => $result,
"sql" => $sql,
"last_id" => $last_id
);
mysqli_close($conn);
}
Then I have another function from where I called the first one to execute the query:
function reg_shp_add($address_type, $company_name, $country, $state, $city, $zip, $street_name, $street_number, $tel){
if($address_type=="residential"){
$my_address_type = "r";
}else{
$my_address_type = "c";
}
$this->query ( "INSERT INTO `Addresses` (`company_name`, `street_address`, `address_two`, `zip_code`, `city_name`, `state_id`, `country_id`, `phone_number`, `res_comm_add`, `date_entered`) VALUES ('$company_name', '$street_name', '$street_number', '$zip', '$city', '$state', '$country', '$tel', '$my_address_type', CURRENT_TIMESTAMP)" );
$address_id = $sql ['user_id'];
$customer_id = $_COOKIE['userId'];
$this->query ( "INSERT INTO `Cust_address_type` (`cust_id`, ` mail_address_id`, `address_type`) VALUES ('$customer_id', '$address_id', 'Shipping')" );
return 'Address was saved.';
}
I first tried to retrieve the last id from my reg_shp_add function, but I guess it must be done from the first one.
Can anybody help me please?
I test your code and the function mysqli_insert_id work correctly with me ( ["last_id"]=> int(8) ). But the problem is in your second function, on the data retrieval ;
$this->query ( "INSERT INTO `Addresses` (`company_name`, `street_address`, `address_two`, `zip_code`, `city_name`, `state_id`, `country_id`, `phone_number`, `res_comm_add`, `date_entered`) VALUES ('$company_name', '$street_name', '$street_number', '$zip', '$city', '$state', '$country', '$tel', '$my_address_type', CURRENT_TIMESTAMP)" );
$address_id = $sql ['user_id'];
Here the $sql variable is undefined, you miss to store the return value into $sql, like that :
$sql = $this->query ( "INSERT INTO `Addresses` (`company_name`, `street_address`, `address_two`, `zip_code`, `city_name`, `state_id`, `country_id`, `phone_number`, `res_comm_add`, `date_entered`) VALUES ('$company_name', '$street_name', '$street_number', '$zip', '$city', '$state', '$country', '$tel', '$my_address_type', CURRENT_TIMESTAMP)" );
$address_id = $sql ['user_id'];

More efficient way of inserting data into mysql using PDo

Ok so I execute the following code for inserting data into database:
$db_conn->beginTransaction();
$query = $db_conn->prepare('INSERT INTO mytable(name, user) VALUES(:name, :user)');
foreach($UploadData AS $DataValue)
{
$query->execute(array(':name' => $DataValue['Name'],':user' =>$_SESSION['user']));
}
$db_conn->commit();
Now in this code block execute() runs 100s time if I have that much data. Like before I use to do with basic mysqli concatenation and executes the query only once.
Will that can be done here with PDO also?
$SQL = 'INSERT INTO mytable (name, user) VALUES';
foreach( $UploadData AS $DataValue)
$SQL .= sprintf(" ( '%s', '%s' ),", $DataValue['Name'], $DataValue['user'] );
$SQL = substr($SQL, -1);
$query = $db_conn->prepare($SQL);
$query->execute();
Result
INSERT INTO mytable (name, user) VALUES ('VAL', 'VAL'), ('VAL', 'VAL') ....

Insert statement with automatically generated columns

I want to create an INSERT statement using the columns of my table and NULL or blank values for the content except for the id, created_by .etc. I am trying to avoid duplicates. Right now I get:
INSERT INTO testimonials (id, created, created_by, id, quote, name, position, company, published, created, created_by, last_modified_by, last_modified) VALUES ('257927816', NOW(), '1', '')
and I would like to have blank values iterate in the VALUES section for everything but the first 3, which I define.
function insertBlankWithID($table, $postFxn) {
global $randomID;
$id = $randomID;
$resultInsert = mysql_query("SELECT * FROM " . $table);
if (!$resultInsert) {
echo '<div class="ec-messages messages-error">'.QUERY_ERROR.'</div>';
include($cmsdir . FOOTER_EXIT);
exit();
}
$columns = array();
while ($row = mysql_fetch_assoc($resultInsert)) {
if (empty($columns)) {
$columns = array_keys($row);
}
}
//$sql = 'INSERT INTO `testimonials` (`id`, `quote`, `name`, `position`, `company`, `published`, `created`, `created_by`, `last_modified_by`, `last_modified`) VALUES ('.$id.', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);';
$sql = sprintf("INSERT INTO %s (id, created, created_by, %s) VALUES ('".$id."', NOW(), '".$_SESSION['user_id']."', '%s')", $table, implode(', ', $columns), implode("', '", ''));
mysql_query($sql);
/*
if (!$sql) {
echo '<div class="ec-messages messages-error">'.QUERY_ERROR.'</div>';
exit();
}
*/
echo $sql;
}
// redirect(basename($_SERVER['PHP_SELF'], ".php").'?s=output&id='.$id
insertBlankWithID('testimonials', $postFxn);
Looking at your code, you should limit the select to 1, (ie $resultInsert = mysql_query("SELECT * FROM " . $table. " limit 1"); as you don't need the information, just the keys. That removes the need for the while loop.
Now, to get all the keys except the first three, for your $columns variable, use array_slice such as $columns = array_slice($columns, 3); Or, if it isn't the first three when you select *, you can do $columns = array_diff($columns, array('id', 'created', 'created_by') );
Now, to insert null after the first three, you are imploding a string - which won't work, instead you can make an array of null values matching the count of the new $columns such as:
$blanks = array_fill(0, count($columns), 'null');
and when creating your statement, do implode(", ", $blanks), which would make your $sql look like:
$sql = sprintf("INSERT INTO %s (id, created, created_by, %s) VALUES ('".$id."', NOW(), '".$_SESSION['user_id']."', '%s')", $table, implode(', ', $columns), implode(", ", $blanks));
And that should fix the issue you've described.
Also, while I'm here, it should be noted that you should not use mysql_ functions anymore and move to mysqli_ for the same type of procedure-oriented MySQL access.

What is proper way to skip a MySQL INSERT

I have a foreach statement looping through JSON data and inserting the contents into MySQL. I want to skip the insert if a specific username is shown for $author string. Is the below method ok or is it better to handle at the database level?
foreach ($response['data'] as $data) {
$id = $data['id'];
$created_time = $data['created_time'];
$thumbnail = $data['images']['low_resolution']['url'];
$author = $data['user']['username'];
$caption = mysql_real_escape_string($data['caption']['text']);
$link = $data['link'];
$likes = $data['likes']['count'];
if ($author == 'USERNAME') {
mysql_close($con);
} else {
$query = "INSERT IGNORE INTO pbr (id, created_time, thumbnail, author, caption, link, likes, hash) VALUES ('$id', '$created_time', '$thumbnail', '$author', '$caption', '$link', '$likes', '$hash')";
$result = mysql_query($query) or die(mysql_error());
mysql_close($con);
}
}
Why closing SQL connection at each loop iteration?
Why not simply do:
if ($author == 'USERNAME')
continue; // next iteration
$query = "INSERT IGNORE INTO pbr (id, created_time, thumbnail, author, caption, link, likes, hash)
VALUES ('$id', '$created_time', '$thumbnail', '$author', '$caption', '$link', '$likes', '$hash')";
$result = mysql_query($query) or die(mysql_error());
BTW you should bind parameters to your queries, or at least use mysql_real_escape_string() otherwise will have problems with values containing quotes (currently, you only do it for variable $caption, I guess that $link, $thumbnail and $username can contain single quotes as well).

Categories