PHP - Dymanic Drop Down Box / Insert
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"; ?> Similar TutorialsI'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. Sorry got it! my apologizes 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]')"; 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; I'm missing something here. I have a form, and when the submit is pressed, the relevant post data inserts into table one, then I want the last insert id to insert along with other form data into a second table. The first table's still inserting fine, but I can't get that second one to do anything. It leapfrogs over the query and doesn't give an error. EDIT: I forgot to add an error: I get: 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 'usage, why VALUES ('14', '', '123', '','1234', '', '')' at line 1 query:INSERT INTO tbl_donar (donar_fname, donar_name, donar_address, donar_address2, donar_city, donar_state, donar_zip, donar_email, donar_phone, donar_fax, donar_company) VALUES ('test 14', 'asdfa', 'asdf', 'adf','asdf', '', '', '', '123', '', '') Code: [Select] if (empty($errors)) { require_once ('dbconnectionfile.php'); $query = "INSERT INTO tbl_donar (donar_fname, donar_name, donar_address, donar_address2, donar_city, donar_state, donar_zip, donar_email, donar_phone, donar_fax, donar_company) VALUES ('$description12', '$sn', '$description4', '$cne','$description5', '$description6', '$description7', '$description8', '$description9', '$description10', '$description11')"; $result = @mysql_query ($query); if ($result) { $who_donated=mysql_insert_id(); $query2 = "INSERT INTO tbl_donation (donor_id, donor_expyear, donor_cvv, donor_cardtype, donor_authorization, amount, usage, why) VALUES ('$who_donated', '$donate2', '$donate3', '$donate4','$donate5', '$donate6', '$donate7')"; $result2 = @mysql_query ($query2); if ($result2) {echo "Info was added to both tables! yay!";} echo "table one filled. Table two was not."; echo $who_donated; //header ("Location: http://www.twigzy.com/add_plant.php?var1=$plant_id"); exit(); } else { echo 'system error. No donation added'; 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 Hi All, I have 2 tables: one CarMake - CarMakeID - CarMakeDesc two CarModel - CarModelID - CarModelMake - CarModelDesc Depending on what the user selects in the first dropdown (carmake) the possible selection in the second dropdown (model) needs to be limited to only the models from the selected carmake. in the second table (Carmodel : the 'CarModelMake' = CarMakeID, to identify the make) How do I limit the dropdown 'CarModel' based on the selected CarMake in the first dropdown. link : http://98.131.37.90/postCar.php code : -- -- -- Code: [Select] <label> <select name="carmake" id="CarMake" class="validate[required]" style="width: 200px;"> <option value="">Select CAR MAKE...</option> <?php while($obj_queryCarMake = mysql_fetch_object($result_queryCarMake)) { ?> <option value="<?php echo $obj_queryCarMake->CarMakeID;?>" <?php if($obj_queryCarMake->CarMakeID == $CarAdCarMake) { echo 'selected="selected"'; } ?> > <?php echo $obj_queryCarMake->CarMakeDesc;?></option> <?php } ?> </select> </label> <label> <select name="carmodel" id="CarModel" class="validate[required]" style="width: 200px;"> <option value="">Select MODEL...</option> <?php while($obj_queryCarModel = mysql_fetch_object($result_queryCarModel)) { ?> <option value="<?php echo $obj_queryCarModel->CarModelID;?>" <?php if($obj_queryCarModel->CarmodelID == $CarAdCarModel) { echo 'selected="selected"'; } ?> > <?php echo $obj_queryCarModel->CarModelDesc;?></option> <?php } ?> </select> </label> I'm a novice.. and appreciates all the help ! I am creating a form that will allow the user to select the make of vehicle "FORD" for example. If that make of vehicle is selected among different makes of vehicles, then another box will appear, with all the models for that particular model "Fiesta" for example. What type of code accomplishes this setup in my web page? I do not want to list 500 models in one drop down list, but just those for each make in the first drop down list. Thanks much! hi; Code: [Select] $giden = $_GET['sehir_part']+1; $url = '31.php?sehir_part='.$giden.''; //$erkek_top = 7 for($q=1;$q<=7;$q++) { //i want insert into to mysql in here ; but its doing only one inserting so i want be 7 more insert } header( 'refresh:1;url=31.php?sehir_part='.$giden)and in every page loading i want inserting to mysql againg pls helpme thanks I'm trying to use PDO and get used to doing things this way. I've been away from php/mysql for a few years, so, I'm crusty. I'm not getting any error messages back on this code, but the insert just doesn't happen. My first guess is that I'm doing something wrong with the datetime now() function. But, I may not have the PDO code right. I tried the script the old fashion way with mysql_query() and that worked. So, it has to be something in this code. I believe my server is set up to do PDO as it shows: PDO PDO support enabled PDO drivers mysql, sqlite pdo_mysql PDO Driver for MySQL, client library version 5.0.45 My php version is 5.2.14 and Mysql is 5.0.45. Any help would be appreciated. Code: [Select] $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); $sql=$DBH->prepare("INSERT INTO assets(asset_name,date_added,short_desc) VALUES (:asset_name,NOW(),:short_desc)"); $sql->bindParam(':asset_name',$asset_name); $sql->bindParam(':short_desc',$short_desc); $name=$_POST["input1"]; $short_desc=$_POST["input2"]; $DBH->exec(); echo $name; echo "\nPDO::errorInfo():\n"; print_r($DBH->errorInfo()); } catch(PDOException $e) { echo "Syntax Error: ".$e->getMessage(); } Hello!Is this correct? Code: [Select] $sql="INSERT INTO pacienti (nume, prenume, cnp, varsta, sex, casa_asigurari, oras, strada, numar, judet, data_inregistrarii) VALUES ('$_POST[nume]','$_POST[prenume]','$_POST[CNP]','$_POST[varsta]','$_POST[sex]','$_POST[casa]','$_POST[oras]','$_POST[strada]','$_POST[nr]','$_POST[judet]','$_POST[internare]')"; $sql="INSERT INTO diagnostic (nume) VALUES ('$_POST[diagnostic]')"; and i mean..if i can do 2 insert in 2 different tables...or how can i do this? Just a quick question I have a form, couple of drop down boxes, input fields etc.. at the end is the submit button. now my question is should my insert into database sqls go before the submit button inside the form? out side the form? after the button inside the form? If by any chance you could give me some advice on the best way to layout my sql that would be great. They are big and go into three tables, at the moment I have them as three seperate queries but I think they must be able to go into one. can someone please help me with the layout and syntax. here is what the queries look like at the moment: if ($IBselect=$_POST ['IBselect']); { //CUSTOMER $enterCust="INSERT INTO customer(username, password, title, firstName, lastName, address, town, country, postCode, phone, email, dateCust) VALUES ('$_POST[username]', '$_POST[password]', '$_POST[title]', '$_POST[firstName]', '$_POST[lastName]', '$_POST[address]', '$_POST[town]', '$_POST[country]', '$_POST[postCode]', '$_POST[phone]', '$_POST[email]', 'DATE: Auto CURDATE()', CURDATE()"; $enterCust_query=mysql_query($enterCust)or die(mysql_error()); //CARD $enterCard="INSERT INTO card(cardNumber, name, expDate, cardID) VALUES ('$_POST[cardNumber]','$_POST[name]', ' $_POST[expDate]', '$_POST[cardID]')"; $enterCard_query=mysql_query($enterCard); //BOOKING $RCenterBook=mysql_query("INSERT INTO booking (custNumber, cardID, rideName, seatNo1, seatNo2, price, price2, dateBook, ID_time_tbl) VALUES ('$custNumber', '$_POST[cardID]', '$rideName', '$_SESSION[IBextract]', '$_SESSION[IBextract2]', '$IBendPrice1', '$IBendPrice2', 'DATE: Auto CURDATE()', CURDATE()', '$_SESSION[IB_slot_Time]'"); $IBenterBooking_query=mysql_query($IBenterBook); if (!mysql_query($enterCard, $enterCust, $IBenterBook)) { die("Error:" .mysql_error()); } echo "1 record added IB"; } Thanks =) I get the following message: Quote name4Query failed: Unknown column 'late' in 'field list' with this code. What does it mean? Code: [Select] <?php $apt=$_POST['search_term']; $stat = mysql_connect("localhost","root",""); $stat = mysql_select_db("prerentdb"); $query = "SELECT name FROM payments WHERE late = 'L'"; $stat = @mysql_fetch_assoc(mysql_query($query)); echo $stat["name"]; $name=$_POST['name']; $apt=$_POST['apt']; $amtpaid=$_POST['amtpaid']; $rentdue=$_POST['rentdue']; $prevbal=$_POST['prevbal']; $hudpay=$_POST['hudpay']; $tentpay=$_POST['tentpay']; $datepaid=$_POST['datepaid']; $late=$_POST['late']; $comments=$_POST['comments']; $paidsum=$_POST['paidsum']; $query = " INSERT INTO payhist (name,apt,amtpaid,rentdue,prevbal, hudpay,tentpay,datepaid,late,comments,paidsum) VALUES('$name','$apt','$amtpaid','$rentdue','$prevbal', '$hudpay','$tentpay','$datepaid','$late','$comments','$paidsum')"; $stat = mysql_query($query) or die('Query failed: ' . mysql_error()); mysql_close(); echo "data inserted<br /><br />"; ?> hey developers,
i have problem to get last insert id. btw.. i try to put that code on my mvc creation.
on register_model page i write like this:
public function numbering(){ $sth = $this->db->prepare('SELECT * FROM member_data'); $result = $this->db->lastInsertId(); return $result; } and for the controllers page, i write the code like this: $c = $this->model->numbering(); foreach ($c as $key => $value) { $data = $result('id'); } $abc['member_id'] = $data; but i didn't get the results,.. can you help me? Dear Sir/Madame I am trying to insert comments into a table called comments using echo ID in the input form but so far i can insert the comments with the post id but unable re-comment again kindly help me what do i do? This is the input form: <div> <form action="ehscomment.php" method="post"> <input type="hidden" name="id" value="<?php echo $id ?>"> <div> <label>Add comment</label> <div> <textarea rows="6" cols="110" name="comment" placeholder="comment"></textarea> </div> </div> <input type="submit" name="postcomment" value="comment"></form> </div> And this is ehscomment.php <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "registration"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } if(isset($_POST['postcomment'])){ $id = $_POST['id']; $comment = $_POST['comment']; $sql = "INSERT INTO comments (id,comment) VALUES ('$id','$comment')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close();} ?>
Error message: Error: INSERT INTO comments (id,comment) VALUES ('242','asddd') I am working with a insert query... Code: [Select] $query="INSERT INTO user_info_more (website) VALUES ('".$website."') WHERE id='$_SESSION[id]'"; mysql_query($query) or die ('Unable to register an account with following details 1'); but the output is " Unable to register an account with following details 1" Basically i have a row with 6 cloumns in mysql database in which only the id column and name column is filled... Now i want to insert $website in the "website" column of the database... Neither i can update as the website column initially is null... I do not know what to do.... A lot of cnfusion Not being able to upload images in the directory with a path name in the database? 1) This is my code for insert into the database and directory: <?php $host="localhost"; $username="root"; $pass=""; $db="registration"; $conn=mysqli_connect($host,$username,$pass,$db); if(!$conn){ die("Database connection error"); } // insert query for register page if(isset($_POST['ronel'])){ $images = $_FILES['file']['name']; $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["file"]["name"]); // Select file type $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Valid file extensions $extensions_arr = array("jpg","jpeg","png","gif","pdf"); // Check extension if( in_array($imageFileType,$extensions_arr) ) { $details=$_POST['details']; $location=$_POST['location']; $checkbox=$_POST['checkbox']; $injured=$_POST['injured']; $agegender=$_POST['agegender']; $contact=$_POST['contact']; $empid=$_POST['empid']; $dept=$_POST['dept']; $organization=$_POST['organization']; $summary=$_POST['summary']; $name=$_POST['name']; $outcome=$_POST['outcome']; $cause=$_POST['cause']; $action=$_POST['action']; $reportedname=$_POST['reportedname']; $position=$_POST['position']; $organisation=$_POST['organisation']; $reportedcontact=$_POST['reportedcontact']; $reporteddept=$_POST['reporteddept']; $status="Pending"; $comment=$_POST['comment']; $query="INSERT INTO `proposals` (`details`,`location`,`date`,`time`,`checkbox`,`injured`,`agegender`,`contact`,`empid`,`dept` ,`organization`,`summary`,`image`,`outcome`,`cause`,`action`,`reportedname`,`position`,`organisation`,`reportedcontact`,`reporteddept`,`status`,`comment`) VALUES ('$details','$location', current_timestamp(),current_timestamp(),'$checkbox','$injured','$agegender','$contact','$empid','$dept' ,'$organization','$summary','$name','$outcome','$cause','$action','$reportedname','$position','$organisation','$reportedcontact','$reporteddept','$status','$comment')"; $res=mysqli_query($conn,$query); if($res){ $_SESSION['success']="Not Inserted successfully!"; header('Location:'); }else{ echo "<script>alert('Proposal not applied!');</script>"; } // Upload file move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$image); } } date_default_timezone_set("Asia/Kolkata"); ?> 2) Here is the input file: <form class="form-horizontal" method="post" action="" enctype="multipart/form-data"> <input type="hidden" name="ronel" value=""> <div class="form-group"> <label style="position:absolute; left:63%; top:425px;" for="inputEmail" class="col-lg-3"><b>Upload Images Here :</b></label><br><br> <div class="col-lg-9"> <input style="position:absolute; left:78%; top:420px;" type="file" name="file" enctype="multipart/form-data" class="form-control" name="incident_reference" onchange="document.getElementById('inc_ref').src = window.URL.createObjectURL(this.files[0]); document.getElementById('inc_ref').className +='_active'; document.getElementById('inc_ref_span').className += '_hidden'"> </div><iframe id="inc_ref" class="form-group" width="220px" height="130px" style="position:absolute; left:78%; top:32%;"></iframe></div> </form> 3) error code: Notice: Undefined index: name in /opt/lampp/htdocs/create-nearmiss.php on line 57 ONGC TRIPUR Edited March 28, 2020 by Ronel change of var Okay, I'm hoping one of you can help me. I have a mysql database that I have configured through phpmyadmin. I have an android app that simply makes and sends a mysql query I can get it to successfully return values when using Select statements but when I use INSERT INTO, it returns " Error Query is invalid" BUT BUT BUT, when I use the same string and enter it through the sql tab in myphpadmin it works fine ! So here is the string ( the semicolons at the end of each field name are so I can use something common to split the string up when the data arrives back on the phone) Code: [Select] randomkey||||||INSERT INTO table4 (`geolat;` , `geolong;` , `mode;` , `destgeolat;` , `destgeolong;` , `cellphone;` , `email;` , `carrego;` , `colour;` , `rating;` , `comment;`) VALUES (0.0,0.0,'driver' ,-43.54779,172.62472, , '' ,'' , 'text' , 'ratingleftblank' , 'commentblank' ) the index4.php script is as follows Code: [Select] ?php /* * Written By: * James */ /************************************CONFIG****************************************/ //DATABSE DETAILS// $DB_ADDRESS="mysql1.openhost.net.nz"; $DB_USER="bling44"; $DB_PASS="sadlyinept"; $DB_NAME="bling44"; //SETTINGS// //This code is something you set in the APP so random people cant use it. $SQLKEY="randomkey"; /************************************CONFIG****************************************/ //these are just in case setting headers forcing it to always expire and the content type to JSON header('Cache-Control: no-cache, must-revalidate'); header('Content-type: application/json'); if(isset($_POST['tag'])){ //checks ifthe tag post is there $tag=$_POST['tag']; $data=explode("||||||",$tag); //split the SQL statement from the SQLKEY if($data[0]==$SQLKEY){ ///validate the SQL key $query=$data[1]; $link = mysql_connect($DB_ADDRESS,$DB_USER,$DB_PASS); //connect ot the MYSQL database mysql_select_db($DB_NAME,$link); //connect to the right DB if($link){ $result=mysql_query($query); //runs the posted query (NO PROTECTION FROM INJECTION HERE) if($result){ if (strlen(stristr($query,"SELECT"))>0) { //tests if its a select statemnet $outputdata=array(); while ($row = mysql_fetch_assoc($result)){ $outputdata[]=$row; //formats the result set to a valid array } echo json_encode(array("VALUE",$tag,array_merge($outputdata))); //sends out a JSON result with merged output data } else { echo json_encode(array("VALUE",$tag,array_merge(array(array("AFFECTED_ROWS ".mysql_affected_rows($link)))))); //if the query is anything but a SELECT it will return the array event count } } else echo json_encode(array("VALUE",$tag,array_merge(array(array("ERROR QUERY IS INVALID"))))); //errors if the query is bad mysql_close($link); //close the DB } else echo json_encode(array("VALUE",$tag,array_merge(array(array("ERROR Database Connection Failed"))))); //reports a DB connection failure } else { echo json_encode(array("VALUE",$tag,array_merge(array(array("ERROR BAD CODE SUPPLIED"))))); //reports if the code is bad } } ?> So to reiterate. I can search the DB but can't INSERT INTO, unless I go through the myphpadmin interface. Any ideas are very much appreciated i need the insert code |