PHP - How Do I Insert Into My Db A Post Array ?
Hi - I have an HTML form which is dynamically produced using CodeIgniter / PHP and presents products a customer has ordered. When the customer has finished changing his quantities they must now submit the form. My problem is that my form will contain many of the same named fields for example, 'Product ID', or 'Product Name' or 'quantity'. So now when it gets processed a typical post array like product id could look like this:
Code: [Select] Array ( [0] => 28 [1] => 24 [2] => 101 [3] => 23 [4] => 17 ) Of course I get an error: Quote Severity: Notice Message: Array to string conversion Filename: mysql/mysql_driver.php I really need some advice on how I should pre-process the various POST arrays so I can get them into my DB. A very grateful student of PHP ! Thanks Similar TutorialsWhen i click my submit button i am posting the following. Array ( [submitStaffOrder] => [staffMember] => Array ( [0] => 2 [1] => ANYCHEF1 ) [date] => Array ( [0] => 2020-02-18 [1] => 2020-02-18 ) [startTime] => Array ( [0] => 11:01 [1] => 10:10 ) [finishTime] => Array ( [0] => 11:01 [1] => 10:01 ) [delExisting] => Array ( [0] => [1] => toDel ) ) I would like to update/insert if delExisting is blank and delete if it has toDel in there. I have the following but i am pretty sure the if is not working. $date = $_POST['date']; $stime = $_POST['startTime']; $ftime = $_POST['finishTime']; $del = $_POST['delExisting']; $staff = $_POST['staffMember']; $stmt = $conn -> prepare(" INSERT IGNORE INTO ssm_staff_order (job_id, staff_id, staff_start_time, staff_finish_time, staff_start_date, staff_finish_date) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE staff_start_time = VALUES(staff_start_time), staff_finish_time = VALUES(staff_finish_time); "); $delstmt = $conn -> prepare(" DELETE FROM ssm_staff_order WHERE staff_id = ? AND job_id = ? AND staff_start_date = ? "); foreach ($staff as $key => $staffId) { if ($del == '') { $start = $date[$key].' '.$stime[$key]; $finish = $date[$key].' '.$ftime[$key]; $stmt -> bind_param('isssss', $jid, $staffId, $start, $finish, $date[$key], $date[$key]); $stmt -> execute(); } if ($del == 'toDel') { $delstmt -> bind_param('sis', $staffId, $jid, $date[$key]); $delstmt -> execute(); } } } Can i do what i am trying to do or am i way off here?
I struggle with arrays Edited February 24, 2020 by Adamhumbug$post='{"cart_items":[{"configuration":{"price":100,"recharge_number":"9999999999"},"product_id":"999","qty":1}]}';i try this n reslut was :There are no valid items in cart: help me plz Edited by ShivaGupta, 30 November 2014 - 01:11 AM. when i remove the action from the form it submits the post correctly if not it goes to the action url withoutposting Code: [Select] <form action="https://www.sandbox.paypal.com/cgi-bin/webscr" target="_top" method="post"> <input type="hidden" name="cmd" value="_s-xclick"> <input type="hidden" name="hosted_button_id" value="wwww"> <?php <input type="hidden" name="item_name" id="item_name" value="<?php echo $md5c;?>"> <input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_paynowCC_LG.gif" border="0" name="submit" alt="Submit Form"> <img alt="" border="0" src="https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1"> </form> <?php if(isset($_POST['submit_x']) || isset($_POST['submit_x'])) { //$Subscription_id = mysql_real_escape_string($md5c); $PropertyID = mysql_real_escape_string($rowData['ID']); $User_ID = mysql_real_escape_string($rowData['User_ID']); $item_name=mysql_real_escape_string($_POST['item_name']); //$query = 'INSERT INTO SP_subscriptions(id,) values("'.$item_name.'")'; $query = 'INSERT INTO SP_subscriptions(id,PropertyID,User_ID) values("'.$item_name.'","'.$PropertyID.'","'.$User_ID.'")'; $success = mysql_query($query); echo $query; } else echo 'POST nada'; var_dump($_POST); var_dump($query); ?> Ok .I tried to look for the problem for about 1 hour but I can't see what's wrong whit the following code: In firebug the post values appear correctly like so:id=116&usern=asdawe&com=qweqw&page=116&submit=submit and the inserc() function works correctly because i tried it whit a array of data created by my; Code: [Select] <?php if(isset($_POST['submit'])) { $comment = new comment; $comment->storeform($_POST); $comment->insertc(); } ?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"> <input type="hidden" name="id" value="<?php echo $result['article']->id ?>"/> <ul> <li> <input type="text" name="usern" id="usern" /> </li> <li> <textarea name="com" id="com" COLS=40 ROWS=6></textarea> </li> <input type="hidden" name="page" value="<?php echo $result['article']->id ?>" /> <input type="submit" name="submit" value="submit" /> </ul> </form> Code: [Select] <?php class comment{ public $id = null; public $usern = null; public $com = null; public $page = null; public function __construct($data=array() ) { if( isset($data['id']) ) $this->id= (int)$data['id']; if( isset($data['usern']) ) $this->usern= preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['usern'] ); if( isset($data['com']) ) $this->com= preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['com'] ); if( isset($data['page']) ) $this->page= (int)$data['page']; } public function storeform ( $params ) { // Store all the parameters $this->__construct( $params ); } public function insertc() { $con = new PDO(DBN,DB_USER,DB_PASS); $sql = "INSERT INTO comments (usern,com,page) VALUES (:usern,:com,:page)"; $st =$con->prepare($sql); $st->bindValue( ":usern", $this->usern, PDO::PARAM_STR ); $st->bindValue( ":com", $this->com, PDO::PARAM_STR ); $st->bindValue( ":page", $this->page, PDO::PARAM_INT ); $st->execute(); $this->id = $con->lastInsertId(); $con = null; } } ?> hi ..
hit little snag Ive got html <form name="formx" method="POST" action="connect.php" class='ajaxform'> and about 4 varibles in that form .. now how to properly
query table users so i can find out which prefix correspond with that user
Insert into table "upis" in this case that prefix with 3 variables..
everything in single,.. in this case connect.php file
I know how to do QUERY and INSERT INTO but i don't know how to connect with 2 different tbl or db and do the query and input of data.. every time I put 2 of them together .. never works out..
this is example.. i dont know is this right way to do it .. I want to remove the HTTP:// or HTTPS:// from the insert into the DB. The Viewer may put just www, or copy the entire URL with the HTTP:// or HTTPS://
I tried using the preg-replace but couldn't seem to get it to work.
Any other recommendation?
Thanks in advance,
Mike
I need a help in the following : I have an admin page from where the admin attaches an gif image.This attached image should be shown to the user as a scrolling image. The code for the scrolling image is done through javascript. So my actual problem is getting the name of the attached gif image to the javascript array which is used for scrolling horizontally. Hi Folks,
Firstly I am new, I have read several topics here and learned a lot, I would class myself as 'slightly better than basic', but my knowledge is mostly gained from reading code.
I am making a simple POST form for work, the data gets inserted into MySQL, nice and easy, I can make it work if I write out the statement completely, BUT I need to make a new form, it will have HUNDREDS of input fields, I really don't want to write the code, and I figured programmatically is a good way to go anyway as forms change and new forms may be required, so I set about building a function to completely handle my post data, bind it to a statement and insert it into a table, I have scrapped it a half dozen times already because something fundamentally doesn't work, but I am very close! The function can write the statement, but I need to bind the POST values before I can insert, something going wrong here and I would appreciate some help, I have a feeling it's a problem with an array, but anyway I will show you what I have, give you some comments as to my reasoning, and hopefully you can help me with the last bit
public function getColumnNames($table){ $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table"; try { $stmt = $this->dbh->prepare($sql); $stmt->bindValue(':table', $table, PDO::PARAM_STR); $stmt->execute(); $output = array(); while($row = $stmt->fetch(PDO::FETCH_ASSOC)){ $output[] = $row['COLUMN_NAME']; } $all = array($output); $a1 = array_slice($output, 1); // I don't want column 1, it contains the ID, its auto incremented. $a2 = array_slice($a1, 0, -3); // I don't want the last 3 columns as they have default values $selected = array($a2); // contains all the columns except those excluded by array_slice, columns now match all of the input fields on the form foreach ($selected as $row){ $fields = "`" . implode('`, `', $row) . "`"; // I'm making `fields` here, $bind = ":" . implode(', :', $row); // And making :values here } return array ( "raw" => $all, "fields" => $fields, "bind" => $bind ); } catch(PDOException $pe) { trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR); } } public function addRecord(){ $col = array(); $col = $this->getColumnNames("table"); $raw = array($col['raw']); $fields = array($col['fields']); $bind = array($col['bind']); $columnList = implode('`, `', $fields); $paramList = implode(', ', $bind); $sql = "INSERT INTO `{$this->dbtable}` ($columnList) VALUES ($paramList)"; return $sql; // this returns something like: INSERT INTO `table` (`field1`, `field2`, `field3`) VALUES (:field1, :field2, :field3)";perfect I thought, now I just need to bind the values from $_POST... then I get stuck. Edited by luke3, 08 January 2015 - 12:10 PM. I have an array $array_1 Code: [Select] ARRAY( [0] => info 1 [1] => info 2 [2] => info 3 ) and I have another array $array_2 Code: [Select] ARRAY( [0] =>thank you and welcome to what ever [1] =>the info you added * thanks for entering your info ) I want to loop though the first array and place the values into the [1] of the second array. But the tricky thing is I want it to insert were the * is. Code: [Select] foreach ($array_1 as $key => $val) { //not sure about this insert into ($array_2[1],after *, $val); } any help would be awesome. Hi all, Can anyone tell me why the declaration below won't work??? Thnx Ryflex $amount = array(0 => $_POST['$n[0]'], 1 => $_POST['$n[1]'], 2 => $_POST['$n[2]'], 3 => $_POST['$n[3]']); I have a dynamic form that I am writing a script for to allow people to modify the fields of the form. I am taking all of the information that they have entered into the post array. Where I am having a problem is that it is not showing all of the fields in the post array. One of the fields is an image field and the name of the image does not show up in the array when I do print_r or anything. One other thing that I would like to know is how to get rid of the submit key and value from the array. I have tried using the unset method but it still shows up in the array. Code: [Select] <?php session_start(); include ('includes/connection.php'); connect(); $table = $_GET['table']; $id = $_GET['id']; $errors = array(); $mod_sql = "SELECT * FROM $table WHERE id = '$id'"; $mod_sql_result = mysql_query($mod_sql); $info = mysql_fetch_assoc($mod_sql_result); $mod_form = "<form name='insert_table' id='insert_table' action='" . $_SERVER['PHP_SELF'] . "?id=$id&table=$table' method='post' enctype='multipart/form-data'> <fieldset> <legend>table information</legend> <input TYPE='hidden' VALUE='" . $table . "' />"; foreach ($info as $key => $val) { $header = str_replace("_", " ", $key); if ($key == 'id') { $mod_form .= "<p>" . $header . ": <input name='" . $key . "' id='" . $key . "' type='text' value='" . $val . "' readonly='readonly' /></p>"; } else if ($key == 'image') { $mod_form .= "<p>Current image: <img style='vertical-align: text-top;' src='../db_images/ad_images/" . $val . "' /><input type='checkbox' name='delete_image' id='delete_image' value='" . $val . "' />Delete this image?</p> <p>" . $header . ": <input name='" . $key . "' id='" . $key . "' type='file' /></p>"; } else { $mod_form .= "<p>" . $header . ": <input name='" . $key . "' id='" . $key . "' type='text' value='" . $val . "' /></p>"; } } $mod_form .= " <p> <input type='submit' name='submit_mod' id='submit_mod' /> </p> </fieldset> </form> "; echo $mod_form; if (isset($_POST['submit_mod'])) { $table = $_POST['table']; $allowed_ext = array('jpg', 'jpeg', 'png', 'gif'); $file_name = $_FILES['image']['name']; $file_ext = (explode(".", $file_name)); $file_ext = strtolower(end($file_ext)); $file_size = $_FILES['image']['size']; $file_tmp = $_FILES['image']['tmp_name']; if (isset($_POST['delete_image'])) { $delete_image_name = $_POST['delete_image']; unlink('../db_images/ad_images/' . $delete_image_name); } if ($file_name != " ") { $new_image = $file_name; move_uploaded_file($file_tmp, '../db_images/ad_images/' . $file_name); } // This is the section of code that I am having trouble with foreach ($_POST as $key => $value) { if ($key == 'image') { $value = $new_image; } $insert_query = "UPDATE $table SET `$key` = '$value' WHERE id = $id"; $insert_action = mysql_query($insert_query); } echo $insert_query; } if (mysql_error()) { $error = "<strong>MySQL error</strong>:<br />" . mysql_errno() . ": " . mysql_error() . "\n<br>When executing:<br>\n$insert_query\n<br>"; $page = $_SERVER["REQUEST_URI"]; $log = "INSERT INTO db_error (`error_id`, `error_page`,`error_text`,`query`) VALUES ('','$page','" . mysql_real_escape_string($error) . "','" . mysql_real_escape_string($mod_sql) . "')"; $insert_log = mysql_query($log); echo $error; if ($insert_log) { echo "<p>Error has been added to the error log</p><p>The error id number is " . mysql_insert_id() . ""; } else { echo "Error adding to error log<br />" . mysql_errno() . ": " . mysql_error(); } } ?> I seem to be having a problem with this code. It's supposed to parse the file info.txt and explode comma separated values into an array and then add each value from that file to the end of a URL and POST that url. What I'm getting now is just the first number in the array. Anyway, here's the code: Code: [Select] <?php $FileName = "info.txt"; $FileHandle = fopen($FileName,"r"); $FileContent = fread ($FileHandle,filesize ($FileName)); fclose($FileHandle); // You can replace the \t with whichever delimiting character you are using $SplitContent = explode("\t", $FileContent); foreach($SplitContent as $CurrValue) { header('Location: http://website.com/file.php?value=' . $CurrValue); } ?> Hi people I am new to php and I need your help.
I am usig libchart and want to make the bars colored based on value:
Original code:
$this->setBarColor(array( new Color(42, 71, 1), )); I want to make something like this: $this->setBarColor(array( if ( ( condition1 )) new Color(42, 171, 1), if ( ( condition2 )) new Color(42, 71, 1), if ( ( condition3 )) new Color(42, 71, 211), )); I do not know php syntax yet, so how can I do this? Thank you, Alex All of my form POST data (from multiple forms) is managed through a file called formdata.php. Formdata.php and check_input() performs trim/stripslashes/htmlspecialchars etc on the posted variables. (it also indirectly calls relevant database functions such as insert or select). What is the correct way to add all of the variables to an array so that I can so that I can pass the array(ofvariables) to a function. ie the checked variables (only a few of them): Code: [Select] $subject = check_input($_POST['subject']); $repphone = check_input($_POST['repphone']); $repfirstname = check_input($_POST['repfirstname']); $replastname = check_input($_POST['replastname']); $streetnum = check_input($_POST['streetnum']); $streetname = check_input($_POST['streetname']); $suburb = check_input($_POST['suburb']); $postcode = check_input($_POST['postcode']); there will be many subjects and many more variables so instead of listing the variables such as: Code: [Select] function post_to_table(){ // variables global $subject;, $streetnum, $streetname, $suburb, $postcode; global $repphone, $repfirstname, $replastname; if ($subject === "specifiedsubject"){ post_to_appropriate_table($streetnum, $streetname, $suburb, $postcode, $repphone, $repfirstname, $replastname); } I would rather use an array instead of passing each variable individually: Code: [Select] function post_to_appropriate_table ($streetnum, $streetname, $suburb, $postcode $repphone, $repfirstname, $replastname) { global $database; $sql = "INSERT INTO incident ("; $sql .= "streetnum, "; $sql .= "streetname, "; $sql .= "suburb, "; $sql .= "postcode, "; $sql .= "repphone, "; $sql .= "repfirstname, "; $sql .= "replastname"; $sql .= ") "; $sql .= "VALUES ("; $sql .= "'{$streetnum}', "; $sql .= "'{$streetname}', "; $sql .= "'{$suburb}', "; $sql .= "'{$postcode}', "; $sql .= "'{$repfirstname}', "; $sql .= "'{$replastname}'"; $sql .= ") "; // echo $sql; //for debugging if required; return $database->query($sql); } how can I ditch the ever growing list of variables and use an array? Thanks. I have worked on a while loop as a radio and this dispalys well and Now I am trying to post this to the next page. But kind of stuck. This is my while loop for the form Code: [Select] $intNum = 1; $intnumber = 1; while( $info = mysql_fetch_array( $sqll )){ echo "<input type='hidden' name=\"Que_ID\" value=\"{$info['Que_ID']}\" /> "; echo " $intNum, {$info['Que_Question']} <br />\n"; $intNum++; for ($i =1; $i < 5; $i++) { echo "<input type=\"Radio\" name=\"choice[{$intnumber}]\" />{$info['Que_Choice'.$i]}<br />\n"; $intnumber++; } } ?> <input type="submit" name="submit" value="submit"/> </form> </body> </html> Now in order for me to post this to the next page, can I do something like Code: [Select] if (isset($_POST['Submit1'])) { $qu=$_POST[Que_ID]; $choi=$_POST[choice]; for($i=1; $1=5; i++) echo $qu. $choi; this is just my guess. I want the que_ID to display four choice for each question ID. so it would be Question ID=2(choice1=selected, choice2=notselected, choice3=not selected, chocie4=not selected) and this would be repeated to the next question ID. So far I can notice that my chociename are added by one(choice1, choice2,choice3,choice4,choice5,choice6,choice7,choice8,choice8......) so my post for loop will not work work as my choices goes up to more then 5. Hi all This is probably the easiest question ever , but I am not familiar with arrays , so hope somebody can help me User post this checkbox form (array): <input type="checkbox" name="type[0][]" value="1" > <input type="checkbox" name="type[0][]" value="2" > <input type="checkbox" name="type[0][]" value="3" > I need to get all checked values and print them ... How can I do this? I tried the code below, but it only returns me one value Code: [Select] $values = array($_POST["type"]); foreach ($values as $item){ echo $item; } Any help??? Thanks!! I have a form that is producing the following : Array ( [formID] => 3154008308 [q1_applicationDate] => Array ( [month] => 11 [day] => 15 [year] => 2010 ) [q4_fullName4] => Array ( [first] => TOM [last] => STONE ) [q5_email] => TSTONE@YAHOO.COM [q6_address6] => Array ( [addr_line1] => 325 E LINCOLN [addr_line2] => [city] => GENESEE [state] => NY [postal] => 33256 [country] => United States ) [q38_selectProvider38] => Sprint [q39_selectPlan] => Individual [website] => [simple_spc] => 3154008308-3154008308 ) HOW do I automatically get each item above into it's own PHP variable? The page that receives this Array is the second page of a 3 or 4 page form. I need to send the above information on through the remainder of the form?? Would appreciate any help! Thanks! Hello! Hi - I am uploading Post variables off a form relating to products and customer orders. If a product has a quantity attached to it then all the POST variables relating to that product need to INSERTED into the DB. If a product has just an empty string in it's quantity variable, then that product does not get INSERTED. So I thought of 2 different approaches: A) I could filter the Quantity Post variable for a positive values then create a new array only containing products with positive quantities. B) I could loop through the product Id (ProdID) POST and using a condition pull out the products with a positive quantity for Insertion. I have been experimenting with B and have failed miserably. However I have succeeded excellently in building some code which INSERTS all the products regardless of their quantities ( see below ) - not ideal as it enters products with empty quantities. I would prefer to adapt what I have rather than throw it away. Can someone kind person give this student a hand with some advice in adapting what I have got ? MANY MANY THANKS ! Code: [Select] <?php function insert_tel_order(){ $lastname = $_POST['lastname']; $orderid = strtoupper(substr($lastname,0,3)).(substr(time(),-4)); //Creates a unique order number $customerid = $_POST['customerid']; $pickupdate = $_POST['pickupdate']; $deliverylocationid = $_POST['deliverylocationid']; $orderdate = $_POST['orderdate']; foreach ($_POST['prodid'] as $arrkey => $prodid){ $quantity = $_POST['quantity'][$arrkey]; $prodid = $_POST['prodid'][$arrkey]; $price = $_POST['price'][$arrkey]; $ordervalue = $quantity * $price; $sql =" INSERT INTO `order` (id, orderid,orderdate,customerid, deliverylocationid,pickupdate,prodid,price, quantity, ordervalue, status) VALUES ('', '$orderid',$orderdate,$customerid,$deliverylocationid,$pickupdate,$prodid,$price,$quantity,$ordervalue,'')"; $this->db->query($sql); } } ?> $space = array('3x3', '3x3_6x6', '3x3_6x6', '6x6_10x10', '10x10_20x20', '20x20_40x40', 'above_40x40'); |