SQL array values in php - php

Hi I'm really new to php/mysql.
I'm working on a php/mysql school project with 39 fields all in all in a single table.
I want to shorten my codes especially on doing sql queries.
$sql = "INSERT into mytable ('field_1',...'field_39') Values('{$_POST['textfield_1']}',...'{$_POST['textfield_39']}')";
I don't know how to figure out this but , i want something like:
$sql = "Insert into mytable ("----all fields generated via loop/array----") Values("----all form elements genrated via loop/array---")";
Thank you in advance.

<?php
function mysql_insert($table, $inserts) {
$values = array_map('mysql_real_escape_string', array_values($inserts));
$keys = array_keys($inserts);
return mysql_query('INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $values).'\')');
}
?>
For example:
<?php`enter code here`
mysql_insert('cars', array(
'make' => 'Aston Martin',
'model' => 'DB9',
'year' => '2009',
));
?>
try this it i thhink it il work

You could use implode:
$sql = "
INSERT into mytable
('" . implode("', '", array_keys($_POST) . "')
VALUES
('" . implode("', '", $_POST . "')";
(This assumes the indices of the POST array are also the names of the db table fields)
However, this is extremely insecure since you would directly insert post data into the database.
So the least you should do beforehand is escape the values and make sure they are ok/valid table fields:
// Apply mysql_real_escape_string to every POST value
array_walk($_POST, "mysql_real_escape_string");
and
// Filter out all POST values with invalid indices
$allowed_fields = array('field_1', 'field_2', /* ... */ );
$_POST = array_intersect_key($_POST, $allowed_fields);

<?php
$sql = "Insert into mytable (";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "field_$i";
} else {
$sql .= "field_$i,";
}
}
$sql .= "Values(";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "'" . $_POST[textfield_$i] . "'";
} else {
$sql .= "'" . $_POST[textfield_$i] . "',";
}
}
?>

< ?php
$sql = "Insert into mytable (";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "field_$i";
} else {
$sql .= "field_$i,";
}
}
$sql .= "Values(";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
if(is_int($POST[textfield$i])){
$sql .= $POST[textfield$i];
}
else{
$sql .= "'" . $POST[textfield$i] . "'";
}
} else {
if(is_int($_POST[textfield_$i])){
$sql .= $_POST[textfield_$i] .",";
}
else{
$sql .= "'" . $_POST[textfield_$i] . "',";
}
}
}
?>
it will work for numeric values. you can insert numeric values in single quotes but some times it will create some problems

Related

Dynamic amount of bindParam

So I am trying to make an undetermined amount of bindParam calls within a foreach, but for some reason it fails. I know the $sql variable is working fine, but I am pretty sure it is failing at the bindParam. Is there any reason for this?
$sql = "INSERT INTO " . $row1["rand"] . " (" . $areas . ") VALUES (" . $vals . ")";
echo $sql;
$entry2 = $conn->prepare("'".$sql."'");
//echo "swag";
foreach($splitHeader as $element){
if(strlen($element)>0) {
$thisVal = "':" . $element . "'";
$entry2->bindParam($thisVal,$_POST[$element]);
}
}
$entry2->execute();
The number of parameters that you define in the query must match the number of parameters that you bind.
You would need to loop twice trough your data : once to dynamically construct a sql statement (that you can then prepare), and then a second time to bind the parameters, before finally calling execute.
Here is an adaptation of your code that demonstrates the principle :
$cols = "";
$vals = "";
foreach( $splitHeader as $element ) {
if( strlen($element) > 0 ) {
if ( strlen($cols) > 0 ) {
$cols .= ", ";
$vals .= ", ";
}
$cols .= $element;
$vals .= "?";
}
}
$sql = "INSERT INTO " . $row1["rand"] . " (". $cols . ") VALUES(". $vals . ")";
echo $sql;
$sth = $conn->prepare($sql);
$i = 1;
foreach($splitHeader as $element){
if( strlen($element) > 0 ) {
$sth->bindParam( $i, $_POST[$element] );
$i++;
}
}
$sth->execute();

How to use single for each loop for multiple array to update single sql statement

I want to use single for each for two array.
array 1 : has path of images (path is dynamic as per user need)
array 2: has values description field of each image (description is dynamic as per user need)
I want to insert both array in sql table using only one sql statement.
<?php $sql="INSERT INTO posts(title,description,category,createdBy,pictureURL,CreatedAt) VALUE ('$title',
'$description','$category','$creatdby','Admin/PostImages/$finalpath',now());";
$result = mysqli_query($conn,$sql);
if($result)
{
$upload_directory = 'PostImages/';
$field_values_array = $_REQUEST['desc'];
$x=0;
foreach($field_values_array as $value1){
foreach ( $_FILES['photo']['name'] AS $key => $value ){
//Move file to server directory
if(move_uploaded_file($_FILES["photo"]["tmp_name"][$x], $upload_directory . $_FILES["photo"]["name"][$x])){
$finalpath=$upload_directory . $_FILES["photo"]["name"][$x];
}
if (isset($_SESSION['p_id'])){
$p_id = $_SESSION["p_id"];
}
$sql1="INSERT INTO `postimages`(`p_id`,`description`, `img_path`) VALUES ('$p_id','$value1','$finalpath')";
$result1 = mysqli_query($conn,$sql1);
$x++;
}
}
header("Location: uploadpost_test.php");
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
} ?>
I refactor and clean up your codes. Try this.
if(isset($_SESSION['p_id']))
{
$p_id = $_SESSION["p_id"];
}
$values = '';
$next = ',';
$len = count($field_values_array);
foreach($field_values_array as $x=>$value1)
{
if(move_uploaded_file($_FILES["photo"]["tmp_name"][$x], $upload_directory.$_FILES["photo"]["tmp_name"][$x]))
{
$tmp_name = $_FILES["photo"]["tmp_name"][$x];
$finalpath = $upload_directory.$tmp_name;
$next = $x >= $len-1 ? '' : $next;
$values .= "VALUES('$p_id','$value1','$finalpath')".$next;
}
}
$sql1="INSERT INTO `postimages`(`p_id`,`description`, `img_path`) $values";
$result1 = mysqli_query($conn,$sql1);

