So the problem is, when uploading to mysql the database is only uploading the last value in the array.
if (substr($avsnitt["serier"], 0, 16) === 'http://random'){
// Create DOM from URL or file
$html = file_get_html($avsnitt["serier"]);
$array_title = array();
$array_link = array();
foreach($html->find('div[class=entry]') as $element){
foreach ($element->find('a') as $text) {
$array_title[] = $text->plaintext;
}
foreach ($element->find('a') as $test) {
$array_link[] = $test->href;
}
$count_name = count($array_title);
for($i=0; $i<$count_name; $i++){
$_array_title = mysql_escape_string($array_title[$i]);
$_array_link = mysql_escape_string($array_link [$i]);
print_r($_array_title);
print_r($_array_link);
$sql2 = "INSERT INTO episodes (name, ID, link) VALUES ('" . #$_array_title. "','" . #$avsnitt["ID"] . "', '" . #$_array_link . "');";
mysqli_query($CON, $sql2);
}
}
}
i'm new to php mysql so i dont relly know how arrays is uploaded to mysql, fast answers will be appreciated thanks.
I think, your database-field "link" is type string.
You want to insert your variable $_array_link, witch is type array.
So try serialize($_array_link) to "convert" array to string.
I think, the # are not nessessary, without it is better to read.
$sql2 = "INSERT INTO episodes (name, ID, link)
VALUES ('" . #$_array_title. "','" . #$avsnitt["ID"] . "', '" . serialize($_array_link). "');";
Later, you want to use the variable from the database. So after you SELECT your data, use unserialize() to get the array back.
problem was the database ID was primery key only allowing one withe a specific ID
I have a form which has multiple drop downs (16) speed[] and some other fields
The data from the dropdown boxes has to be inserted into a Mysql table
What I did is I took the count count($_POST["speed"]);and then loop through until the end of the speed array.
The problem is:
If Anyone of the dropdown is not selected it returns "-1", if used `($_POST["speed"][$i]!="-1")for that but it does not compare and goes into the IF loop
The Insert Query is not a valid not sure how to append the extra commas
$sql when printed
INSERT INTO mytablename (w_name,wtype,speed1,speed2, speed3, speed4, speed5, speed6, speed7, speed8, speed9, speed10, speed11, speed12, speed13, speed14, speed15, speed16, coach_id) VALUES ('name', '', ''-1''800''-1''-1''200''-1''-1''-1''-1''-1''-1''-1''-1''-1''-1''200'', '208')
My PHP code
$itemCount = count($_POST["speed"]);
$itemValues=0;
$query = "INSERT INTO mytablename (w_name,wtype,speed1,speed2, speed3, speed4, speed5, speed6, speed7, speed8, speed9, speed10, speed11, speed12, speed13, speed14, speed15, speed16, coach_id) VALUES ";
$bldSpltString="";
$queryValue = "";
for($i=0;$i<$itemCount;$i++) {
if(($_POST["speed"][$i]!="-1") || !empty($_POST["speed"][$i])) {
$bldSpltString .= "'" . $_POST["speed"][$i] ."'";
}
}
$queryValue .= "('" . $wkout . "', '" . $wtype . "', '" . $bldSpltString . "', '" .$_SESSION['id']."')";
$sql = $query.$queryValue;
echo $sql;
exit;
I would do something like this:
<?php
function dynamicInsert($table_name, $assoc_array){
$keys = array();
$values = array();
foreach($assoc_array as $key => $value){
$keys[] = $key;
$values[] = $value;
}
$query = "INSERT INTO `$table_name`(`".implode("`,`", $keys)."`) VALUES('".implode("','", $values)."')";
echo $query;
}
dynamicInsert("users", array(
"username" => "Test User",
"password" => "Password123"
));
?>
WARNING: This code is not secure, I would run a mysql_real_escape_string and any other necessary sanitation on the variables being sent to mysql. I would also steer clear of allowing this script to run on anything public facing as a dynamic insert could allow for huge security risks!
I have a problem in trying to store database values in their respective rows inside the database using dynamic form fields. I have provided here the screenshots of my codes and outputs.
This is my script in adding dynamic form fields in which the form is located in a separate file named load_work_experience_form.php
This is the html code for the form I have appended in the my script to add a dynamic form fields
This is the look of my dynamic form fields
This happens to be the wrong output inside the database in which data values do not store in their proper record. I am attempting to insert 2 records of work experience but it seems that it has created 4 records.
The source code for adding into the database is supplied below. Kindly help me in fixing this problem. Thanks. More power:
<!--ADD WORK EXPERIENCE TO DATABASE -->
<?php
require'../admin/php/db_connection.php';
if(isset($_POST['update_profile']))
{
if (isset($_POST['employer'])) {
foreach ( $_POST['employer'] as $value ) {
$values = mysql_real_escape_string($value);
$query = mysql_query("INSERT INTO tbl_work_exp (employer) VALUES ('$values')");
}}
if (isset($_POST['job_position'])) {
foreach ( $_POST['job_position'] as $value ) {
$values = mysql_real_escape_string($value);
$query = mysql_query("INSERT INTO tbl_work_exp (job_position) VALUES ('$values')");
}}
//some more codes here for Work From and To. This website does not accept alot of codes. But the codes here are just like the ones at the top.
}
?>
<!--ADD WORK EXPERIENCE TO DATABASE -->
In the case that you have every time the same fields with dynamic rows:
<!--ADD WORK EXPERIENCE TO DATABASE -->
<?php
require'../admin/php/db_connection.php';
if(isset($_POST['update_profile']))
{
if (isset($_POST['employer'])) {
for ($i = 0, $nCount = count($_POST['employer']); $i < $nCount; $i++) {
$employer = mysql_real_escape_string($_POST['employer'][$i]);
$job_position = mysql_real_escape_string($_POST['job_position'][$i]);
$query = mysql_query('INSERT INTO tbl_work_exp (´employer´, ´job_position´) VALUES (´' . $employer . '´, ´' . $job_position . '´)');
}
}
}
?>
<!--ADD WORK EXPERIENCE TO DATABASE -->
You must add there the other fields also...
The problem of your logic is that you do for every field a insert but you need only one insert for one row.
And please don't use mysql library in php, it is better to use mysqli
Your problem is that you pass each value separately. I strongly suggest to change your HTML markup to group each value, but that's not the goal here. As for your current problem, this is a quick solution that can help you through. Picking up from your current code:
<?php
if (isset($_POST['update_profile'])) {
$profileFields = array('employer', 'job_position');
$profiles = array();
foreach ($profileFields as $field)
{
if (isset($_POST[$field])) {
foreach ($_POST[$field] as $key => $value) {
if (!isset($profiles[$key])) {
$profiles[$key] = array();
}
$profiles[$key][$field] = mysql_real_escape_string($value);
}
}
}
foreach ($profiles as $profile) {
$tableCols = implode(",", array_keys($profile));
$profileValues = implode("','", array_values($profile));
$insertQuery = "INSERT INTO tbl_work_exp ({$tableCols}) VALUES ('{$profileValues}')";
}
}
?>
Give or take a few tweaks or special treatment for each field. This is very generic code just to give you a guide.
Hope this helps
<?php
if(isset($_POST['Button_name'])){
for($i=0; $i<count($_POST['employer_name']); $i++){
$query="INSERT INTO table_name(employer_name,employer_age) VALUES ('".$_POST['employer_name']."','".$_POST['employer_age']."')";
$result=mysql_query($query);}}
<?php
$count_post_value = $_POST['first_name'] //this is value of text box //
for($i=0; $i<$count_post_value; $i++)
{
if(trim($_POST["first_name"][$i] && $_POST["last_name"] && $_POST["remarks"]!= ''))
{
$sql = mysql_query("INSERT INTO Table_name(first_name,last_name) VALUES('".$_POST["first_name"][$i]."','".$_POST["last_name"][$i]."')");
if($sql)
{
echo "<script>alert('Inserted Successfully');</script>";
}
else
{
echo "<script>alert('ERROR');</script>";
}
}
}
?>
Ok, I asked a question last night and received a number of really great responses. Since that was my first time using StackOverflow I was really pleased.
I'm hoping you guys can help with a new one. Hopefully, down the road, I'll be able to repay the favor to some NEW newbies.
I have the following code in a php file:
$sql = "";
$now=date("Y-m-d h:i:s");
$updatedRecords = $json1->{'updatedRecords'};
foreach ($updatedRecords as $value){
$sql = "update `acea` set ".
"`ACEA_A1`='".$value->ACEA_A1 . "', ".
"`ACEA_A2`='".$value->ACEA_A2 . "', ".
"`ACEA_A3`='".$value->ACEA_A3 . "', ".
"`ACEA_A4`='".$value->ACEA_A4 . "', ".
"`ACEA_A5`='".$value->ACEA_A5 . "', ".
"`ACEA_B1`='".$value->ACEA_B1 . "', ".
"`ACEA_B2`='".$value->ACEA_B2 . "', ".
"`ACEA_B3`='".$value->ACEA_B3 . "', ".
"`ACEA_B4`='".$value->ACEA_B4 . "', ".
"`ACEA_B5`='".$value->ACEA_B5 . "', ".
"`ACEA_E1`='".$value->ACEA_E1 . "', ".
"`ACEA_E2`='".$value->ACEA_E2 . "', ".
"`ACEA_E3`='".$value->ACEA_E3 . "', ".
"`ACEA_E4`='".$value->ACEA_E4 . "', ".
"`ACEA_E5`='".$value->ACEA_E5 . "', ".
"`ACEA_E7`='".$value->ACEA_E7 . "' ".
"where `acea_id`=".$value->acea_id;
if(mysql_query($sql)==FALSE){
$errors .= mysql_error();
}
}
The "ACEA_XX" portions relate to columns in the "acea" database table (obviously), but the programmer set them statically. Unfortunately, these columns need to be added to periodically, with new columns being created related to the new ACEA specs that are introduced.
As a result, this code becomes outdated.
Without having to go in and update this code each time I add a new column, how can I redesign this code so that it updates itself dynamically to include the new columns? I've been trying all morning to make it work, and I can set it so that I can dynamically insert the actual column names into the update statement, but, I can't seem to dynamically grab the associated values dynamically (and I think my method for grabbing and inserting the column names is a little convoluted).
My actual database table columns are currently:
acea_id ACEA_A1 ACEA_A2 ACEA_A3 ACEA_A4 ACEA_A5 ACEA_B1 ACEA_B2 ACEA_B3 ACEA_B4 ACEA_B5 ACEA_E1 ACEA_E2 ACEA_E3 ACEA_E4 ACEA_E5 ACEA_E6 ACEA_E7 ACEA_E9 oil_data_id
The first and last columns will never change and will continue to be the first and last columns. Any new columns will be added somewhere in between, but not necessarily immediately preceding the "oil_data_id" column.
I've tried revising the code numerous ways in order to properly grab the values, but just can't make it work.
Anyone have a concise modification to the code to do what I want? It would be greatly appreciated.
Seems like Doug Kress' method spits some errors out so here is my shot:
$errors = array();
foreach($json1->updatedRecords as $record)
{
$fields = array();
foreach($record as $field => $value)
{
if(substr($field, 0, 5) === 'ACEA_')
{
$fields[] = $field.' = '.mysql_real_escape_string($value);
}
}
// Check if there are any fields set to be updated.
if(isset($fields[0]))
{
// I'm assuming $record->acea_id is an integer. If not,
// replace '%d' with '%s'.
$sql = "UPDATE `acea` SET %s WHERE `acea_id` = '%d';";
$sql = sprintf($sql, implode(',', $fields), $record->acea_id);
if(mysql_query($sql) === false)
{
$errors[] = mysql_error();
}
}
}
First, I would highly recommend making that into a separate table (turning the data 'sideways', if you will). Assuming that's not feasible:
$sql = "";
$updatedRecords = $json1->{'updatedRecords'};
foreach ($updatedRecords as $values){
$flist = array();
$params = array();
foreach ($values as $key => $value) {
if (preg_match('/^ACEA_[A-Z]+\d+$/', $key)) {
$flist[] = $key .'="%s"';
$params[] = mysql_real_escape_string($value);
}
}
$sql = "update `acea` set ". implode(', ', $flist) .
"WHERE `acea_id`='%s'";
$params[] = mysql_real_escape_string($value->acea_id);
$sql = sprintf($sql, $params);
if(mysql_query($sql)==FALSE){
$errors .= mysql_error();
}
}
EDIT:
Thank you so much for your answers, you really amaze me with so much wisdom :)
I am trying to relay on TuteC's code a bit changed, but can't figure how to make it work properly:
$valor = $_POST['valor'];
$post_vars = array('iphone3g1', 'iphone3g2', 'nome', 'iphone41', 'postal', 'apelido');
foreach($post_vars as $var) {
$$var = "'" . mysql_real_escape_string($_POST[$var]). "', ";
}
$sql = "INSERT INTO clientes (iphone3g1, iphone3g2, nome, iphone41, postal, apelido, valor) VALUES ($$var '$valor')";
$query= mysql_query($sql);
I know there's a bit of cheating on the code, i would need to use substring so the $$var wouldn't output a "," at the end where i need the values, instead i tried to insert a variable that is a value ($valor = $_POST['valor'];)
What is going wrong?
And for the others who tried to help me, thank you very much, i am learning so much with you here at stackoverflow.
I have a form with several field values, when trying to write a php file that reads those values it came out a mostruosity:
$codigounico= md5(uniqid(rand()));
$modelo=$_POST['selectName'];
$serial=$_POST['serial'];
$nif=$_POST['nif'];
$iphone3g1=$_POST['iphone3g1'];
$iphone3g2=$_POST['iphone3g2'];
$iphone3g3=$_POST['iphone3g3'];
$iphone3g4=$_POST['iphone3g4'];
$iphone3gs1=$_POST['iphone3gs1'];
$iphone3gs2=$_POST['iphone3gs2'];
$iphone3gs3=$_POST['iphone3gs3'];
$iphone3gs4=$_POST['iphone3gs4'];
$iphone41=$_POST['iphone41'];
$iphone42=$_POST['iphone42'];
$iphone43=$_POST['iphone43'];
$iphone44=$_POST['iphone44'];
$total=$_POST['total'];
$valor=$_POST['valor'];
$nome=$_POST['nome'];
$apelido=$_POST['apelido'];
$postal=$_POST['postal'];
$morada=$_POST['morada'];
$notas=$_POST['notas'];
$sql="INSERT INTO clientes (postal, morada, nome, apelido, name, serial, iphone3g1, iphone3g2, iphone3g3, iphone3g4, total, valor, iphone3gs1, iphone3gs2, iphone3gs3, iphone3gs4, iphone41, iphone42, iphone43, iphone44, nif, codigounico, Notas)VALUES('$postal', '$morada', '$nome', '$apelido', '$modelo', '$serial', '$iphone3g1', '$iphone3g2', '$iphone3g3', '$iphone3g4', '$total', '$valor', '$iphone3gs1', '$iphone3gs2', '$iphone3gs3', '$iphone3gs4', '$iphone41', '$iphone42', '$iphone43', '$iphone44', '$nif', '$codigounico', '$notas')";
$result=mysql_query($sql);
This is a very dificult code to maintain,
can I make my life easier?
To restrict which POST variables you "import", you can do something like:
$post_vars = array('iphone3g1', 'iphone3g2', '...');
foreach($post_vars as $var) {
$$var = mysql_real_escape_string($_POST[$var]);
}
EDIT: Changed addslashes by mysql_real_escape_string (thanks #Czechnology).
The issue I see is repetition of the same names four times over. This is how I would reduce it to two occurrences (you could drop it to one with more finagling).
$sql = 'INSERT INTO clientes (postal, morada, nome, apelido, name, serial, iphone3g1, iphone3g2, iphone3g3, iphone3g4, total, valor, iphone3gs1, iphone3gs2, iphone3gs3, iphone3gs4, iphone41, iphone42, iphone43, iphone44, nif, codigounico, Notas) VALUES(:postal, :morada, :nome, :apelido, :modelo, :serial, :iphone3g1, :iphone3g2, :iphone3g3, :iphone3g4, :total, :valor, :iphone3gs1, :iphone3gs2, :iphone3gs3, :iphone3gs4, :iphone41, :iphone42, :iphone43, :iphone44, :nif, :codigounico, :notas)';
preg_match_all('/:(\w+)/', $sql, $inputKeys);
$tokens = $inputKeys[0];
$values = array_map($inputKeys[1], function($k){
return mysql_real_escape_string($_POST[$k]);
});
$sql = str_replace($tokens, $values, $sql);
$result = mysql_query($sql);
Depending on how you want to separate your logic, a reversed approach might be more useful, where you would specify the array of key names and iterate over that to generate the SQL string.
<?php
$inputKeys = array('postal', 'morada', 'nome', 'apelido', 'name', 'serial', 'iphone3g1', 'iphone3g2', 'iphone3g3', 'iphone3g4', 'total', 'valor', 'iphone3gs1', 'iphone3gs2', 'iphone3gs3', 'iphone3gs4', 'iphone41', 'iphone42', 'iphone43', 'iphone44', 'nif', 'codigounico', 'Notas');
$keyList = '(' . implode(',', $inputKeys) . ')';
$valueList = 'VALUES (';
foreach ($inputKeys as $k) {
$valueList .= mysql_real_escape_string($_POST[$k]);
$valueList .= ',';
}
$valueList = rtrim($valueList, ',');
$valueList .= ')';
$sql = 'INSERT INTO clientes '.$keyList.' '.$valueList;
$result = mysql_query($sql);
This approach drops the occurrences of the keys to one and will probably more naturally with your application.
TuteC had a good aim but failed in details.
It makes me wonder, why noone has a ready made solution, but had to devise it on-the-fly. Nobody faced the same problem before?
And why most people trying to solve only part of the problem, getting variables only.
The goal is not to get variables.
The goal is to get a query. So, get yourself a query.
//quite handy way to define an array, saves you from typing zillion quotes
$fields = explode(" ","postal morada nome apelido name serial iphone3g1 iphone3g2 iphone3g3 iphone3g4 total valor iphone3gs1 iphone3gs2 iphone3gs3 iphone3gs4 iphone41 iphone42 iphone43 iphone44 nif codigounico Notas");
$sql = "INSERT INTO clientes SET ";
foreach ($fields as $field) {
if (isset($_POST[$field])) {
$sql.= "`$field`='".mysql_real_escape_string($_POST[$field])."', ";
}
}
$sql = substr($set, 0, -2);
This code will create you a query without boring repeating the same field name many times.
But that's still not all improvements you can make.
A really neat thing is called a function.
function dbSet($fields) {
$set = '';
foreach ($fields as $field) {
if (isset($_POST[$field])) {
$set.="`$field`='".mysql_real_escape_string($_POST[$field])."', ";
}
}
return substr($set, 0, -2);
}
put this function into your code library being included into all your scripts (you have one, don't you?)
and then use it for both insert and update queries:
$_POST['codigounico'] = md5(uniqid(rand()));//a little hack to add custom field(s)
if ($action=="update") {
$id = intval($_POST['id']);
$sql = "UPDATE $table SET ".dbSet($fields)." WHERE id = $id";
}
if ($action=="insert") {
$sql = "INSERT $table SET ".dbSet($fields);
}
So, your code become extremely short and reliable and even reusable.
The only thing you have to change to handle another table is $fields array.
It seems your database is not well planned as it contains seemingly repetitive fields (iphone*). You have to normalize your database.
The same approach to use with prepared statements can be found in this my question: Insert/update helper function using PDO
You could use a rather ugly part of PHP called variable variables, but it is generally considered a poor coding practice. You could include your database escaping at the same time. The code would look something like:
foreach($_POST as $key => $value){
$$key = mysql_real_escape_string($value);
}
The variable variables manual section says they do not work with superglobals like $_PATH, but I think it may work in this case. I am not somewhere where I can test right now.
PHP: extract
Be careful though and make sure you clean the data before using it.
$set = array();
$keys = array('forename', 'surname', 'email');
foreach($keys as $val) {
$safe_value = mysqli_escape_string($db, $_POST[$val]);
array_push($set, "$val='$safe_value'");
}
$set_query = implode(',', $set);
Then make your MySQL query something like UPDATE table SET $set_query WHERE... or INSERT INTO table SET $set_query.
If you need to validate, trim, etc, do it before the above code like this:
$_POST["surname"] = trim($_POST["surname"];
Actually, you could make your life easier by making your code a bit more complicated - escape the input before inserting into the database!
$sql =
"INSERT INTO clientes SET
"postal = '" . mysql_real_escape_string($_POST['postal']) . "', ".
"morada = '" . mysql_real_escape_string($_POST['morada']) . "', ".
...
First, I recommend you to create a key-value array like this:
$newClient = array(
'codigounico' => md5(uniqid(rand())),
'postal' => $_POST['postal'],
'modelo' => $_POST['selectName'],
...
);
In this array key is the column name your MySQL table.
In the code you've provided not every field is copied right from POST array (some are calculated, and some keys of the POST aren't equal with the tables column names), so you should use a flexible method.
You should still specify all columns and values but only once so code is still maintainable and you won't have any security errors if someone sends you a broken POST. As for me it looks more like configuration than coding.
Then I recommend you to write a function similar to this:
function buildInsertQuery($tableName, $keyValue) {
$result = '';
if (!empty($keyValue)) {
$delimiter = ', ';
$columns = '';
$values = '';
foreach ($keyValue as $key => $value) {
$columns .= $key . $delimiter;
$values .= mysql_real_escape_string($value) . $delimiter;
}
$columns = substr($columns, 0, -length($delimiter));
$values = substr($values, 0, -length($delimiter));
$result = 'INSERT INTO `' . $tableName . '` (' . $columns . ') VALUES (' . $values . ')';
}
return $result;
}
And then you can simply build your query with just one function call:
$query = buildInsertQuery('clientes', $newClient);