PHP - Mysql Insert Code Not Working.
Hello everybody, I can't seem to figure out why this insert code isn't working. I'm trying to create a database of US zip codes. I created this user interface (form) with nothing but a submit button to execute the insert query
<div id="right_content" class=""> <h3> Insert Zips </h3> <form action = "insertzip1.php" method = "post"> <input type = "submit" name = "submit" value = "submit"/> </form> </div> <!--closes right content--> Well here is the insert query which is supposed to accomplish the task. I have just included a tiny subsets of all the zipcodes (the insertzip1.php page which is the value of the action attribute of the form). <php? if (isset($_POST['submit'])) { require ('config.php'); $query = "INSERT INTO zips (zip, lat, lon, city, state, county, z_type, xaxis, yaxis, zaxis, z_primary, worldregion, country, locationtext, location, population, housingunits, income, landarea, waterarea, decommisioned, militaryrestrictioncodes, decommisionedplace) VALUES ('00501', 40.81, -73.04, 'HOLTSVILLE', 'NY', 'SUFFOLK', 'UNIQUE', 0.22, -0.72, 0.65, 'Yes', 'NA', 'US', 'Holtsville, NY', 'NA-US-NY-HOLTSVILLE', '', 0, 0, '', '', 'No', '', ''), ('00501', 40.81, -73.04, 'I R S SERVICE CENTER', 'NY', 'SUFFOLK', 'UNIQUE', 0.22, -0.72, 0.65, 'No', 'NA', 'US', 'I R S Service Center, NY', 'NA-US-NY-I R S SERVICE CENTER', '', 0, 0, '', '', 'No', '', ''), ('00544', 40.81, -73.04, 'HOLTSVILLE', 'NY', 'SUFFOLK', 'UNIQUE', 0.22, -0.72, 0.65, 'Yes', 'NA', 'US', 'Holtsville, NY', 'NA-US-NY-HOLTSVILLE', '', 0, 0, '', '', 'No', '', ''), ('00544', 40.81, -73.04, 'IRS SERVICE CENTER', 'NY', 'SUFFOLK', 'UNIQUE', 0.22, -0.72, 0.65, 'No', 'NA', 'US', 'Irs Service Center, NY', 'NA-US-NY-IRS SERVICE CENTER', '', 0, 0, '', '', 'No', '', '') "; $result = mysql_query($query); header("Location: insertzipsuccess.php"); }else{ die ("Could not insert data because" . mysql_error());} ?> The insertzipsuccess.php page is simply a page that prints out a success message if the query is successfully executed. Well when I hit the submit button, I just get redirected to a blank insertzip1.php page Can anyone show me what I'm not doing right here? PS I already created the table with fields that correspond to all the fields I'm trying insert. Similar TutorialsI 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 I am trying to insert a record into a mysql database which has a $ as part of the value of a field. But it seems that when the INSERT query is processed its actually looking for a variable with that name and not just inserting the raw text. Here is the insert query $query = "INSERT mytable SET myfield='I would like to have this field contain this information with a $matches[1] showing in the field value as well'"; $matches[1] has no value. Its not a variable which is in this script. I am not trying to insert the value of it. I just want to insert the actual text characters $matches[1] How can I do that? Code: [Select] <?php require "db/config.php"; $fname = $_POST['fname']; $lname = $_POST['lname']; $country = $_POST['country']; $state = $_POST['state']; $city = $_POST['city']; $zcode = $_POST['zcode']; $address = $_POST['address']; $ppemail = $_POST['ppemail']; $pnumber = $_POST['pnumber']; $cemail = $_POST['cemail']; $url = $_POST['url']; $price = "$5.00"; $query = "INSERT INTO custpackage1000( id, FirstName, LastName, Country, State, City, ZipCode, Address, PayPalEmail, PhoneNumber, PrimaryEmail, WebsiteURL) VALUES ( '1', '$fname', '$lname', '$country', '$state', '$city', '$zcode', '$ppemail', '$pnumber', '$cemail', '$url')"; mysql_connect($host, $user, $pass) or die("<br /><br /><h1>Fatal error. Please contact support if this persists.</h1>"); mysql_select_db($dbname); mysql_query($query) or die ("could not open db".mysql_error()); sleep(2); ?> Why won't the code insert into my database upon submission of data? What am I doing wrong? Can anyone tell me why this is not INSERTing? My array data is coming out just fine.. I've tried everything I can think of and cannot get anything to insert.. Ahhhh! <?php $query = "SELECT RegionID, City FROM geo_cities WHERE RegionID='135'"; $results = mysqli_query($cxn, $query); $row_cnt = mysqli_num_rows($results); echo $row_cnt . " Total Records in Query.<br /><br />"; if (mysqli_num_rows($results)) { while ($row = mysqli_fetch_array($results)) { $insert_city_query = "INSERT INTO all_illinois SET state_id=$row[RegionID], city_name=$row[City] WHERE id = null" or mysqli_error(); $insert = mysqli_query($cxn, $insert_city_query); if (!$insert) { echo "INSERT is NOT working!"; exit(); } echo $row['City'] . "<br />"; echo "<pre>"; echo print_r($row); echo "</pre>"; } //while ($rows = mysqli_fetch_array($results)) } //if (mysqli_num_rows($results)) else { echo "No results to get!"; } ?> Here is my all_illinois INSERT table structu CREATE TABLE IF NOT EXISTS `all_illinois` ( `state_id` varchar(255) NOT NULL, `city_name` varchar(255) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; Here is my source table geo_cities structu CREATE TABLE IF NOT EXISTS `1` ( `CityId` varchar(255) NOT NULL, `CountryID` varchar(255) NOT NULL, `RegionID` varchar(255) NOT NULL, `City` varchar(255) NOT NULL, `Latitude` varchar(255) NOT NULL, `Longitude` varchar(255) NOT NULL, `TimeZone` varchar(255) NOT NULL, `DmaId` varchar(255) NOT NULL, `Code` varchar(255) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; Hi, I need to insert some code into my current form code which will check to see if a username exist and if so will display an echo message. If it does not exist will post the form (assuming everything else is filled in correctly). I have tried some code in a few places but it doesn't work correctly as I get the username message exist no matter what. I think I am inserting the code into the wrong area, so need assistance as to how to incorporate the username check code. $sql="select * from Profile where username = '$username'; $result = mysql_query( $sql, $conn ) or die( "ERR: SQL 1" ); if(mysql_num_rows($result)!=0) { process form } else { echo "That username already exist!"; } the current code of the form <?PHP //session_start(); require_once "formvalidator.php"; $show_form=true; if (!isset($_POST['Submit'])) { $human_number1 = rand(1, 12); $human_number2 = rand(1, 38); $human_answer = $human_number1 + $human_number2; $_SESSION['check_answer'] = $human_answer; } if(isset($_POST['Submit'])) { if (!isset($_SESSION['check_answer'])) { echo "<p>Error: Answer session not set</p>"; } if($_POST['math'] != $_SESSION['check_answer']) { echo "<p>You did not pass the human check.</p>"; exit(); } $validator = new FormValidator(); $validator->addValidation("FirstName","req","Please fill in FirstName"); $validator->addValidation("LastName","req","Please fill in LastName"); $validator->addValidation("UserName","req","Please fill in UserName"); $validator->addValidation("Password","req","Please fill in a Password"); $validator->addValidation("Password2","req","Please re-enter your password"); $validator->addValidation("Password2","eqelmnt=Password","Your passwords do not match!"); $validator->addValidation("email","email","The input for Email should be a valid email value"); $validator->addValidation("email","req","Please fill in Email"); $validator->addValidation("Zip","req","Please fill in your Zip Code"); $validator->addValidation("Security","req","Please fill in your Security Question"); $validator->addValidation("Security2","req","Please fill in your Security Answer"); if($validator->ValidateForm()) { $con = mysql_connect("localhost","uname","pw") or die('Could not connect: ' . mysql_error()); mysql_select_db("beatthis_beatthis") or die(mysql_error()); $FirstName=mysql_real_escape_string($_POST['FirstName']); //This value has to be the same as in the HTML form file $LastName=mysql_real_escape_string($_POST['LastName']); //This value has to be the same as in the HTML form file $UserName=mysql_real_escape_string($_POST['UserName']); //This value has to be the same as in the HTML form file $Password= md5($_POST['Password']); //This value has to be the same as in the HTML form file $Password2= md5($_POST['Password2']); //This value has to be the same as in the HTML form file $email=mysql_real_escape_string($_POST['email']); //This value has to be the same as in the HTML form file $Zip=mysql_real_escape_string($_POST['Zip']); //This value has to be the same as in the HTML form file $Birthday=mysql_real_escape_string($_POST['Birthday']); //This value has to be the same as in the HTML form file $Security=mysql_real_escape_string($_POST['Security']); //This value has to be the same as in the HTML form file $Security2=mysql_real_escape_string($_POST['Security2']); //This value has to be the same as in the HTML form file $sql="INSERT INTO Profile (`FirstName`,`LastName`,`Username`,`Password`,`Password2`,`email`,`Zip`,`Birthday`,`Security`,`Security2`) VALUES ('$FirstName','$LastName','$UserName','$Password','$Password2','$email','$Zip','$Birthday','$Security','$Security2')"; //echo $sql; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } else{ mail('email@gmail.com','A profile has been submitted!',$FirstName.' has submitted their profile',$body); echo "<h3>Your profile information has been submitted successfully.</h3>"; } mysql_close($con); $show_form=false; } else { echo "<h3 class='ErrorTitle'>Validation Errors:</h3>"; $error_hash = $validator->GetErrors(); foreach($error_hash as $inpname => $inp_err) { echo "<p class='errors'>$inpname : $inp_err</p>\n"; } } } if(true == $show_form) { ?> Hello, I'm having a bit of a problem here, all help to this issues would be much appreciated I am trying to use text boxes to insert numbers into the database based on what is inputed. If I have a string, like this for example: $variable = 09385493; And I want to insert it into the database like this: mysql_query("INSERT INTO integers(number) VALUES ('$variable')"); When checking the integers table in my database, looking at the number field, the $variable that was inserted is outputted as 9385493 Notice the number zero was taken out of the front of the number. If the number is double 0's (009385493), both of those zero's would disappear, too. Thanks I use this type of a code to send automatic emails from my website: Code: [Select] $headers = ; $headers .= ; $to = ; Click here to go to Google. ", $headers); I am having hard time figuring out how to do hyperlink on words (like here). If I do something like this: Code: [Select] <a href='http://www.google.com'>here</a> it spits out that exact thing out. Thanks you for your input 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> 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' 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."; } 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 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)); } } 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? 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>"; } } } 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) <?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); ?> Basically I need to input data into two tables. I am running 3 different query's but only 2 of them work. The other one doesn't. None working query: mysql_query("INSERT INTO users(username, password, email, pin, key) VALUES('$username', '$password', '$email', '$key', '$pin')"); Working querys: mysql_query("DELETE FROM beta_keys WHERE keys_new='$key'"); **and** mysql_query("INSERT INTO beta_keys(keys_used) VALUES('$key')"); So any ideas why the top one doesn't work but the bottom two do? 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".";"; ?> Hi guys I have a registration form working fine, my database is as below: userid username password repeatpassword I have added another column which is "name", users can update their profile once they have logged in so I have created updateprofile.php and when I login-->go to update profile and insert my name nothing adds to mysql name column this is my code below: <?php include ("global.php"); //username session $_SESSION['username']=='$username'; $username=$_SESSION['username']; //welcome messaage echo "Welcome, " .$_SESSION['username']."!<p>"; if ($_POST['register']) { //get form data $name = addslashes(strip_tags($_POST['name'])); $update = mysql_query("INSERT INTO users (name) VALUES ('$_POST[name]') WHERE username='$username'"); } ?> <form action='updateprofile.php' method='POST'> Company Name:<br /> <input type='text' name='name'><p /> <input type='submit' name='register' value='Register'> </form> can you please tell me where in this code is wrong? Im new in php so please excuse me if I have silly mistakes. thanks in advance |