MYSQL Insert the same value again and again

I'm having problem with my query, it inserts the same the value again and again even though the value of the variable is different.
Here is the first page. it contains a randomizer for the creation of accounts.
function getRandomString($length = 10) {
$validCharacters = "1234567890";
$validCharNumber = strlen($validCharacters);
$result = "";
for ($i = 0; $i < $length; $i++) {
$index = mt_rand(0, $validCharNumber - 1);
$result .= $validCharacters[$index];
}
return $result;
}
$idNo=getRandomString();
function getRandomPassword($length = 6) {
$validCharacters = "qwertyuiopasdfghjklzxcvbnm1234567890";
$validCharNumber = strlen($validCharacters);
$result = "";
for ($i = 0; $i < $length; $i++) {
$index = mt_rand(0, $validCharNumber - 1);
$result .= $validCharacters[$index];
}
return $result;
}
$password=getRandomPassword();
The values will then be submitted to the next page which is below. The submitted values are correct because i print them out first to check. It always inserts the value "2147483647" for the ID_No even though this is not the randomize value.
$insert = "INSERT INTO person (ID_No, P_Word, E_Status)
VALUES('$userName', '$userPass', 'Applicant')";
$result = mysql_query($insert);
How do you fix this? Is it a bug?
We can only guess given the code posted.
I don't see where $index ends up being $userName.
The sql posted shows userName being inserted as a character string, quotes around it.
ID_No is likely an integer type and thus the character string fills it up.
This should just blow up on insert so you know that this is wrong. Best practice is to use sql_mode = 'STRICT_ALL_TABLES' in the MySQL configuration file.
I think you should check data type for id_no column..You must give double data type to that column
I think what you have in mind is this : You must use the string concatenation operator (here, in PHP, it is the DOT) if you are thinking of $ symbols as variable names.
$insert = "INSERT INTO person (ID_No, P_Word, E_Status) " .
" VALUES( " .
"'" . $userName . "'" . " , " .
"'" . $userPass. "'" . " , " .
"'" . "Applicant. "'" . " ) " ;
$result = mysql_query($insert);

PHP - for statement in a string

I have a MySQL statement that I want to execute and inside this statement I would like to include a for loop to define the columns that data will be entered into etc.
The code I currently have is
$stmt = $conn->prepare('INSERT into DATA ('.
for($i = 0; $i < count($columns); $i++) {
echo $columns[$i];
}
.') VALUES ('.
for($i = 0; $i < count($columns); $i++) {
echo ':'.$columns[$i].' , ';
}
.')');
Obviously this doesn't work but if it was to work also in the second for statement it echos a comma at the end of each loop, which will cause an error for the last loop so also is there a way to fix this to?
Thanks in advance!
Use the join/implode function:
$params = array_map(function($var){return ':'.$var;}, $columns);
$sql = 'INSERT into DATA ('.join(',', $columns).') VALUES ('.join(',', $params).')';
$stmt = $conn->prepare($sql);
Another approach using implode:
$sql = "INSERT into DATA (`" . implode('`,`', $columns) . "`) values (:" . implode(',:', $columns) . ")"
$stmt = $conn->prepare($sql);
Example result:
// Input array
$columns = array('A', 'B', 'C');
// Output
INSERT into DATA(`A`,`B`,`C`) values (:A,:B,:C)
You should create the query outside of the prepare() function to make it easier.
Something like that would be better/clearer :
$count = count ($columns); // Avoid using count in your loop init (Performances)
$query = 'INSERT INTO DATA (' .
for($i = 0; $i < $count; $i++) {
$query .= $columns[$i];
}
$query .= ') VALUES (';
for($i = 0; $i < $count; $i++) {
if ($i != $count - 1) $query.= ':'.$columns[$i].' , ';
else $query .= ':'.$columns[$i]; // No coma for the last value
}
$query .= ')';
$stmt = $conn->prepare($query);

array data to mysql

I need to parse the following code and process the resulting data.
foreach($job as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
The above code is returning the following as expected.
Key=vca_id, Value=20130<br>Key=uuid, Value=3c87e0b3-cfa<br>Key=originate_time, Value=2013-03-15 14:30:18<br>
What I need to do is to put the values in mysql database. So the insert statement would look something like this...
insert into test.master_table (vca_id, uuid, originate_time) values ('20130', '3c87e0b3-cfa', '2013-03-15 14:30:18')
What is the correct way to save the array values to mysql database?
<?php
mysql_query("insert into test.master_table(vca_id, uuid, originate_time)values('".$job['vca_id']."','".$job['uuid']."','".$job['originate_time']."')");
?>
Well i will recommend implode
$keys = array();
$values = array();
foreach($job as $x => $x_value)
{
$keys[] = $x;
$values[] = $x_value;
}
$query = 'INSERT INTO test.master_table' . '('.implode(',',$keys) .') VALUES (' .implode(',',$values) . ')';
You can try this
$temp_value_arr = array();
$query = "INSERT into test.master_table SET ";
foreach($job as $x=>$x_value)
{
$query .= "$x = '$x_value',";
}
$query = rtrim($query, ',');
mysql_query($query);

Categories