PHP - Insert A Option From A Drop Down Box Not Working?
Sorry got it! my apologizes
Similar TutorialsI’m trying to insert from a multiple option form into MySQL. I’ve tried numerous methods and have had issues such as blank entries being inserted for each specified column, to the last value selected from the form being inserted multiple times, but I never get the desired outcome. Any guidance on how to insert from this type of HTML form? I know that there are issues regarding SQL injection - I'll worry about that later. I'd like to understand how to insert data from this kind of HTML form into MySQL, as i can't seem to find any guidance. There's plenty on how to insert from a standard HTML form i.e. where either every value is selected or left blank, but each entry corresponds to a column in MySQL which either receives a value or NULL. I'm really struggling with when a user can select more than one option from a list. Quote
<form action ='insert.php' method='POST'>
Here’s one option I’ve tried for PHP Quote
<?php
{ { } $conn->close(); ?>
Hi, I am trying to create a drop down menu that will select a value that is stored in the database - right now the code creats a dropdown (with nothing selected) - hope someone can help. in the database, the values are stored as --null- Option1 Option2 Option3 my code is Code: [Select] $instruction = $_GET['instruction']; <?php <select id="instruction" name="instruction"> <option value="" <?php if (!empty($instruction) && $instruction == '' ) echo 'selected = "selected"'; ?>></option> <option value="Option1" <?php if (!empty($instruction) && $instruction == 'Option1') echo 'selected = "selected"'; ?>>Option1</option> <option value="Option2" <?php if (!empty($instruction) && $instruction == 'Option2') echo 'selected = "selected"'; ?>>Option2</option> <option value="Option3" <?php if (!empty($instruction) && $instruction == 'Option3') echo 'selected = "selected"'; ?>>Option3</option> </select> <? Hello guys I've hit a problem whicle trying to validate my form. I have 3 drop down boxes where the user chooses from three options. But I can't seem to figure out how to set the validation so the user does not select the same option in each drop down. Can anyone help me solve this please. Thank you. <p><b>Course Choice 1</b> <select name="course1"> <option value="0"></option> <option value="Business computer Systems">Business computer Systems</option> <option value="Business computer Science">Business computer Science</option> <option value="Business computer Science (Games)">Business computer Science (Games)</option> <option value="Business Information Systems">Business Information Systems</option> <option value="Digital Media Development">Digital Media Development</option> <option value="Digital Media">Digital Media</option> </select></p> <p><b>Course Choice 2</b> <select name="course2"> <option value="Leave Blank">Leave Blank</option> <option value="Business computer Systems">Business computer Systems</option> <option value="Business computer Science">Business computer Science</option> <option value="Business computer Science (Games)">Business computer Science (Games)</option> <option value="Business Information Systems">Business Information Systems</option> <option value="Digital Media Development">Digital Media Development</option> <option value="Digital Media">Digital Media</option> </select></p> <p><b>Course Choice 3</b> <select name="course3"> <option value="Leave Blank">Leave Blank</option> <option value="Business computer Systems">Business computer Systems</option> <option value="Business computer Science">Business computer Science</option> <option value="Business computer Science (Games)">Business computer Science (Games)</option> <option value="Business Information Systems">Business Information Systems</option> <option value="Digital Media Development">Digital Media Development</option> <option value="Digital Media">Digital Media</option> </select></p> <div align="centre"><input type="submit" name="submit" value="send request" /></div> //Validate course choice 1 if (!empty($_REQUEST['course1'])) { $course1 = $_REQUEST['course1']; } else { $course1 = NULL; echo '<p><font color="red">Please enter your first choice</font></p>'; } //Validate course choice 2 if (!empty($_REQUEST['course2'])) { $course2 = $_REQUEST['course2']; } else { $course2 = NULL; echo '<p><font color="red">Please enter your second choice</font></p>'; } //Validate course choice 3 if (!empty($_REQUEST['course3'])) { $course3 = $_REQUEST['course3']; } else { $course3 = NULL; echo '<p><font color="red">Please enter your third choice</font></p>'; } //If everything is ok, print the message if ($name && $email && $course1 && $course2 && $course3) { echo "<p>Thank you, <b>$name</b>, You have chosen the following courses for information:<br /><br /> <b>$course1</b><br /> <b>$course2</b><br /> <b>$course3</b></p> <p>We will reply to you at <i>$email</i>.</p>\n"; } else { // One form element was not filled out properly echo '<p><font color="red">Please go back and fill out the form again.</font></p>'; } I have a search function in php where the text characters are matched to characters in a tables field--- works perfectly.... I need to make the input box have a droplist of words from database, this is also easy for me to do. the problem here is there is no definitive value! the options list always outputs a blank in the url--- its supposed to search a matching value and then output the matching value to url... Here is the droplist code: $output['RATESTITLE']='<input class="inputbox" type="text" size="24px" name="ratestitle" value="'.$sch->filter['ratestitle'].'" onfocus="if (this.value ==\''.$output['LANGUAGE_SEARCH_RATESTITLE'].'\') {this.value = \'\'}" />'; this outputs a input text box--- i want to have a droplist of options to populate this text box... If you must know this is the third day im at it... Created a dynamic drop down box which pulls values from three columns from the database. However my insert function is not injecting the values in and i get an undefined index error. html> <div id = "form" align="center"> <h1> Create a repair Ticket </h1> <?php // Connects to Database mysql_connect("localhost", "bla", "bla") or die(mysql_error()); mysql_select_db("bla bla") or die(mysql_error()); ?> <form> <p> Choose the machine to be repaired: </p> <select> <?php // This query selects the machine_id and name from the machine table and stores in the "result" variable. $sql="SELECT machine_id,description FROM machine"; $result =mysql_query($sql); while ($data=mysql_fetch_assoc($result)) { echo ("<option value=".$data['machine_id'].">". $data['description']."</option>"); ?> <?php } ?> </select> <p> Choose the engineer to be allocated: </p> <select> <?php // This query selects engineer_id and name $sql="SELECT engineer_id,engineer_name FROM engineer"; $result =mysql_query($sql); while ($data=mysql_fetch_assoc($result)) { echo ("<option value=".$data['engineer_id'].">". $data['engineer_name']."</option>"); ?> <?php } ?> </select> <p> Choose the part to be allocated: </p> <select> <?php // This query selects the part_number and description $sql="SELECT part_number,description FROM parts"; $result =mysql_query($sql); while ($data=mysql_fetch_assoc($result)) { echo ("<option value=".$data['part_number'].">". $data['description']."</option>"); ?> <?php } ?> </select> <p> Reported By: <input type="text" name="reported_by" /> </p> <p><b>Fault Description</b> </p> <textarea cols="50" rows="4" name="fault_description" align="right" wrap="virtual"></textarea> </form> <form action="insert.php" method="post"> <input type="Submit"> </div> <?php ini_set("display_errors", "1"); error_reporting(E_ALL); $con = mysql_connect("localhost","bla","bla"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("bla", $con); $machine_id= $_POST['machine_id']; $reportedby= $_POST['reported_by']; $Date = date("d/m/y"); $fault_description =$_POST['fault_description']; $repaired_by = $_POST['engineer_name']; $part_used = $_POST['description']; $sql="INSERT INTO repairs (machine_number,reported_by,repair_start_date,fault description,repaired_by,part_used) VALUES ('".$machine_id."', '".$reportedby."','".$Date."','".$fault_description."','".$repairedby."','".$part_used."')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } mysql_close($con); echo "You records have been updated"; ?> I'm a newbie on php. I'm really a system administrator and I was just task to do this simple task. For me its hard but I'm sure for a programmer this is very simple. My agenda is to pull out data on one of my column in mysql, select it and dump it on mysql. Here is the php for retrieving mysql data Code: [Select] <?php function database_connect($users) { $resource_link = mysql_connect("localhost", "root", "root"); if (mysql_select_db($users, $resource_link)) { return $resource_link; } else { echo "Cannot connect to DB"; return false; } } function print_dropdown($query, $link){ $queried = mysql_query($query, $link); $menu = '<select username="username">'; while ($result = mysql_fetch_array($queried)) { $menu .= ' <option value="' . $result['id'] . '">' . $result['username'] . '</option>'; } $menu .= '</select>'; return $menu; } //Some other form elements, or just start a form. echo '<form method="post" action="create2.php">'; //The important bit echo print_dropdown("SELECT username FROM mailbox;", database_connect("users")); //Some other form elements, or just end the form. echo '<input type="submit" name="submit" value="submit"/></form>'; Here is the content of my create2.php. This is the php page who do the insert on my mysql. Code: [Select] <?php // open the connection $conn = mysql_connect("localhost", "root", "root"); // pick the database to use mysql_select_db("users",$conn); // create the SQL statement $sql2 = "INSERT INTO mailbox values ('','locked','','$_POST[username]','',NOW(),'','locked','')"; // for troubleshooting $result = mysql_query($sql2, $conn) or die(mysql_error()); // execute the SQL statement //if (mysql_query($sql2, $conn)) { // echo "Success"; //} else { // echo "Fail"; //} } ?> When I click the submit button, I don't see any record being inserted on my table. I'm using the create2.php on my other page though it is only an insert/fill up form not like this one that I need to pull up the date, select and insert to mysql. I'm trying to create a dynamic option menu with one alert selected based on the first query to the db. Any help would be greatly appreciated. Code: [Select] //function to get alerts and create select menu with current alerts pre-selected function getALERTS1($id){ require('db.php'); $alert = mysqli_query($conn, "SELECT alert1 FROM visit_data WEHERE patientid = $id AND discharged IS NULL"); $row = mysqli_fetch_array($alert); $selects=null; $query = mysqli_query($conn, "SELECT alertid, name FROM alerts"); while($row1 = mysqli_fetch_array($query)) { $selects .= "<option value=\"" . $row1['alertid'] . "\"> if($row1['alertid']==$row['alert1']) { echo ' selected'; } ".$row1['name']."</option>"; } return $selects; } I am trying to insert a date into a mySQL table from html drop downs with php. Right now when I enter the date it goes into the database as 0000-00-00. Can anybody see why it might be doing this? My html: Code: [Select] <label for='birthdate' >Birthdate (Optional):</label><br/> <select name='month' id='month' value='<?php echo $fgmembersite->SafeDisplay('month') ?>'> <option value="01" selected="January">January</option> <option value="02">February</option> <option value="03">March</option> etc... </select> <select name='day' id='day' value='<?php echo $fgmembersite->SafeDisplay('day') ?>'> <option value="01" selected="1">1</option> <option value="02">2</option> <option value="03">3</option> etc... </select> <select name='year' id='year' value='<?php echo $fgmembersite->SafeDisplay('year') ?>'> <option value="2010" selected="2010">2010</option> <option value="2009">2009</option> <option value="2008">2008</option> etc... </select> And my php to collect info: Code: [Select] $formvars['birthdate'] = $this->Sanitize($_POST['year'], $_POST['month'], $_POST['day']); php where I make table: Code: [Select] "birthdate DATE NOT NULL ,". php to insert into mysql: Code: [Select] $insert_query = 'insert into '.$this->tablename.'( name, address, birthdate, sex, program, guide, email, username, password, confirmcode ) values ( "' . $this->SanitizeForSQL($formvars['name']) . '", "' . $this->SanitizeForSQL($formvars['address']) . '", "' . $this->SanitizeForSQL($formvars['birthdate']) . '", "' . $this->SanitizeForSQL($formvars['sex']) . '", "' . $this->SanitizeForSQL($formvars['program']) . '", "' . $this->SanitizeForSQL($formvars['guide']) . '", "' . $this->SanitizeForSQL($formvars['email']) . '", "' . $this->SanitizeForSQL($formvars['username']) . '", "' . md5($formvars['password']) . '", "' . $confirmcode . '" )'; Thank you! I am simply trying to insert a value generated from an array in a while loop, but it seems the value is not global and I can't pass it as I like. I did some research on this, but could not find an answer that solved my issue... Here is my select box code which is working perfect: <select name="city"> <?php $sql = "SELECT id, city_name FROM cities ". "ORDER BY city_name"; $results_set = (mysqli_query($cxn, $sql)) or die("Was not able to produce the result set!"); while($row = mysqli_fetch_array($results_set)) { echo "<option value=$row[id]>$row[city_name]</option>"; } ?> </select> Are any variables defined in a while loop global to the while loop only? Here is my SQL which you can see my $row[id] being passed thru field city_id... The value is being generated as supposed to based on value like: value="1", value="2" etc.. for the select options for each city name. So the values are there... But I CANNOT get that numerical id to pass to the database when submitting my form. Any ideas for a workaround to get this value passing as normal? if (isset($_POST['addPosting'])) { $query = "INSERT INTO Postings (id, city_id, title, description) VALUES ('','$row[id]','$_POST[title]','$_POST[description]')"; I am trying to do an INSERT on my "bio_answer" table which is a junction table in between the "member" and "bio_question" tables. My PHP just tries to do the INSERT into "bio_answer" and doesn't touch the parent tables, which I assume is okay?! Here is a snippet of my code... if ($_SERVER['REQUEST_METHOD']=='POST'){ // Form was Submitted (Post). // Initialize Errors Array. $errors = array(); // Trim all form data. $trimmed = array_map('trim', $_POST); // ************************ // Validate Form Data. * // ************************ // Validate Answer1. if (strlen($trimmed['answer01']) >= 2 && strlen($trimmed['answer01']) <= 1024){ // Valid Answer1. $answerArray[0] = $trimmed['answer01']; $questionID = 1; echo '<p>$memberID = ' . $memberID . '</p>'; // Resolves to 19 which exists in the "member" table echo '<p>$questionID = ' . $questionID . '</p>'; // Resolves to 1 which exists in the "bio_question" table echo '<p>$answerArray[0] = ' . $answerArray[0] . '</p>'; // Resolves to whatever I type in my form, e.g. "This is a test..." }else{ // Invalid Answer1. $errors['question01'] = 'Answer must be 2-1024 characters.'; }//End of VALIDATE ANSWER1 // ****************************** // Attempt to Create Thoughts. * // ****************************** if (empty($errors)){ // Valid form data. // Build query. $q1 = "INSERT INTO bio_answer(member_id, question_id, response, created_on) VALUES(?, ?, ?, NOW())"; // Prepare statement. $stmt1 = mysqli_prepare($dbc, $q1); // Bind variables to query. mysqli_stmt_bind_param($stmt1, 'iis', $memberID, $questionID, $answerArray[0]); // Execute query. mysqli_stmt_execute($stmt1); // Verify Insert. if (mysqli_stmt_affected_rows($stmt1)==1){ // Insert Succeeded. $_SESSION['resultsCode'] = 'THOUGHTS_NEW_THOUGHTS_CREATED_2138'; }else{ // Insert Failed. $_SESSION['resultsCode'] = 'THOUGHTS_NEW_THOUGHTS_FAILED_2139'; }//End of UPDATE MEMBER RECORD // Close prepared statement. mysqli_stmt_close($stmt1); // Set Error Source. $_SESSION['errorPage'] = $_SERVER['SCRIPT_NAME']; // Redirect to Display Outcome. header("Location: " . BASE_URL . "/members/results.php"); // End script. exit(); }//End of ATTEMPT TO CREATE THOUGHTS My script keeps failing and errors to 'THOUGHTS_NEW_THOUGHTS_FAILED_2139' What is wrong with my Script/SQL?? Thanks, Debbie Hello PHP freaks. Having a few issues with my PHP scripts, specifically the $query = sprintf and mysql_real_escape_string functions. Kind of new to this, so if you do reply, explain it to me like I am a complete moron... Oh, before I forget. My specific problem is that I can click the "Post" button and follow the header to "Location: view.php", but the actual text in the Subject and Message fields is not being sent to the database. Finally managed to get rid of all the error messages I was getting, and now I get this... Thanks in advance! Here is my script for the entire page: _________________________________________________ ____________ <?php require_once('auth.php'); ?> <?php mysql_connect('xxxxxx', 'xxxxxx', 'xxxxxx'); $subject = $_POST['subject']; $message_text = $_POST['message_text']; // add entry to the databse if the form was submitted and // the necessary information was supplied in the form if (isset($_POST['submitted']) && $subject && $message_text) { $query = sprintf('INSERT INTO FORUM_MESSAGE (SUBJECT, MSG_TEXT) VALUES ($subject, $message_text)', Ryan_iframe, mysql_real_escape_string($subject), mysql_real_escape_string($message_text)); mysql_query($query); // redirect user to list of forums after new record has been stored header('Location: view.php'); } // form was submitted but not all the information was correctly filled in else if (isset($_POST['submitted'])) { $message = '<p>Not all information was provided. Please correct ' . 'and resubmit.</p>'; } ?> <!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=iso-8859-1" /> <title>Member Index</title> <link href="loginmodule.css" rel="stylesheet" type="text/css" /> </head> <body> <h1>Welcome <?php echo $_SESSION['SESS_FIRST_NAME'];?></h1> Home | <a href="member-profile.php">My Profile</a> | <a href="logout.php">Logout</a> <br /><br /> <form method="post"> <div> <label for="subject">Subject: </label> <input type="text" id="subject" name="subject" value="<?php echo htmlspecialchars($subject); ?>" /><br /> <label for="message_text">Message: </label> <input type="text" id="message_text" name="message_text" value="<?php echo htmlspecialchars($message_text); ?>" /><br /> <input type="hidden" name="submitted" value="true" /> <input type="submit" value="Post" /> </div> </form> </body> </html> hello, i am returning the error in the following code. im i doing something wrong? Code: [Select] { $sql = "UPDATE jobs SET contact = ' . mysql_real_escape_string{$_POST['contact']} .', contactphone = ' . mysql_real_escape_string{$_POST['contactphone']} .', customer = ' . mysql_real_escape_string{$_POST['customer']} .', initial = ' . mysql_real_escape_string{$_POST['initial']} .', address = ' . mysql_real_escape_string{$_POST['address']} .', city = ' . mysql_real_escape_string{$_POST['city']} .', postal = ' . mysql_real_escape_string{$_POST['postal']} .', province = ' . mysql_real_escape_string{$_POST['province']} .', description = ' . mysql_real_escape_string{$_POST['description']} .', mechanic = ' . mysql_real_escape_string{$_POST['mechanic']} .', ponumber = ' . mysql_real_escape_string{$_POST['ponumber']} .', status = ' . mysql_real_escape_string{$_POST['status']} .' WHERE id = '$id"; $result = mysql_query($sql) or die('Error, updating job failed. Check you fields and try again.'); echo "<center> You have successfully updated the new job. You can see your changes below."; } EvilSpider 123456 FakeEmail@yahoo.com Connected successfullyYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@yahoo.com)' at line 2 mysql_query("INSERT INTO user (username, password,email) VALUES($user, $pass, $email) ") and when i dont do the @ sign i still get the error EvilSpider 123456 FakeEmail Connected successfully Unknown column 'EvilSpider' in 'field list' Can anyone help me out with this. I have been struggling on and off it for weeks. Heres the description of the problem. I insert into a MySQL database from a query that is performed using an array that is posted from a page. The incoming array contains selected users (unique id's) that are used to lookup the users telephone numbers in a query and then insert into a DB. This code works intermittently. It will insert the records fine and then on the next attempt it may not? There is not pattern to it working and failing. Does anyone have any idea why this is happening? I have tried a loop using the posted array data count and also a loop based on the count of records brought back from the query but to no avail, it is still intermittently working. The '$stripped_message' data is just a text string. Code: [Select] <?php $date = date('Y-m-d H:i:s'); for ($i=0;$i<count($_POST['recipient']);$i++) // loop based on count of selected users $uk_mob_number = "44".substr($row_selected_recipients['User_mobile'], 1); // take off the first digit and replace with 44 $unique = makeRandomstring(); // Create a unique string for each entry $values.="('$unique','$date','$stripped_message','$uk_mob_number','sent','$date','$userid'),"; // usleep(50000); // Tried a delay to try to fix, did not work } // End of loop $values=substr($values,0,-1); // to remove last comma $query="INSERT INTO `sms` (`sms_unique`, `sms_sent`, `sms_body`, `sms_to`, `sms_status`, `sms_db_entry_time`, `sms_user`) VALUES $values".";"; ?> I have no idea and there is no reason why this should not be working. im simply trying to add three variables into a database, and only one works. the other two do not work for any reason i can find. can someone point out my error, if any? code: <?php $date = date("Y-m-d"); $dbc = mysqli_connect('localhost', 'root', '', 'timer') or die('Error connecting to DB'); $query = @"INSERT INTO sessions (date, user, sessiontime) VALUES ('$date', '$user', '$sessiontime')"; $user = @$_GET['user']; $sessiontime = @$_GET['clock']; if (@$_GET['addDB'] == "Session Complete") { mysqli_query($dbc, $query) or die( '<br>Query string: ' . $query . '<br>Produced error: ' . mysqli_error($dbc) ); } ?> Form: Code: [Select] <label for="user"><b><em>Your name: </b></em></label><br /><input type="text" name="user" value="Admin/User" /> <input id="clock" name="clock" type="text" value="00:00:0" readonly><br> <input id="startstopbutton" type="button" value="S t a r t" onClick="startstop();" style="font-weight:bold"><br> <input type="submit" name="addDB" value="Session Complete" /> See, all the variables match up!? I dont get what im doing wrong? my SQL Query wont execute on on following lines: Code: [Select] $result = mysql_query("INSERT INTO 'gallery' ('image', 'memberid', 'caption') VALUES ('$newFileName', '$member_id', '$caption')") or die (mysql_error()); i get the following error: Code: [Select] 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 ''gallery' ('image', 'memberid', 'caption') VALUES ('gallery/9074849_1.jpg', '1',' at line 1 here is my full code: Code: [Select] <?php require_once('connect.php'); $rand = mt_rand(1,9999999); $rand2 = mt_rand(1,9999999); $member_id = $_SESSION['SESS_MEMBER_ID']; $caption = $_POST["caption"]; if(isset($_FILES['uploaded']['name'])) { $allowed_filetypes = array('.jpg','.gif','.bmp','.png','.jpeg'); $max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB) $fileName = basename($_FILES['uploaded']['name']); $errors = array(); $target = "gallery/"; $fileBaseName = substr($fileName, 0, strripos($fileName, '.')); // Get the extension from the filename. $ext = substr($fileName, strpos($fileName,'.'), strlen($fileName)-1); //$newFileName = md5($fileBaseName) . $ext; $newFileName = $target . $rand . "_" . $member_id.$ext; // Check if filename already exists if(file_exists("gallery/" . $newFileName)) { $errors[] = "The file you attempted to upload already exists, please try again."; } // Check if the filetype is allowed. if(!in_array($ext,$allowed_filetypes)) { $errors[] = "The file you attempted to upload is not allowed."; } // Now check the filesize. if(!filesize($_FILES['uploaded']['tmp_name']) > $max_filesize) { $errors[] = "The file you attempted to upload is too large."; } // Check if we can upload to the specified path. if(!is_writable($target)) { $errors[] = "You cannot upload to the specified directory, please CHMOD it to 777."; } //Here we check that no validation errors have occured. if(count($errors)==0) { //Try to upload it. if(!move_uploaded_file($_FILES['uploaded']['tmp_name'], $newFileName)) { $errors[] = "Sorry, there was a problem uploading your file."; } } //Lets INSERT database information here //Here we check that no validation errors have occured. if(count($errors)==0) { $result = mysql_query("INSERT INTO 'gallery' ('image', 'memberid', 'caption') VALUES ('$newFileName', '$member_id', '$caption')") or die (mysql_error()); { $errors[] = "SQL Error."; } } //If no errors show confirmation message if(count($errors)==0) { echo "<div class='notification success png_bg'> <a href='#' class='close'><img src='img/cross_grey_small.png' title='Close this notification' alt='close' /></a> <div> The file {$newFileName} has been uploaded<br>\n </div> </div>"; //echo "The file {$fileName} has been uploaded"; echo "<br>\n"; echo "<a href='gallery.php'>Go Back</a>\n"; } else { //show error message echo "<div class='notification attention png_bg'> <a href='#' class='close'><img src='img/cross_grey_small.png' title='Close this notification' alt='close' /></a> <div> Sorry your file was not uploaded due to the following errors:<br>\n </div> </div>"; //echo "Sorry your file was not uploaded due to the following errors:<br>\n"; echo "<ul>\n"; foreach($errors as $error) { echo "<li>{$error}</li>\n"; } echo "</ul>\n"; echo "<br>\n"; echo "<a href='gallery.php'>Go Back</a>\n"; } } else { //Show the form echo "Use the following form below to add a new image to your gallery;<br />\n"; echo "<form enctype='multipart/form-data' action='' method='POST'>\n"; echo "Please choose a file: <input name='uploaded' type='file' /><br />\n"; echo "Caption: <input name='caption' type='text' /><br />\n"; echo "<input type='submit' value='Upload' />\n"; echo "</form>\n"; //Echo Tests! echo "<br /><br />Random FileName: "; echo $rand; echo "<br />"; echo "member ID: #"; echo $member_id; } ?> any help appreciated. its prob something simple. my table has the following fields: "gallery" id (primary Key, AUTO_INC) memberid (fetched from session) image (will store image name including extension) caption (from "caption" text field in form) I have a mysql insert statement generated with php that is not populating the table. I've echoed the statement and if I copy and paste into phpmyadmin it works fine. The result of the mysql_query function is true. I've emptied the table so there are no primary key conflicts. I've put the statement in a try catch and it does not display a exception. What else can I try? Here's the statement INSERT INTO `wp_term_relationships` (object_id, term_taxonomy_id, term_order) VALUES (1597,83,0) Works absolute fine if I copy and paste into phpmyadmin. Does not populated the table if run through mysql_query <?php error_reporting(E_ALL^E_NOTICE); $connect = mysqli_connect("");//removed $doc = $_GET["doctor"]; $username = $_GET["username"]; $sql = "SELECT fname, lname from newpatient where username = '$username'"; $result = mysqli_query($connect, $sql); $value = mysqli_fetch_row($result); $fname = $value[0]; $lname = $value[1]; $totalcost = $_GET["totalcost"]; $reason1 = $_GET["reason1"]; $reason2 = $_GET["reason2"]; $reason3 = $_GET["reason3"]; $reason4 = $_GET["reason4"]; $reason5 = $_GET["reason5"]; $reason6 = $_GET["reason6"]; $reason7 = $_GET["reason7"]; $reason8 = $_GET["reason8"]; $date = $_GET["date"]; $reasons = array($reason1,$reason2,$reason3,$reason4,$reason5,$reason6,$reason7,$reason8); rsort($reasons); $reason1 = $reasons[0]; $reason2 = $reasons[1]; $reason3 = $reasons[2]; $reason4 = $reasons[3]; if(isset($_REQUEST["yes"])) { $sql1 = "SELECT * FROM appointments where doctor_name = '$doc' and time = '$time'"; $result1 = mysqli_query($connect, $sql1); $num_rows = mysqli_num_rows($result1); if($num_rows > 0) { echo "Appointment Time already chosen. Select another time."; echo "<script language = 'javascript'>document.location.href='make_appointment.php?doc=$doc&username=$username'</script>"; } else { $sql2 = "INSERT INTO appointments (username, time, doctor_name, cost, reason1_for_visit, reason2_for_visit,reason3_for_visit,reason4_for_visit, fname, lname) values ('$username','$date','$doc',$totalcost,'$reason1','$reason2','$reason3','$reason4','$fname','$lname')"; $result2 = mysqli_query($connect, $sql2); if($result2) echo "This worked."; else echo "Insert did not work."; //echo "<script language = 'javascript'>document.location.href='registered_login_page.php?username=$username'</script>"; } } mysqli_close($connect); ?> I have a class built for an INSERT query but it is passing two sets of records into the database rather than one. Code: [Select] class DatabaseInsert { function DatabaseConnectionRequire() { include("../scrips/php/database.connection.class.php"); include("../scrips/php/database.settings.php"); include("../scrips/php/database.connection.class.invoke.php"); } function ArticleInsert($values,$fields,$table) { $values_imploded = implode(" ",$values); $fields_imploded = implode(" ",$fields); $i = "INSERT INTO $table ($fields_imploded) VALUES ($values_imploded)"; mysql_query($i) or die(mysql_error()); if (!mysql_query($i)) { echo "Sorry, something whent wrong there..."; } else { echo "<strong><p style='color:green;'>Content added sucessfully!!!</p></strong>"; } } } Hello all, so I created an insert function and it seems no matter what I try that it won't add values using the query function inside a table from the respective variables, I would like to know why is this happening? Here is the code can you tell me why it doesn't insert anything in the database? It shows no errors when it runs but then again when I check the tables they're empty!
function insert(){ $user = $_POST['user']; $pass = md5($_POST['pass']); $priv = "User"; $mail = $_POST['mail']; $avatar = $_FILES['avatar']['name']; $date="now()"; $submit = $_POST['submit']; $query = "INSERT INTO user(user,pass,priv,mail,avatar,date) VALUES(`$user`,`$pass`,`$priv`,`$mail`,`$avatar`,`$date`);"; if($submit){ $res = mysqli_query($con,$query) or die(mysqli_error($con)); } } |