PHP - Trouble Inserting Data Into Table
Hello,
I'm having trouble inserting data into a MySQL table. The user has a form which is HEIGHT and WIDTH and NUMBER_OF_OBSERVATIONS. All these values are stored in the same table. NUMBER_OF_OBSERVATIONS does what it needs to and inserts its calculated results into the database, as does DATE_TIME. I've been trying for a couple of days to get this done, and I am having no luck in getting it sorted. Any help is greatly appreciated! Generator.php Code: [Select] $WIDTH = $_POST['WIDTH']; $HEIGHT = $_POST['HEIGHT']; $NUMBER_OF_OBSERVATIONS = $_POST['NUMBER_OF_OBSERVATIONS']; $db1 = new Number_Information(); $db1->openDB(); $OBSERVATION_ID = $db1->insert_Observation(); echo "<br /><br />Success. ID: <strong>$OBSERVATION_ID<strong>"; $db1->closeDB(); Number_Information.php Code: [Select] function insert_Observation() { //$Date_Now = datetime(); $sql = "INSERT INTO Observations (DATE_TIME, HEIGHT, WIDTH) VALUES (NOW(), '{$esc_HEIGHT}','{$esc_WIDTH}' )"; $result = mysql_query($sql, $this->conn); if (!$result) { die("SQL Insertion error: " . mysql_error()); } else { return mysql_insert_id($this->conn); } The table name is Observations Again - Any help is greatly appreciated! Similar TutorialsI'm trying to create a script to use PDO prepared statements to enter data from a post form using functions to perform the PDO required statements. But, it's not working. When I execute it, it enters null in all the fields. I'm hoping someone can tell me why this is not working. I think the functions output what PDO is looking for. I'm not sure how to do this otherwise without writing a lot of code like $site_name= $_POST['site_name']; and entering all of that in the PDO statments. It seemed like it made sense to create the statements from the post array. My code is included below and after that is some output I used to monitor what is going on that shows the output of the functions in the script. Am I doing this all wrong. Is another approach that I haven't discovered? Thanks --Kenoli <?php if(isset($_POST['submit'])){ /** Establish DB connection. Not real data, of course. */ $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /** Remove empty $_POST elements. */ $insert_array = array_filter($_POST); /** Whitelists input to identify columns to which changes are allowed */ $whitelist = array('site_name' =>'', 'site_address' =>'', 'description' =>'', 'surface' =>'', 'tio_contact' =>'', 'site_contact' =>'', 'contact_phone' =>'', 'contact_email' =>'', 'contact_date' =>'', 'comments' =>''); $insert_array = array_intersect_key($insert_array,$whitelist); /************/ /** Create query from $insert_array. */ foreach($insert_array as $key => $value) { $col .= $key . ', '; $val .= ':' .$key . ', '; } /** Remove ', " from end of each array. */ /* For use with update actions to prevent deleting data from fields that contain data. */ $col = substr_replace($col ,"",-2); $val = substr_replace($val ,"",-2); $sql = "INSERT INTO Sites ($col) VALUES ($val)"; /* The result is: INSERT INTO Sites (site_name, site_address, description, contact_phone) VALUES (:site_name, :site_address, :description, :contact_phone)*/ /************/ /** Prepared statement functions */ $stmt = $conn->prepare($sql); foreach($insert_array as $key => $value) { $param = ':' . $key; $stmt->bindParam($param, $$value); echo '$' . "stmt->bindParam($param, $$key)<br>"; // Monitor output } foreach($insert_array as $key => $value) { $$key = $value; echo "$$key = $value<br>"; // Monitor output } $stmt->execute(); // Execute insert ?> The result with dummy data: $insert_array
(
$stmt->bindParam(:site_name, $site_name)
$site_name = asdfasdf Everything looks right but NULLs are inserted in all fields.
i want insert data from text box in html form.there are many text boxes gave name using 2 loops..please tell how can insert data to table?please reply Stuck again on simple code. I am trying to insert some fields extracted from one table into another. I'm using code that worked elsewhere. The SQL statement flies, the script runs, the input array is printed back I get an echo back from the end of the script but nothing is added to the table. Even aded an echo print_r in the conditional and I know the data is getting to the execute command. The script follows with a sample of the input array. I have attached am image of the table I am trying to insert the data into. --Kenoli The script: <?php require '__classes/DB.php'; $sql = "SELECT name, table_id, image_name, description, medium FROM tbl_person_data "; $stmt = $pdo->query($sql); $array1 = $stmt->fetchall(PDO::FETCH_ASSOC); $stmt = $pdo->prepare("INSERT INTO Images (name, person_id, filename, description, medium) VALUES (?,?,?,?,?)"); //$pdo->beginTransaction(); foreach ($array1 as $row) { $stmt->execute($row); } echo "<pre>"; print_r ($row); echo "</pre>"; echo '<h4>Got to end of file</h4>'; ?> $array1: The input array [0] => Array ( [name] => Carol Lettko [table_id] => 21 [image_name] => Carol_Lettko-DSC_3022.jpg [description] => Baby Herons/Brickyard [medium] => photo ) [1] => Array ( [name] => [table_id] => 22 [image_name] => Carol_Lettko-DSC_0164.JPG [description] => Heron/Brickyard [medium] => photo ) [2] => Array ( [name] => [table_id] => 23 [image_name] => Carol_Lettko-IMG_5723.jpg [description] => Kayaker/Brickyard [medium] => photo )
I want to take data from one table and insert it into another in the same database, the problem is the two tables have different values so it wouldn't be as simple as using an INSERT INTO script. From table 1 I want to extract a row ID as well as a field called systems. I then want to insert that into the second table which is structured, Id (null) Name (games) Value (the data given from Systems in the other) ID2 (the ID from the other table) Category (news) Any ideas how I can go about this? Hello there! I've been banging my head on this for a while and I just can't seem to get it to work properly. I have a dropdown menu which selects information from table1 using a select statement (this table is called 'lid'). It selects the firstname, lastname and member id from this table and shows it in the dropdown menu. I'm glad I got that part working but the hard thing is inserting the data that the user selects into another table. So when you select the id member from this dropdown menu it only inserts a blank row into table2 (which is called 'teamlid'). Can you guys help me? How can I insert the id member into my table2? What am I doing wrong here? Thanks a million! This is my first post so if I'm doing anything wrong, let me know and I'll fix it asap! My code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Boast & Drive</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css"> <style type="text/css"> .wrapper{ width: 650px; margin: 0 auto; } .page-header h2{ margin-top: 0; } table tr td:last-child a{ margin-right: 15px; } </style> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="page-header clearfix"> <h2 class="pull-left">Teamleden</h2> <div class="btn-toolbar"> <a href="read.php" class="btn btn-primary btn-lg pull-right">Terug</a> </div> </div> <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); error_reporting(E_ALL); //Verbinding maken met de database require_once "login.php"; $sql = "SELECT tl.teamnaam, tl.tl_ID, tl.lidnummer, l.voornaam, l.achternaam FROM teamlid tl JOIN lid l ON tl.lidnummer = l.lidnummer ORDER BY tl.teamnaam;"; if($result = mysqli_query($conn, $sql)) { if(mysqli_num_rows($result) > 0) { echo "<table class='table table-bordered table-striped'>"; echo "<thead>"; echo "<tr>"; echo "<th>Teamnaam</th>"; echo "<th>Tl_ID</th>"; echo "<th>Lidnummer</th>"; echo "<th>Voornaam</th>"; echo "<th>Achternaam</th>"; echo "</tr>"; echo "</thead>"; echo "<tbody>"; while($row = mysqli_fetch_array($result)){ echo "<tr>"; echo "<td>" . $row['teamnaam'] . "</td>"; echo "<td>" . $row['tl_ID'] . "</td>"; echo "<td>" . $row['lidnummer'] . "</td>"; echo "<td>" . $row['voornaam'] . "</td>"; echo "<td>" . $row['achternaam'] . "</td>"; echo "<td>"; echo "<a href='update.php?id=". $row['lidnummer'] ."' title='Gegevens wijzigen' data- toggle='tooltip'><span class='glyphicon glyphicon-pencil'></span></a>"; echo "<a href='delete.php?id=". $row['lidnummer'] ."' title='Lid verwijderen' data- toggle='tooltip'><span class='glyphicon glyphicon-trash'></span></a>"; echo "</td>"; echo "</tr>"; } echo "</tbody>"; echo "</table>"; mysqli_free_result($result); } else{ echo "<p class='lead'><em>Er zijn geen gegevens om weer te geven.</em></p>"; } } else{ echo "De volgende fout is gevonden: " . mysqli_error($conn); } ?> <form name="dropdown" method="post"> <div class="page-header clearfix"> <h2 class="pull-left">Teamlid toevoegen</h2> </div> <p>Selecteer hieronder met behulp van het dropdown menu een lid welke je aan bovenstaand team wilt toevoegen</p> <div class="container-fluid"> <div class="row"> <?php // Variabelen aanmaken en tonen met lege waardes $teamnaam = $lidnummer = ''; // Code voor dropdown. Selecteert voornaam, achternaam en lidnummer van tabel lid) $sql = "SELECT voornaam, achternaam, lidnummer FROM lid ORDER BY achternaam"; $result = mysqli_query($conn, $sql); echo "<select id='teamLid' name='teamLid'>"; echo "<option>--Selecteer Lid--</option>"; while ($row = mysqli_fetch_array($result)) { echo "<option value='" . $row['lid'] . "'>" . $row['voornaam'] . " " . $row['achternaam'] . " " . $row['lidnummer'] . "</option>"; } echo "</select>"; if (isset($_POST["id"]) && !empty($_POST["id"])) { $id = $_POST["teamLid"]; $stmt = $conn->prepare("INSERT INTO teamlid (teamnaam, lidnummer) VALUES (?,?)"); $stmt->bind_param('si', $param_teamnaam, $param_lidnummer); $param_teamnaam = $teamnaam; $param_lidnummer = $lidnummer; $stmt->execute(); } // Verbinding sluiten mysqli_close($conn); ?> <div> <input type="hidden" name="id" value="<?php echo $id; ?>" /> <input type="submit" name="submit" class="btn btn-primary" value="Toevoegen"> </div> </div> </div> </form> </div> </div> </body> </html>
I've got the following code: echo <<<myStringEcho <script src="$myPluginPath/jquery.dummy.js"></script> myStringEcho; The problem is that $myPluginPath already has a / character at the end, so I don't need to put it in above But, I can't just remove it, otherwise I'll get $myPluginPathjquery.dummy.js How can I insert and have no spaces? Thanks OM I have this simple form that registers schools. This year I have decide to upgrade and include a feature that checks if the school is already registered or not based on the imputed name. Here is the code (that is the only way I know how): mysql_connect("", "", "") or die(mysql_error( '' )); mysql_select_db("") or die(mysql_error( '' )); $query = "SELECT * FROM School_Registrations WHERE School_Name= '$_POST[SchoolName]' "; $result = mysql_query($query); if (mysql_numrows($result) > 0) { while($row = mysql_fetch_array($result)) echo" error code here";} else {mysql_query("INSERT INTO `database`.`School_Registrations` (all the variables here);") or die(mysql_error( '' )); echo "Success Code";} I am trying to incorporate this code somewhere into the 'else' statement but I have no luck. I am constantly getting some errors and when I fix one there is one more to take its place. I am lost. The last one I can not fix and I am not sure what it wants from me: Fatal error: Call to undefined function getPage() It works by itself without the if/else statement but not in the code listed above $url = 'http://www.otherpage.com/page.php?'; $url .= 'email='.urlencode($_POST['email']); $result2 = getPage('', $url, '', 15); function getPage($proxy, $url, $header, $timeout) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, $header); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_PROXY, $proxy); curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_REFERER, 'http://azsef.org'); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8'); $result2['EXE'] = curl_exec($ch); $result2['INF'] = curl_getinfo($ch); $result2['ERR'] = curl_error($ch); curl_close($ch); return $result2; } Can you tell me why doesn't it work? Thanks I am trying to insert values stored within two dimensional array into mysql database but it does not work as I would expect it. The locations in mysql are defined as char length of 2. When I print_r the array it shows: Array( [0] => Array ( [0] => 04 [1] => 22 [2] => 27 [3] => 28 [4] => 39 [5] => 43 [6] => 47 )) but when I insert them into the mysql like this: Number1A='$MaxMillionsNumber[0][0]', Number1B='$MaxMillionsNumber[0][1]', Number1C='$MaxMillionsNumber[0][2]', Number1D='$MaxMillionsNumber[0][3]', Number1E='$MaxMillionsNumber[0][4]', Number1F='$MaxMillionsNumber[0][5]', Number1G='$MaxMillionsNumber[0][6]'; my values in mysql all show as Ar What am I doing wrong? Can someone please help me figure out how to insert "image" from table users, that contains the .jpg data associated with "screen_name", into table friends "friendimg" Here are the tables: friends: id, member, friendwith, friendimg users: id, screen_name, image $_GET["id"] only contains "screen_name" and"image" is not included add.php Code: [Select] <?php if(isset($_GET["id"])) { echo "<br/><a href=\"member?add=".$_GET["id"]."\">Add ".$_GET["id"]." to your list of friends</a>"; } ?>member.php Code: [Select] <?php if(isset($_GET["add"])) { $username = $_SESSION["screen_name"]; $friend = $_GET["add"]; $query = "SELECT * FROM friends WHERE member='$username' AND friendwith='$friend'"; $result = mysql_query($query); $exist = mysql_num_rows($result); if($exist=='0') { $query = "INSERT INTO friends(member,friendwith) VALUES('$username','$friend')"; mysql_query($query); echo "<br/>You are now friends with $friend"; } else { echo "<br/>$friend is already in your list of friends!"; } } ?> This UPDATE script works:
$query = $pdo->prepare("UPDATE posts SET headline = ? WHERE id = ?"); $query->bindValue("1", $_POST['headline']); $query->bindValue("2", "2"); $query->execute();Though, this INSERT script does not work: $query = $pdo->prepare("INSERT INTO posts (headline, post) VALUES (?, ?)"); $query->bindValue("1", $_POST['headline']); $query->bindValue("2", $_POST['post']); $query->execute();Nothing gets added, when executing this script. The connection: <?php $dsn = "mysql:dbname=phpblog;host=localhost"; $user = "root"; $password = ""; try{ $pdo = new PDO($dsn, $user, $password); }catch(PDOException $e){ echo "Connection failed: " . $e->getMessage(); } ?>Any suggestions why the INSERT script is not working? Edited by glassfish, 25 November 2014 - 09:26 AM. I am at a loss why my query is not inserting values into db. Even if I do echo $query or var_dump($query) there is nothing printed at all. All values are being passed successfully just not being inserted. I am getting 'Could not connect' but I do not know why. All connections are established and as a test I took this code and ran it on it's own with dummy data and it inserted the data fine. I can only think it has something to do with the $response_array. Where am I going wrong. and would appreciate any help. Thanks Code: [Select] <?php require_once('Connections/sample.php'); ?> <?php session_start(); $new = 1; $activity = 'General Contact Enquiry'; $mobile = 'Submitted from mobile'; $name = mysql_real_escape_string($_POST['GC_name']); $department = mysql_real_escape_string($_POST['GC_department']); $message = mysql_real_escape_string($_POST['GC_message']); $email = mysql_real_escape_string($_POST['GC_email']); $company = mysql_real_escape_string($_POST['GC_company']); $position = mysql_real_escape_string($_POST['GC_position']); //response array with status code and message $response_array = array(); //validate the post form //check the name field if(empty($name)){ //set the response $response_array['status'] = 'error'; $response_array['message'] = 'Name cannot be blank'; //check the name field } elseif(empty($company)) { //set the response $response_array['status'] = 'error'; $response_array['message'] = 'You must enter a company name'; //check the position field }elseif(empty($position)) { //set the response $response_array['status'] = 'error'; $response_array['message'] = 'You must enter a position'; //check the email field } elseif(empty($email)) { //set the response $response_array['status'] = 'error'; $response_array['message'] = 'You must enter a valid email address'; //check the dept field }elseif($department=="Choose Department") { //set the response $response_array['status'] = 'error'; $response_array['message'] = 'You must select a department'; //check the message field }elseif(empty($message)) { //set the response $response_array['status'] = 'error'; $response_array['message'] = 'You must enter a message'; //check the dept field } else { //set the response $response_array['status'] = 'success'; $response_array['message'] = 'Your enquiry has been sent succesfully'; $flag=1; } //send the response back echo json_encode($response_array); if($flag == 1) { mysql_select_db($database_sample, $sample); $query = 'INSERT INTO feedback (company, department, name, email, position, feedback, date, new) VALUES (\''.$company.'\', \''.$department.'\', \''.$name.'\', \''.$email.'\', \''.$position.'\', \''.$message.'\', NOW() , \''.$new.'\')'; mysql_query($query) or die("Could not connect"); } ?> Hello, I have three scripts below that I was wondering if someone can look at as a second opinion. What they all have in common is they are supposed to append data to some tables in my database. They match the code on all my other scripts but for some reason these particular scripts will not append the data to the files. This first one... is supposed to insert the name of the doctor this person uses, and then gets the last ID created and inserts it into another table...no matter what I try, it will not do it. Code: [Select] <?php session_start(); $userid=$_SESSION['userID']; $firstName=$_SESSION['fname']; $lastName=$_SESSION['lname']; $camperID=$_POST['camperID']; $physicianFName=$_POST['physicianFName']; $physicianLName=$_POST['physicianLName']; $physicianSuffix=$_POST['physicianSuffix']; $practiceName=$_POST['practiceName']; $physicianAddress1=$_POST['physicianAddress1']; $physicianAddress2=$_POST['physicianAddress2']; $physicianAddress3=$_POST['physicianAddress3']; $physicianCity=$_POST['physicianCity']; $physicianState=$_POST['physicianState']; $physicianZip=$_POST['physicianZip']; $physicianOfficeP=$_POST['physicianOfficeP']; $physicianOfficeF=$_POST['physicianOfficeF']; $physicianSpecialty=$_POST['physicianSpecialty']; echo $camperID. ' ' .$physicianFName. ' ' .$physicianLName; //htc information and physician $htcName=$_POST['htcInfo']; $htcPhysician=$_POST['htcPhysician']; $con=mysql_connect("xxx.xxx.xxx.xx", "xxx", "xxxx") or die ("cannot connect"); mysql_select_db("testcamp") or die ("cannot select database"); $sql="INSERT INTO Physicians(physicianFName, physicianLName, physicianSuffix, practiceName, physicianAddress1, physicianAddress2, physicianAddress3, physicianCity, physicianState, physicianZip, physicianOfficeP, physicianOfficeF, physicianSpecialty) VALUES ('$physicianFName', '$physicianLName', '$physicianSuffix', '$physicianAddress1', '$physicianAddress2', '$physicianAddress3', '$physicianCity', '$physicianState', '$physicianZip', '$physicianOfficeP', '$physicianOfficeF', '$physicianSpecialty')"; $result=mysql_query($sql,$con); $physicianID=mysql_insert_id(); $sql2="INSERT INTO CamperPhysicianInfo(physicianID, camperID) VALUES ('$physicianID', '$camperID')"; $result2=mysql_query($sql2,$con); $sql3="INSERT INTO CamperHTCInfo(camperID, htcID) VALUES ('$camperID', '$htcName')"; $result3=mysql_query($sql3,$con); $sql4="INSERT INTO camperHTCPhysicianInfo(camperID, htcPhysicianID) VALUES ('$camperID', '$htcPhysician')"; $result4=mysql_query($sql4,$con); ?> This next one...is supposed to enter data into the CamperRegistrations tables and also enter data into another table for a questionaire that was completed on the form previous to this page...same thing no matter what I try will not append data. Code: [Select] <?php $question12=$_POST['question12']; $question12a=$_POST['question12a']; session_start(); $userid=$_SESSION['userID']; $firstName=$_SESSION['fname']; $lastName=$_SESSION['lname']; $camperID=$_SESSION['camperID']; $con=mysql_connect("xxx.xxx.xxx.xx", "xxx", "xxx") or die ("cannot connect"); mysql_select_db("testcamp") or die ("cannot select database"); $sql="INSERT INTO Question12(camperID, question12Answer, teaching) VALUES ('$camperID', '$question12', '$question12a')"; $result=mysql_query($sql,$con); $date=date("Y-m-d"); $defaultStatus=1; $sql2="INSERT INTO CamperRegistrations(userID, camperID, registrationDate, registrationStatus) VALUES ('$userid', '$camperID', '$date', '$defaultStatus')"; $result2=mysql_query($sql2,$con); ?> and then on this same page with this script... is it possible to carry session information when using HTML links instead of a submit form? I need the userid to carry to the next page with a link, but it won't do that either... Any help would be appreciated and thanks in advance for looking. ~jcjst21 i want to insert only whats checked to db:) but everything get posted for now i came upwith a for loop but thats for inserting all data not only whats checked any one know a good way to do this? Hey all I really need help with a project I am doing. I need to create a website with a registration form that checks if the user exists if not to add the user details to my local database MySQL. My webpage looks like it should, it connects with the database but when I enter a new user it does nothing when it should save the new user to the database! I am guessing my problem is within the if...else section. Please help my code is: Code: [Select] <?php include('connect.php'); //connection details to database in a connect.php page $name = ""; $surname = ""; $username = ""; $password = ""; $confirmp = ""; $errorMessage = ""; $num_rows = 0; //if form was submitted if ($_SERVER['REQUEST_METHOD'] == 'POST'){ //get values from fields $submit = $_POST['Submit']; $title = $_POST['title']; $name = $_POST['name']; $surname = $_POST['surname']; $username = $_POST['username']; $password = $_POST['password']; $confirmp = $_POST['confirmp']; //getting string lengths $nameLength = strlen($name); $surnameLength = strlen($surname); $usernameLength = strlen($username); $passwordLength = strlen($password); $confirmpLength = strlen($confirmp); //testing if strings are between certain numbers if ($nameLength > 1 && $nameLength <= 20) { $errorMessage = ""; } else { $errorMessage = $errorMessage . "Name must be between 2 and 20 characters" . "<br>"; } if ($surnameLength >= 2 && $surnameLength <= 50) { $errorMessage = ""; } else { $errorMessage = $errorMessage . "Surname must be between 2 and 50 characters" . "<br>"; } if ($usernameLength = 6) { $errorMessage = ""; } else { $errorMessage = $errorMessage . "Username must be 6 characters long" . "<br>"; } if ($passwordLength = 6) { $errorMessage = ""; } else { $errorMessage = $errorMessage . "Password must be 6 characters long" . "<br>"; } if ($confirmpLength = 6) { $errorMessage = ""; } else { $errorMessage = $errorMessage . "Password must be 6 characters long" . "<br>"; } if ($errorMessage == "") { $query = "SELECT * FROM user WHERE username = '$username' AND password = '$password'"; $result = mysql_query($query); $num_rows = mysql_num_rows($result); //check to see if the $result is true if ($num_rows = 1){ $errorMessage = "Username already exists"; } else { if($password == $confirmp){ $query = "INSERT INTO user (title, name, surname, username, password) VALUES ('$title', '$name', '$surname', '$username', '$password')"; $result = mysql_query($query); session_start(); $_SESSION['login'] = "1"; header ("Location: login.php"); } else { $errorMessage = "Passwords do not match!"; } } } else { $errorMessage = "Error Registering"; } } else { $errorMessage = "Please enter your details"; } ?> <html> <head> <title>Mia's Beauty Products</title> </head> <body> <p><img src = "banner1.jpg" width = "975" height = "95" alt = "Mia's Beauty Product" /></p> <br> <p align= "center"><a href="register.php">Register</a> | <a href="login.php">Login</a> | <a href="insert.php">Insert</a> | <a href="list.php">List</a></p> <form method = "post" action = "register.php"> <table> <tr><td>Title:</td><td><select name = "title"> <option>Miss</option> <option>Mrs</option> <option>Mr</option> </select></td></tr> <tr><td>Name:</td><td><input name = "name" type = "text" value ="<?php print $name;?>"></td></tr> <tr><td>Surname:</td><td><input name = "surname" type = "text" value ="<?php print $surname;?>"></td></tr> <tr><td>Username:</td><td><input name = "username" type = "text" value ="<?php print $username;?>"></td></tr> <tr><td>Password:</td><td><input name = "password" type = "password" value ="<?php print $password;?>"></td></tr> <tr><td>Confirm Password:</td><td><input name = "confirmp" type = "password" value ="<?php print $confirmp;?>"></td></tr> <tr><td><input type = "submit" name = "Submit" value = "Submit"></td></tr> </table> </form> <p align= "center"><a href="code.txt">Code</a></p> <br> <?php print $errorMessage; ?> <p><img src = "banner2.jpg" width = "975" height = "95" alt = "Mia's Beauty Product" /></p> </body> </html> Thank you Amanda Hello All, First, I'm new to php and I have spent a lot of time searching forums and google for the answer to my question with no luck, so if it's a topic already covered, PLEASE reply with a link or point me in the right direction. OK, I have a form that let's users upload multiple images. The upload portion works fine. What I can't figure out how to do is put the image name of each file that gets uploaded all into the same table record. I also need each file name to be put into it's own column in the table. For example, file1, file2 and file3 will get dumped into the same record and into it's respective column (uploaded_image1, uploaded_image2, uploaded_image3). I've included the working upload code and the code that inserts some of the information into the database (just not the image names). Code: [Select] echo "<textarea name=challenge rows=15 cols=60> </textarea><br/><br/>" echo "<textarea name=insight rows=15 cols=60> </textarea><br/><br/>" for($i=1; $i<=$max_no_img; $i++){ echo "Image $i <input type=file name='image[]' ><br/>"; } echo "<input type=submit value=Submit>"; Code: [Select] // Connect to DB $host = 'xxx'; $user = 'xxx'; $pass = 'xxx'; $db = 'xxx'; mysql_connect($host,$user,$pass) or die(mysql_error()); mysql_select_db($db) or die(mysql_error()); // Post Variables $challenge = $_POST['challenge']; $insight = $_POST['insight']; $filename=serialize($_POST['filename']); // Upload Images while(list($key,$value) = each($_FILES[image][name])) { if(!empty($value)) { $filename = $value; $add = "upimage/$filename"; copy($_FILES[image][tmp_name][$key], $add); chmod("$add",0777); } } // Insert into database $query = "INSERT INTO table ( challenge, insight, uploaded_image1, uploaded_image2, uploaded_image3,)". "values ( '$challenge', '$insight', '$filename' '$filename2' '$filename3')"; mysql_query($query) or die('Error, query failed : ' . mysql_error()); I know just enough about php that the reason the above wont work, is because $filename2 and $filename3 haven't been given a value. Unfortunately, I have no idea how to separate that information in the array. If anyone can point me in the right direction I'd be forever grateful! Thanks, Gary I am trying to insert product descriptions into a mysql database, however they are failing because of apostrophes in the text. How do I fix this? Everything is working fine except $productdescription $ProductDescription contains, "Record In Stereo Sound, Then Play Back Your Videos Instantly On You Computer. The Sx130 Is Is All About Creativity, With Fun New Scene Modes Like Miniature Effect For Movies, And Fisheye Effect For Artistically Distorted Stills. While You're Having Fun Creating, The Camera's Smart Flash Exposure And Advanced Smart Auto Systems Are Ensuring That Every Image Is The Best It Can Be. Add The Digic 4 Image Processor, 12.1 Megapixels And Canon's Optical Image Stabilizer, And You've Got The Ideal Camera For Making The Good Times Last." SQL Error on insert, "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 're Having Fun Creating, The Camera's Smart Flash Exposure And Advanced Smart Aut' at line 1 " Code: [Select] mysql_select_db("testdb") or die(mysql_error()); mysql_query ("INSERT INTO product (merchantname, producttitle, productdescription, gtin, availability, price) VALUES ('$merchantname[1]','$producttitle[1]','$productdescription[1]','$gtin[1]',''$availability[1]','$price[1]')"); hi guys Ive written this php to take in two variables from the http POST, the idea is that I can multiple devices submit temperature readings to the php script, the script then append the unix time stamp and then the the 3 variables - device id, temp and unix time are then stored in a mysql DB. I can get the variables to present on a php page for debugging but I cant get the variables to be stored in the mysql DB. See the code: Code: [Select] <?php $unixtime = time(); // get device variables $device_id=$_GET['device']; $device_temp=$_GET['temp']; /* //for testing purposes echo "unixtime: " . $unixtime . "<br />"; echo "device id: " . $device_id . "<br />"; echo "device_temp: " . $device_temp . "<br />"; */ // Make a MySQL Connection mysql_connect("localhost", "username", "password") or die(mysql_error()); mysql_select_db("test") or die(mysql_error()); //mysql query $query = "INSERT INTO temperature VALUES ('',$device_id,$temp,$unixtime)"; // Insert a row of information into the relevant device table mysql_query($query); or die(mysql_error()); mysql_close(); echo "Data Inserted!"; ?> I cant see where Im going wrong to correct this, but as nothing is displayed on the page i believe I am not forming the query correctly? - any ideas would be much appreciated. Thank you Mathew hello friends, actually i am trying to insert data in mysql database. here is my code <?php include_once("../includes/database.php"); ?> <!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>Insert Product</title> </head> <body> <form action="insert_product.php" method="post" enctype="multipart/form-data"> <table align="center" width="600"> <tr align="center"> <td colspan="8"><h2> Insert New Post</h2></td> </tr> <tr> <td align="right"><b>Product Title :</b></td> <td><input type="text" name="product_title" size="50" style="background-color:#06C; color:#FFF" /></td> </tr> <tr> <td align="right"><b>Product Category :</b></td> <td> <select name="product_cat" style="background-color:#06C; color:#FFF" > <option>Select A Category </option> <?php $get_cats = "SELECT * FROM categories"; $run_cats = mysqli_query($con, $get_cats); while($row_cats = mysqli_fetch_array($run_cats)){ $cat_id = $row_cats['cat_id']; $cat_title = $row_cats['cat_title']; echo "<option value='$cat_id'>$cat_title</option>"; } ?> </select> </td> </tr> <tr> <td align="right"><b>Product Platform :</b></td> <td> <select name="product_brand" style="background-color:#06C; color:#FFF" > <option>Select A Platform </option> <?php $get_brands = "SELECT * FROM brands"; $run_brands = mysqli_query($con, $get_brands); while($row_brands = mysqli_fetch_array($run_brands)){ $brand_id = $row_brands['brand_id']; $brand_title = $row_brands['brand_title']; echo "<option value='$brand_id'>$brand_title</option>"; } ?> </select> </td> </tr> <tr> <td align="right"><b>Product Image :</b></td> <td><input type="file" name="product_image" /></td> </tr> <tr> <td align="right"><b>Product Price :</b></td> <td><input type="text" name="product_price" style="background-color:#06C; color:#FFF" /></td> </tr> <tr> <td align="right" valign="top"><b>Product Description :</b></td> <td><textarea name="product_desc" cols="50" rows="10" style="background-color:#06C; color:#FFF" ></textarea></td> </tr> <tr> <td align="right"><b>Product Keywords :</b></td> <td><input type="text" name="product_keywords" size="50" style="background-color:#06C; color:#FFF" /></td> </tr> <tr align="center"> <td colspan="8"><input type="submit" name="insert_post" value="Submit Now" /></td> </tr> </table> </form> </body> </html> <?php if(isset($_POST['insert_post'])){ $product_title = $_POST['product_title']; $product_cat = $_POST['product_cat']; $product_brand = $_POST['product_brand']; $product_price = $_POST['product_price']; $product_desc = $_POST['product_desc']; $product_keywords = $_POST['product_keywords']; $product_image = $_FILES['product_image']['name']; $product_image_tmp = $_FILES['product_image']['tmp_name']; move_uploaded_file($product_image_tmp,"product_image/$product_image"); $sql = "INSERT INTO products (product_cat,product_brand,product_title,product_price,product_desc,product_image,product_keywords) VALUES ('$product_cat','$product_brand','$product_title','$product_price','$product_desc','$product_image','$product_keywords')"; $query = mysqli_query($con, $sql); if($query){ echo "<script>alert('Product Has Been Inserted')</script>"; echo "<script>windoow.open('insert_product.php','_self')</script>"; exit(); }else{ echo "<script>alert('errror')</script>"; } } ?>but somehow its not inserting data into my table can somebody tell wherre m i doing mistake. the categories and brands are displaying from database. But its not inserting data here is my database script. <?php $con = mysqli_connect("localhost","root","","sg"); ?> Hi.. I need help in using for loop in saving data from while loop. Now, I encountered that the Demanded Qty was get only is the last Demanded Qty and save it to all Items. I want to happen is per Items will save the Demanded Qty. for example: Items Demanded Qty P28 ---1 P28 ---1 P28 ---1 P30 ---2 P30 ---2 P30 ---2 and so on.. here is my code: <?php error_reporting(0); date_default_timezone_set("Asia/Singapore"); //set the time zone $con = mysql_connect('localhost', 'root',''); if (!$con) { echo 'failed'; die(); } mysql_select_db("mes", $con); $sr_date =date('Y-m-d H:i:s'); $sql = "SELECT sr_number FROM stock_requisition ORDER BY sr_date DESC LIMIT 1"; $result = mysql_query($sql, $con); if (!$result) { echo 'failed'; die(); } $total = mysql_num_rows($result); if ($total <= 0) { $currentSRNum = 1; $currentYear = (int)(date('y')); $currentMonth = (int)(date('m')); $currentDay = (int)(date('d')); $currentSRYMD = substr($row['sr_number'], 0, 6); $currentYMD = date("ymd"); if ($currentYMD > $currentSRYMD) { $currentSRNum = 1; } else { $currentSRNum += 1; } } else { $row = mysql_fetch_assoc($result); $currentSRNum = (int)(substr($row['sr_number'],0,3)); $currentSRYear = (int)(substr($row['sr_number'],2,2)); $currentSRMonth = (int)(substr($row['sr_number'],0,2)); $currentSRNum = (int)(substr($row['sr_number'],6,4)); $currentYear = (int)(date('y')); $currentMonth = (int)(date('m')); $currentDay = (int)(date('d')); $currentSRYMD = substr($row['sr_number'], 0, 6); $currentYMD = date("ymd"); if ($currentYMD > $currentSRYMD) { $currentSRNum = 1; } else { $currentSRNum += 1; } } $yearMonth = date('ymd'); $currentSR = $currentYMD . sprintf("%04d", $currentSRNum); ?> <html> <title>Stock Requisition</title> <head> <link rel="stylesheet" type="text/css" href="kanban.css"> <script type="text/javascript"> function save_sr(){ var sr_date = document.getElementById("sr_date").value; var sr_number = document.getElementById("sr_number").value; var Items1 = document.getElementById("Items1").value; var SubItems = document.getElementById("SubItems").value; var ItemCode = document.getElementById("ItemCode").value; var DemandedQty = document.getElementById("DemandedQty").value; var UoM = document.getElementById("UoM").value; var Class = document.getElementById("Class").value; var Description = document.getElementById("Description").value; var BINLocation = document.getElementById("BINLocation").value; var RequestedBy = document.getElementById("RequestedBy").value; var ApprovedBy = document.getElementById("ApprovedBy").value; var ReceivedBy = document.getElementById("ReceivedBy").value; var IssuedBy = document.getElementById("IssuedBy").value; var Items = document.getElementById("Items").value; document.stock_requisition.action="StockRequisitionSave1.php?sr_date="+sr_date+"&sr_number="+sr_number+"&Items1="+Items1+ "&SubItems="+SubItems+"&ItemCode="+ItemCode+"&DemandedQty="+DemandedQty+"&UoM="+UoM+"&Class="+Class+"&Description="+ Description+"&BINLocation="+BINLocation+"&RequestedBy="+RequestedBy+"&ApprovedBy="+ApprovedBy+"&ReceivedBy="+ReceivedBy+ "&IssuedBy="+IssuedBy+"&Items="+Items; document.stock_requisition.submit(); alert("Stock Requisition data save."); window.location = "StockRequisition1.php"; } function disp(){ document.stock_requisition.action="StockRequisitionDisplay.php"; document.stock_requisition.submit(); } </script> </head> <body> <form name="stock_requisition" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <div id="SR_date"> <label>Date :</label> <input type="text" name="sr_date" value="<?php echo $sr_date; ?>" size="16" readonly="readonly"> </div> <div id="SR_number"> <label>SR# :</label> <input type="text" name="sr_number" value="<?php echo $currentSR; ?>" size="10" readonly="readonly"> <br/> </div> <div> <table> <thead> <th>Items</th> <th>Sub Items</th> <th>Item Code</th> <th>Demanded Qty</th> <th>UoM</th> <th>Class</th> <th>Description</th> <th>BIN Location</th> </thead> <?php $sql = "SELECT DISTINCT Items FROM bom_subitems ORDER BY Items"; $res_bom = mysql_query($sql, $con); while($row = mysql_fetch_assoc($res_bom)){ $Items = $row['Items']; echo "<tr> <td> <input type='name' value='$Items' name='Items[]' id='Items' readonly = 'readonly' size='5'></td> <td> </td> <td> </td> <td><center><input type='text' name='DemandedQty' id='DemandedQty[]' value='' size='7'></center></td> </tr>"; $sql = "SELECT Items, SubItems, ItemCode, UoM, Class, Description, BINLocation FROM bom_subitems WHERE Items = '$Items' ORDER BY Items"or die(mysql_error()); $res_sub = mysql_query($sql, $con); while($row_sub = mysql_fetch_assoc($res_sub)){ $Items1 = $row_sub['Items']; $SubItems = $row_sub['SubItems']; $ItemCode = $row_sub['ItemCode']; $UoM = $row_sub['UoM']; $Class = $row_sub['Class']; $Description = $row_sub['Description']; $BINLocation = $row_sub['BINLocation']; echo "<tr> <td> <input type='hidden' value='$Items1' id='Items1' name='Items1[]'></td> <td> <input type='text' name='SubItems[]' value='$SubItems' id='SubItems' readonly='readonly' size='10'></td> <td> <input type='text' name='ItemCode[]' value='$ItemCode' id='ItemCode' readonly='readonly' size='10'></td> <td> </td> <td> <input type='text' name='UoM[]' value='$UoM' id='UoM' readonly='readonly' size='3'></td> <td> <input type='text' name='Class[]' value='$Class' id='Class' readonly='readonly' size='10'></td> <td> <input type='text' name='Description[]' value='$Description' id='Description' readonly='readonly' size='10'></td> <td> <input type='text' name='BINLocation[]' value='$BINLocation' id='BINLocation' readonly='readonly' size='10'></td> </tr>"; } } ?> </table> </div> <?php $RequestedBy = array('AAA', 'BBB'); $ApprovedBy = array('EEE', 'FFF'); $ReceivedBy = array('III', 'JJJ'); $IssuedBy = array('MMM', 'NNN'); ?> <div id='Requested_By'> <label>Requested By:</label> <select name="RequestedBy"> <option value="Select">Select</option> <option value="AAA" <?php if($_POST['RequestedBy'] == 'AAA') echo "selected='selected'"; ?>>AAA</option> <option value="BBB" <?php if($_POST['RequestedBy'] == 'BBB') echo "selected='selected'"; ?>>BBB</option> </select> </div> <div id='Approved_By'> <label>Approved By:</label> <select name="ApprovedBy"> <option name='Select'>Select</option> <option value="EEE" <?php if($_POST['ApprovedBy'] == 'EEE') echo "selected='selected'"; ?>>EEE</option> <option value="FFF" <?php if($_POST['ApprovedBy'] == 'FFF') echo "selected='selected'"; ?>>FFF</option> </select> </div> <div id='Received_By'> <label>Issued By:</label> <select name="IssuedBy"> <option name='Select'>Select</option> <option value="III" <?php if($_POST['ReceivedBy'] == 'III') echo "selected='selected'"; ?>>III</option> <option value="JJJ" <?php if($_POST['ReceivedBy'] == 'JJJ') echo "selected='selected'"; ?>>JJJ</option> </select> </div> <div id='Issued_By'> <label>Received By:</label> <select name="ReceivedBy"> <option name='Select'>Select</option> <option value="MMM" <?php if($_POST['IssuedBy'] == 'MMM') echo "selected='selected'"; ?>>MMM</option> <option value="NNN" <?php if($_POST['IssuedBy'] == 'NNN') echo "selected='selected'"; ?>>NNN</option> </select> </div> <div id="save_btn"> <input type="button" name="button" value="save" onClick="save_sr()" style="width: 5em;"> <input type="button" name="button" value="display" onclick="disp()"> </div> </form> </body> </html> and here is the save code: <?php error_reporting(0); date_default_timezone_set("Asia/Singapore"); //set the time zone $con = mysql_connect('localhost', 'root',''); if (!$con) { echo 'failed'; die(); } mysql_select_db("mes", $con); $sr_date = $_POST['sr_date']; $sr_number = $_POST['sr_number']; $Items1 = $_POST['Items1']; $SubItems = $_POST['SubItems']; $ItemCode = $_POST['ItemCode']; $DemandedQty = $_POST['DemandedQty']; $UoM = $_POST['UoM']; $Class = $_POST['Class']; $Description = $_POST['Description']; $BINLocation = $_POST['BINLocation']; $RequestedBy = $_POST['RequestedBy']; $ApprovedBy = $_POST['ApprovedBy']; $ReceivedBy = $_POST['ReceivedBy']; $IssuedBy = $_POST['IssuedBy']; $Items = $_POST['Items']; for($i = 0; $i < count($Items1); $i++) { if ( $DemandedQty != "" ) { $sql = "INSERT INTO stock_requisition (sr_date, sr_number, Items, SubItems, ItemCode, DemandedQty, UoM, Class, Description, BINLocation, RequestedBy, ApprovedBy, ReceivedBy, IssuedBy) VALUES ('$sr_date', '$sr_number', '$Items1[$i]', '$SubItems[$i]', '$ItemCode[$i]', '$DemandedQty', '$UoM[$i]', '$Class[$i]', '$Description[$i]', '$BINLocation[$i]', '$RequestedBy', '$ApprovedBy', '$ReceivedBy', '$IssuedBy') "; $result = mysql_query($sql, $con); } } ?> I attach my sample form and the data save in database. Thank you so much Hi,
I have a form like this
<tr> <td><a href="edit_sales_invoice_details.php?id=<?php echo $row['dispatch_id']?>"><?php echo $row['oid'] ?></a></td> <td><?php echo $row['dispatch_id'] ?></td> <td><?php echo $row['cname'] ?></td> <td><?php echo $row['iname'] ?></td> <td><?php echo $row['quantity'] ?></td> <td><?php echo $row['dispatch_quantity'] ?></td> <td><select name="tax[<?php echo $row['dispatch_id']?>]" class="span9"> <option value="<?php echo $row['rate'] ?>"><?php echo $row['tname'].'-'.$row['rate'];?> %</option> <option value="">Tax</option> <?php $s1 = mysql_query("select * from taxes"); while($s2 = mysql_fetch_array($s1)) { ?> <option value="<?php echo $s2['rate'] ?>"><?php echo $s2['name'].'-'.$s2['rate'] ?>%</option> <?php } ?> </select> </td> <td><input type="text" name="freight[<?php echo $row['dispatch_id']?>]" class="span6" /></td> <td><input type="text" name="discount[<?php echo $row['dispatch_id']?>]" class="span6" /></td> <input type="hidden" name="order_id[<?php echo $row['dispatch_id']?>]" value="<?php echo $row['oid']; ?>" /> <td><input type="checkbox" name="selector[]" value="<?php echo $row['dispatch_id']; ?>" /></td> </tr> <?php } ?> <tr><td colspan="11"><input type="submit" name="submit" value="SAVE INVOICE" class="btn btn-info" /></td></tr>Here dispatch_id will be different but the order_id will be same. I want to generate a single invoice id for this and store it in this table invoice.JPG 18.85KB 0 downloads and by taking that invoice_id, i want to insert rest of the multiple line items to this table invoice_line_items.JPG 29.7KB 0 downloads I tried doing like this |