PHP - Explode String Then Insert Into Database
Hello all, been trying for over a day to get something to work and after searching and searching I could not find what I was looking for. I found people looking to do something similar, but the answers seemed more complicated than I would think they need to be. First off, I'm still horrible at arrays and loops so try not to laugh too hard if my code is waaaayyyy off...haha
I am essentially trying to tie products and quantities to a reservation. The user has the ability to add items to the form. I'm using jquery .clone to create each new item product and quantity form fields. When the user submits the form jquery inputs the values of the cloned fields into 2 hidden text fields called "productsField" and "quantitiesField" The values of these fields look something like value="1,2,2,1,3" depending on how many products were added. What I want to do is explode both and then enter them into the database. Seems simple enough, but apparently I am not getting it. I thought something like this would work, but it is not. if (isset($_POST["reserve_button"])) { $theReservationID = $_SESSION['createdReservationID']; $items = explode (",",$_POST['productsField']); $quantities = explode (",",$_POST['quantitiesField']); // loop through array $number = count($items); for ($i=0; $i<=$number; $i++) { // store a single item number and quantity in local variables $itno = $items[$i]; $quant = $quantities[$i]; if ($items[$i] <> '') { mysql_query('INSERT INTO reservation_items (reservationID,productID,productQuantity) VALUES($theReservationID,$itno,$quant)'); } } } Any help would be greatly appreciated. Thanks in advance, Twitch Similar TutorialsHi everyone, I'm new to this group and new to php. I have created a multi-part form that allows the user the option to add multiple input fields to a form to upload images. Here is the form structu Code: [Select] <form action="Scripts/processreports2.php" method="post" enctype="multipart/form-data" name="report_form" target="uploader" class="reportfrm"> <fieldset> <legend>Upload your images</legend> <ol id="add_images"> <li> <input type="file" class="input" name="files[]" /> </li> <li> <input type="file" class="input" name="files[]" /> </li> <li> <input type="file" class="input" name="files[]" /> </li> </ol> <input type="button" name="addFile" id="addFile" value="Add Another Image" onclick="window.addFile(this);"/> </fieldset> <p>* indicates a required field.</p> <input name="submit" type="submit" id="submit" value="Send Info!" /> </form> Through php a maximum of three input fields are fed into an array that checks to make sure that the uploaded files are images and not some other type of file. The uploading porition of this script works. Now I am trying to get the values of the input fields as a string and insert them into the database as one record. Let's say the user has three files they want to upload. I have managed to get the files as a string ie; file1.jpg, file2.jpg, file3.jpg but what is happening is that I am getting three separate records with file1.jpg, file2.jpg, file3.jpg in them. If the user has only two files to upload then I get two separate records with file1.jpg and file2.jpg in them. (Hope that makes sense). I want one record. I have been struggling with this since Monnday and while every day I get closer, this is as close as I can get. Below is the php code. #connect to the database mysql_connect("localhost", "root", ""); mysql_select_db("masscic"); //Upload Handler to check image types function is_image($file) { $file_types = array('jpeg', 'gif', 'bmp'); //acceptable file types if ($img = getimagesize($file)){ //echo '<pre>'; //print_r($_FILES); used for testing //print_r($img); used for testing if(in_array(str_replace('image/', '', $img['mime']), $file_types)) return $img; } return false; } //form submission handling if(isset($_POST['submit'])) { //file variables $fname = $_FILES['files']['name']; $ftype = $_FILES['files']['type']; $fsize = $_FILES['files']['size']; $tname = $_FILES['files']['tmp_name']; $ferror = $_FILES['files']['error']; $newDir = '../uploads/'; //relative to where this script file resides for($i = 0; $i < count($fname); $i++) { //echo 'File name ' . $fname[$i] . ' has size ' . $fsize[$i]; used for testing if ($ferror[$i] =='UPLOAD ERR OK' || $ferror[$i] ==0) { if(is_image($tname[$i])) { //append the tmp_name($tname) to the file name ($fname) and upload to the server move_uploaded_file($tname[$i], ($newDir.time().$fname[$i])); echo '<li><span class="success">'.$fname[$i].' -- image has been accepted<br></span></li>'; }else echo '<li><span class="error">'.$fname[$i].' -- is not an accepted file type<br></span></li>'; } if (is_array($fname)) $files = implode(', ',$fname); //else $files = $fname; $sqlInsert = mysql_query("INSERT INTO files (file_names) VALUES('$files')") or die (mysql_error()); } } Hi all . In my scripts , there is a textarea that allow user to enter multiple phone number , message and date . If there are 3 phone numbers in textarea , how can I insert 3 of them into sql with the same data of message and date? Such as : phone number : 0102255888,0235544777,0896655444 message:hello all date:10/10/2011 and when it's insert into table , it will become: 1. 0102255888 | hello all | 10/10/2011 2. 0235544777 | hello all | 10/10/2011 3. 0896655444 | hello all | 10/10/2011 Here is the code I tried , but it will just save the last phone number . Code: [Select] $cellphonenumber = explode(',', $_POST['cellphonenumber']); $message = $_POST['inputtext']; $date = $_POST['datetime']; foreach($cellphonenumber as $value) { $sql="INSERT INTO esp( Recipient , Message , Date) VALUES ('$value','$message','$date')"; } mysql_query($sql) or die ("Error: ".mysql_error()); echo "Database updated."; Any hints or advices ? Thanks for every reply . Hi all, I am still learning all the variations of code commonly used with sites. I have one particular issue of which I am having trouble locating an answer or returning a proper result. I want to be able to use one page to query a distinct date, say 1-1-11 and the results return with the other columns matching this date and separating the time to be displayed for the entry row. So it would look something like this in the results. Acct: Tester User: John.Smith Time: 1:30 PM Currently there are 4 columns to the table, ID, Acct, Logintime, User. I have tried splitting this off the table but that fails out, unless someone knows an insert command to enter date and time individually. This would make it much easier for my purposes as well. Below is one of the many codes I have tried for this from examples. <?php $con = mysql_connect("localhost","gram","compassion"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("tester", $con); $result = mysql_query("SELECT * FROM test_history"); echo "<table border='1'> <tr> <th>Date:</th> <th>Time:</th> </tr>"; while($row = mysql_fetch_array($result)) (explode(" ",$row['logintime'])); echo $row[0]; echo $row[1]; { echo "<tr>"; echo "<td>" . $row[0] . "</td>"; echo "<td>" . $row[1] . "</td>"; echo "</tr>"; } echo "</table>"; mysql_close($con); ?> I know I am newb but I am a fast learner if I can merely get some points in the right direction. How I can explode by a series of characters (not one single character)? For example, divide the string to an array by any of these characters "," and ";" and "." $string = "this, that;some.word;second"; I want to put all of these words into an array. I have in ONE MySQL database row a string of ID's like this: Name of Row: Values: Post IDs 10 14 52 37 And now I want to fetch those ID's explode them (by the space) and then use them as an array, like this: $array[] = explode(" ", $query); echo $array[0]; // 10 echo $array[1]; // 14 echo $array[2]; // 52 Is this possible, if yes how can I do this? hey guys, I apologize, as this stuff should be easy to figure out, but I am getting stumped again being a php rookie. I have searched a lot for an answer before I bothered you all. Here's the skinny: I have a string coming in via post content that looks like: name1\x1ddata1\x1ename2\x1ddata2\x1e ... where the delimiters are 0x1e for the field/data pairs and 0x1d between the field/data . there may be as many as 20 of these pairs in the string. I have the string and I can store the pairs with explode in an array correctly, I just cant seem to get them all into one array. it would be even more helpful if the first element of the pairs were the array keys. Any guidance would be helpful. Thanks Code: [Select] $raw_post_data=file_get_contents("php://input"); $records=explode("\x1e",$raw_post_data,-1); foreach($records as $data){ $pairs=explode("\x1d",$data);} If I explode a string well using a substring when I implode that substring is now missing. for example. Code: [Select] $exploded = explode("[MAC]",$data); $data = implode($exploded); Now [MAC] would be missing in the $data string. any way to get around this? hello I want query from one table and insert in another table on another domain . each database on one domain name. for example http://www.site.com $con1 and http://www.site1.com $con. can anyone help me? my code is : <?php $dbuser1 = "insert in this database"; $dbpass1 = "insert in this database"; $dbhost1 = "localhost"; $dbname1 = "insert in this database"; // Connecting, selecting database $con1 = mysql_connect($dbhost1, $dbuser1, $dbpass1) or die('Could not connect: ' . mysql_error()); mysql_select_db($dbname1) or die('Could not select database'); $dbuser = "query from this database"; $dbpass = "query from this database"; $dbhost = "localhost"; $dbname = "query from this database"; // Connecting, selecting database $con = mysql_connect($dbhost, $dbuser, $dbpass) or die('Could not connect: ' . mysql_error()); mysql_select_db($dbname) or die('Could not select database'); //query from database $query = mysql_query("SELECT * FROM `second_content` WHERE CHANGED =0 limit 0,1"); while($row=mysql_fetch_array($query)){ $result=$row[0]; $text=$row[1]."</br>Size:(".$row[4].")"; $alias=$row[2]; $link = '<a target="_blank" href='.$row[3].'>Download</a>'; echo $result; } //insert into database mysql_query("SET NAMES 'utf8'", $con1); $query3= " INSERT INTO `jos_content` (`id`, `title`, `alias`, `) VALUES (NULL, '".$result."', '".$alias."', '')"; if (!mysql_query($query3,$con1)) { die('Error: text add' . mysql_error()); } mysql_close($con); mysql_close($con1); ?> Hi all, I'm having a hard time with strings... I am pulling data from an XML feed, and then trying to insert into my database. All the code is wrote, the problem is that some of the descriptions contain both ' and " so it is messing with my insert statement. I can get over the ' by doing this: \"$newstring\" however it then fails on " I have tried every function I can think of: str_replace, mysql_real_escape_string, htmlspecialchars, addslashes, stripslashes etc. etc. nothing seems to do the trick! I have attached the code in full, would someone be able to take a look and help me out? Any help would be greatly appreciated! many thanks Greens85 I am trying to add a value, input into a form, to a MySQL database. However, something must be wrong with the casting, because if there is a space in the form value, then I get an error, as in: //$_POST['string'] == '1blah 2blah'; sql = "INSERT INTO table (some_string) VALUES ($_POST[string])"; $sql_result = mysql_query($sql) or die ('The error is as follows: ' . mysql_error() . '<br /><br />Value could not be added.'); Then I get the following error: The error is as follows: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '2blah' at line 1 I've entered paragraphs into a database before, so this error is now to me. The column 'some_value' is a type: varchar(50). Hi everyone this time I want to do something everyone here knows it is possible: when posting a message at a forum you can press buttons and text appears at your pointer. Now that is not exactly what I want to do. at some forum sites (not phpfreaks) when pressing a button while posting you get a popup with buttons which make things appear in the not popup-window. that is exactly what I need to do. This is not about posting messages, btw, but a list of contacts of which you can select 2 in a popup. any ideas? any help is appreciated Hi,
I currently have some html stored in a variable as below:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> Hello world </body> </html>This requires a "<div class='container'>" to be inserted directly after the opening body tag. My original thinking was to use str_replace on the <body> to be <body><div class="container"> however note that occasionally my body will require an ID or Class. I therefore need a way to make it appear after the body tag, even if it has an ID or Class on it :-\ . I assume this may be reg-ex, but am not sure if there is a simple way around this? Would anyone be able to clarify and point me in the right direction. Much appreciated. MoFish Hi guys, I have a very simple add.php to add data to a mySQL db. I have a menu/list drop down as one of my fields on my form and this shows an array of results from another table (ranks of the RAF) within my db. When I click the save button I have it process a INSERT INTO command but all i get inputted into my staff table is the first word... eg if I chose "Pilot Officer" from the list menu and then click save all that would appear in my db is "Pilot". Any clues? I will paste the php below... Code: [Select] <?php include('config.php'); ?> <form action='' method='POST' enctype='multipart/form-data'> <p><b>Rank:</b><br /> <select name="rank" id="rank"> <option selected>Please Select</option> <?php $query = "SELECT * FROM ranks ORDER BY rank ASC"; $result = mysql_query($query); while($row = mysql_fetch_array($result)) { echo "<option value=". $row["rank"] .">". $row["rank"] ."</option>"; } ?> </select> <p><b>Forename:</b><br /> <input name="forename" type="text" id="forename" value="" size="40"> <p><b>Surname:</b><br /><input name='surname' type='text' id="surname" value='' size="40" /> <p><b>Category:</b><br /> <select name="category" id="category"> <option selected>Please Select</option> <?php $query = "SELECT * FROM categories"; $result = mysql_query($query); while($row = mysql_fetch_array($result)) { echo "<option value=". $row["category"] .">". $row["category"] ."</option>"; } ?> </select> <p><b>Email:</b><br /><input name='email' type='text' id="email" value='' size="50" /> <p><b>Mobile:</b><br /> <input name='mobile' type='text' id="mobile" value='' size="40" /> </p> <input type='submit' value='Save' /> <input type='hidden' value='1' name='submitted' /> </form> <?php if (isset($_POST['submitted'])) { $rank = mysql_real_escape_string($_POST['rank']); $forename = mysql_real_escape_string($_POST['forename']); $surname = mysql_real_escape_string($_POST['surname']); $category = mysql_real_escape_string($_POST['category']); $email = mysql_real_escape_string($_POST['email']); $mobile = mysql_real_escape_string($_POST['mobile']); $sql = "INSERT INTO `staff` (`rank` , `forename` , `surname` , `category` , `email` , `mobile` ) VALUES ( '$rank' , '$forename' , '$surname' , '$category' , '$email' , '$mobile')"; mysql_query($sql) or die(mysql_error()); echo (mysql_affected_rows()) ? "Staff Added":"Nothing Added"; } ?> Hi to everybody I need ur help because I’m trying to make a script in php to write the same data but with different date in MySQL depending on the splitting ($data06).... like a schedule...
For example if $data06 = annual and $data03 = “2019/01/01” programm must create in MySQL : 2019/01/01 2020/01/01 2021/01/01 2022/01/01 2023/01/01
if $data06=“half year” will create 10 date , increasing 6 moths ...
But I have a problem at finish of code switch ($data06) { case 'annual': $numrate = 5; $aumdata = "+12 months"; break; case 'half year': $numrate = 10; $aumdata = "+6 month"; break;
default: echo "error"; $sql = "INSERT into $nometb ( name, scadenza ) values ( '$data01', '$data03' )"; if ($conna->query($sql) === TRUE) {} else {die('ERROR'. $conna->error); }
//IMPORT NEXT AND NEW DATE $newDate = date_create($data03); for ($mul = 2; $mul <= $numrate; ++$mul) {
$datanuova = date_create($data03); $datanuova->modify($aumdata); $datanuova->format('yy/m/d'); $newDate = $datanuova->format('yy/m/d');
$sql = "INSERT into $nometb ( name, scadenza ) values ( '$data01', '$newDate' )"; if ($conna->query($sql) === TRUE) {} else {die('ERROR'. $conna->error); }
//HERE THERE IS ERROR $data03 = $newDate;
if ($conna->query($sql) === TRUE) {} else {die('ERRORE NELL\'IMPORTAZIONE'. $conna->error); } }
} }
}
How I can resolve ?
many thanks Francesco I've begun to play around with object oriented php and I was wondering how I would go about writing a method that inserts values into a table.
I have a class, called queries, and I made this very simple function:
class queries { public function insert($table, $field, $value){ global $dbh; $stmt = $dbh->prepare("INSERT INTO $table ($field) VALUES (:value)"); $stmt->bindParam(":value", $value); $stmt->execute(); } } $queries = new queries(); how do I make the $image piece so that it inserts "images/$image.php" into the database? VALUES('$name', '$id', '$image','$event')";
Hi guys, Thanks
if(isset($_POST['send'])){ $category = $_POST['category']; $item_type = $_POST['item_type']; $item_size = $_POST['item_size']; $product_name = $_POST['product_name']; $item_qty = $_POST['item_qty']; $price = $_POST['price']; $total_price = $_POST['total_price']; $item_price = $_POST['item_price']; $sql = " INSERT INTO shopping( trans_ref, category, product_name, item_type, item_size, item_qty, item_price, price, date ) VALUES( :trans_ref, :category, :product_name, :item_type, :item_size, :item_qty, :item_price, :price, NOW() ) "; $stmt = $pdo->prepare($sql); $stmt->execute(array( ':trans_ref' => $_SESSION['trans_ref'], ':category' => $category, ':product_name' => $product_name, ':item_type' => $item_type, ':item_size' => $item_size, ':item_qty' => $item_qty, ':item_price' => $item_price, ':price' => $price )); if ( $stmt->rowCount()){ echo '<div class="alert bg-success text-center">SHOPPING COMPLETED</div>'; }else{ echo '<div class="alert bg-danger text-center">SHOPPING NOT COMPLETED. A PROBLE OCCURED</div>'; } }
Hi I have started my error checking for my form. I am understand that the date must be inserted in the format yyyy/mm/dd but on my form i need it to be inserted in the format dd/mm/yyyy. I have wrote some code but have only been doing php about a week properly so I can't see what my error is. Whenever I try to insert the date, the form its self does not error but if i check the database the date is simply 0000/00/00. Can anyone help? if(isset($_POST['submit'])) { $first_name = mysql_real_escape_string($_POST['first_name']); $last_name = mysql_real_escape_string($_POST['last_name']); $DOB = mysql_real_escape_string($_POST['DOB']); $sex = mysql_real_escape_string($_POST['sex']); $email = mysql_real_escape_string($_POST['email']); $username = mysql_real_escape_string($_POST['username']); $password = mysql_real_escape_string($_POST['password']); $agree = mysql_real_escape_string($_POST['agreed']); $creation_date = mysql_real_escape_string($_POST['creation_date']); $user_type = mysql_real_escape_string($_POST['member_type']); $access_level = mysql_real_escape_string($_POST['access_level']); $validation = mysql_real_escape_string($_POST['validation_id']); $club_user = mysql_real_escape_string($_POST['user_type']); $date_check = "/^([0-9]{2})/([0-9]{2})/([0-9]{4})$/"; if($first_name == "") { $message = "Please enter a first name"; $success = 0; } else if($last_name == "") { $message = "Please enter a surname"; $success = 0; } else if($DOB =="") { $message = "Please enter your date of birth."; $success = 0; } else if(!(preg_match("/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/", $DOB))) { $message = "Please enter your birthday in the format dd/mm/yyyy"; $success = 0; } else if($email =="") { $message = "Please enter a correct email."; $success = 0; } else if($username =="") { $message = "Please enter a username."; $success = 0; } else if($password =="") { $message = "Please enter a password greater than 6 characters long."; $success = 0; } else { $DOB = $explode[2]."-".$explode[1]."-".$explode[0]; $password_md5 = md5($password); $insert_member= "INSERT INTO Members (`first_name`,`last_name`,`DOB`,`sex`,`email`,`username`,`password`,`agree`,`creation_date`,`usertype`,`access_level`,`validationID`) VALUES ('".$first_name."','".$last_name."','".$DOB."','".$sex."','".$email."','".$username."','".$password_md5."','".$agree."','".$creation_date."','".$user_type."','".$access_level."', '".$validation."')"; $insert_member_now= mysql_query($insert_member) or die(mysql_error()); $url = "thankyou.php?name=".$_POST['username']; header('Location: '.$url); i have this code... and i want to make it more dynamic.... Code: [Select] <?php $content = $content[1].$content[2].$content[3].$content[4].$content[5].$content[6].$content[7].$content[8].$content[9].$content[10].$content[11].$content[12] .$content[13].$content[14].$content[15].$content[16] .$content[17].$content[18].$content[19].$content[20].$content[21].$content[22].$content[23].$content[24]; $sql = mysql_query ("insert into database (content) values ('$content')") or die(mysql_error()); ?> for example... instead content[1]. content[2]. content[3] ...etc... i want something like this....... $content = $content[from 1 to 24]; or $content = $content[from 1 to 777]; any solutions? |