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!
Related
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 am trying to be lazy (or smart): I have 7 checkboxes which correlate with 7 columns in a MySQL table.
The checkboxes are posted in an array:
$can = $_POST['can'];
I've created the following loop to dump the variables for the MySQL insert:
for($i=1;$i<8;$i++){
if($can[$i] == "on"){
${"jto_can".$i} = 'Y';
}
else{
${"jto_can".$i} = 'N';
}
}
print_r($jto_can1.$jto_can2.$jto_can3.$jto_can4.$jto_can5.$jto_can6.$jto_can7);
This correctly outputs:
YYNYYYY
However, when I attempt to use those variables in my MySQL update, it doesn't accept the changes.
mysqli_query($db, "UPDATE jto SET jto_can1 = '$jto_can1', jto_can2 = '$jto_can2', jto_can3 = '$jto_can3', jto_can4 = '$jto_can4', jto_can5 = '$jto_can5', jto_can6 = '$jto_can6', jto_can7 = '$jto_can7' WHERE jto_id = '$id'")or die(mysqli_error($db));
Can anyone explain why the print_r displays the variables whereas MySQL update does not?
Stick with the array, and form the query dynamically:
$sql = 'UPDATE jto SET ';
$cols = array();
foreach( range( 1, 7) as $i) {
$value = $_POST['can'][$i] == 'on' ? 'Y' : 'N'; // Error check here, $_POST['can'] might not exist or be an array
$cols[] = 'jto_can' . $i . ' = "' . $value . '"';
}
$sql .= implode( ', ', $cols) . ' WHERE jto_id = "' . $id . '"';
Now do a var_dump( $sql); to see your new SQL statement.
this is not a mysql problem. mysql will only see what you put into that string. e.g. dump out the query string BEFORE you do mysql_query. I'm guessing you're doing this query somewhere else and have run into scoping problems. And yes, this is lazy. No it's not "smart". you're just making MORE work for yourself. What's wrong with doing
INSERT ... VALUES jto_can1=$can[0], jto_can2=$can[1], etc...
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();
}
}
i need some help with inserting multiple rows from different arrays into my database.
I am making the database for a seating plan, for each seating block there is 5 rows (A-E) with each row having 15 seats.
my DB rows are seat_id, seat_block, seat_row, seat_number, therefore i need to add 15 seat_numbers for each seat_row and 5 seat_rows for each seat_block.
I mocked it up with some foreach loops but need some help turning it into an (hopefully single) SQL statement.
$blocks = array("A","B","C","D");
$seat_rows = array("A","B","C","D","E");
$seat_nums = array("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15");
foreach($blocks as $block){
echo "<br><br>";
echo "Block: " . $block . " - ";
foreach($seat_rows as $rows){
echo "Row: " . $rows . ", ";
foreach($seat_nums as $seats){
echo "seat:" . $seats . " ";
}
}
}
Maybe there's a better way of doing it instead of using arrays?
i just want to avoid writing an SQL statement that is over 100 lines long ;)
(im using codeigniter too if anyone knows of a CI specific way of doing it but im not too bothered about that)
try
<?php
$blocks = array("A","B","C","D");
$seat_rows = array("A","B","C","D","E");
$seat_nums = array("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15");
foreach($blocks as $block){
foreach($seat_rows as $rows){
foreach($seat_nums as $seats){
$querys[] = "('" . $block "','" . $rows . "', '" . $seats . "' )";
}
}
}
$query_inserts = join ( ", ", $querys );
$query = "
INSERT INTO
table
( block, rows, seats )
VALUES
" . $query_inserts . "
";
mysql_query ($query);
?>
One solution is to use prepared statements:
$pdo = new PDO('mysql:dbname=mydb', 'myuser', 'mypass');
$stmt = $pdo->prepare('INSERT INTO seats
(seat_id, seat_block, seat_row, seat_number)
VALUES (?,?,?,?);
');
foreach (...) {
$stmt->execute(array($seat_id, $seat_block, $seat_row, $seat_number));
}
I have been given the task of devising a custom forms manager that has a mysql backend.
The problem I have now encountered after setting up all the front end, is how to process a form that is dynamic.
For E.G
Form one could contain 6 fields all with different name attributes in the input tag.
Form two could contain 20 fields all with different name attributes in the input tag.
How would i process the forms without using up oodles of resource.
Final Answer
Based on Accepted answer by Arda Xi
function processForm($form_id) {
$rows = "";
$values = "";
foreach($_POST as $key => $value) {
$rows = mysql_real_escape_string($key);
$values = mysql_real_escape_string($value);
$entry .= "[".$rows . "::".$values."]";
}
// clean up the array
$entry = preg_replace('/^\[|\d+|\:\:\]/', '', $entry);
$query = mysql_query("INSERT INTO `forms_form_data` (`id`, `form_id`, `entry`, `manager_id`, `status`, `created_at`) VALUES (NULL, '".$form_id."', '".$entry."', '".$_SESSION['manager_id']."', '0', NOW())");
}
Literally the only way would be using a loop. If you want to use as little resources as possible, you can concatenate them.
$columns = "";
$values = "";
foreach($_POST as $key => $value) {
$columns .= "`" . mysql_real_escape_string($key) . "`, ";
$values .= "`" . mysql_real_escape_string($value) . "`, ";
}
$columns = substr($columns, 0, -2);
$values = substr($values, 0, -2);
$query = "INSERT INTO `table` (".$colums.") VALUES (".$values.")";
This will create one query for all the values in the form.
Why not store the serialized value of $_POST as is? Of course escaping it to make it database safe. Like:
$value=serialize($_POST);