PHP - Insert Into Mysql (full String Please!)
Hi guys,
I have a very simple add.php to add data to a mySQL db. I have a menu/list drop down as one of my fields on my form and this shows an array of results from another table (ranks of the RAF) within my db. When I click the save button I have it process a INSERT INTO command but all i get inputted into my staff table is the first word... eg if I chose "Pilot Officer" from the list menu and then click save all that would appear in my db is "Pilot". Any clues? I will paste the php below... Code: [Select] <?php include('config.php'); ?> <form action='' method='POST' enctype='multipart/form-data'> <p><b>Rank:</b><br /> <select name="rank" id="rank"> <option selected>Please Select</option> <?php $query = "SELECT * FROM ranks ORDER BY rank ASC"; $result = mysql_query($query); while($row = mysql_fetch_array($result)) { echo "<option value=". $row["rank"] .">". $row["rank"] ."</option>"; } ?> </select> <p><b>Forename:</b><br /> <input name="forename" type="text" id="forename" value="" size="40"> <p><b>Surname:</b><br /><input name='surname' type='text' id="surname" value='' size="40" /> <p><b>Category:</b><br /> <select name="category" id="category"> <option selected>Please Select</option> <?php $query = "SELECT * FROM categories"; $result = mysql_query($query); while($row = mysql_fetch_array($result)) { echo "<option value=". $row["category"] .">". $row["category"] ."</option>"; } ?> </select> <p><b>Email:</b><br /><input name='email' type='text' id="email" value='' size="50" /> <p><b>Mobile:</b><br /> <input name='mobile' type='text' id="mobile" value='' size="40" /> </p> <input type='submit' value='Save' /> <input type='hidden' value='1' name='submitted' /> </form> <?php if (isset($_POST['submitted'])) { $rank = mysql_real_escape_string($_POST['rank']); $forename = mysql_real_escape_string($_POST['forename']); $surname = mysql_real_escape_string($_POST['surname']); $category = mysql_real_escape_string($_POST['category']); $email = mysql_real_escape_string($_POST['email']); $mobile = mysql_real_escape_string($_POST['mobile']); $sql = "INSERT INTO `staff` (`rank` , `forename` , `surname` , `category` , `email` , `mobile` ) VALUES ( '$rank' , '$forename' , '$surname' , '$category' , '$email' , '$mobile')"; mysql_query($sql) or die(mysql_error()); echo (mysql_affected_rows()) ? "Staff Added":"Nothing Added"; } ?> Similar TutorialsI am trying to add a value, input into a form, to a MySQL database. However, something must be wrong with the casting, because if there is a space in the form value, then I get an error, as in: //$_POST['string'] == '1blah 2blah'; sql = "INSERT INTO table (some_string) VALUES ($_POST[string])"; $sql_result = mysql_query($sql) or die ('The error is as follows: ' . mysql_error() . '<br /><br />Value could not be added.'); Then I get the following error: The error is as follows: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '2blah' at line 1 I've entered paragraphs into a database before, so this error is now to me. The column 'some_value' is a type: varchar(50). Hi to everybody I need ur help because I’m trying to make a script in php to write the same data but with different date in MySQL depending on the splitting ($data06).... like a schedule...
For example if $data06 = annual and $data03 = “2019/01/01” programm must create in MySQL : 2019/01/01 2020/01/01 2021/01/01 2022/01/01 2023/01/01
if $data06=“half year” will create 10 date , increasing 6 moths ...
But I have a problem at finish of code switch ($data06) { case 'annual': $numrate = 5; $aumdata = "+12 months"; break; case 'half year': $numrate = 10; $aumdata = "+6 month"; break;
default: echo "error"; $sql = "INSERT into $nometb ( name, scadenza ) values ( '$data01', '$data03' )"; if ($conna->query($sql) === TRUE) {} else {die('ERROR'. $conna->error); }
//IMPORT NEXT AND NEW DATE $newDate = date_create($data03); for ($mul = 2; $mul <= $numrate; ++$mul) {
$datanuova = date_create($data03); $datanuova->modify($aumdata); $datanuova->format('yy/m/d'); $newDate = $datanuova->format('yy/m/d');
$sql = "INSERT into $nometb ( name, scadenza ) values ( '$data01', '$newDate' )"; if ($conna->query($sql) === TRUE) {} else {die('ERROR'. $conna->error); }
//HERE THERE IS ERROR $data03 = $newDate;
if ($conna->query($sql) === TRUE) {} else {die('ERRORE NELL\'IMPORTAZIONE'. $conna->error); } }
} }
}
How I can resolve ?
many thanks Francesco 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 am having the database consists of morethan one lac rows. we have a search option in our website to search the database for required information. the present code is like this: form.php `<input type="radio" name="tag" value="city" /> CITY <br/>` `<input type="radio" name="tag" value="name" /> NAME OF CUSTOMER <br/>` `<input type="radio" name="tag" value="amount" /> CHEQUE AMOUNT <br/>` `<input type="radio" name="tag" value="somethingelse" /> some thing else ` `Enter the part of any of the above Here :<input type="text" name="value" />` search.php `$tag = $_POST['tag'];` `$value = $_POST['value'];` `$query = "SELECT * FROM database WHERE $tag LIKE '%$value%' "` note: we always input the part field only. with this some times the output comes in thousands of rows. with which we are facing problems. we want to search the two or more fields for getting more precise results. hence i tried this form: `<h3 align="center">ENTER ALL OR DESIRED ITEMS YOU WANT TO SEARCH</h3>` `<div width="80%" align="center">` `<input type="text" name="city" /> CITY <br/>` `<input type="text" name="name" /> NAME OF THE CUSTOMER <br/>` `<input type="text" name="amount" /> AMOUNT <br/>` `<input type="text" name="somethingelse" /> SOME OTHER SEARCH FIELD </div> ` `$query = "SELECT * FROM database WHERE city LIKE %$city%' || name LIKE %$name%' || amount LIKE %$amount%' || somethingelse LIKE %$somethingelse%';` it worked in the mysql console, and even in our website when we give all the variables. but it displaying the entire database when we dont give even one field in the search box. i tried to assign NULL to the variable which was not given. it is also not worked. it works if any variable is replaced with NULL in the query. i don't know how to do that. i tried a lot of queries after searching in lot of code provider websites. but none of them gave the desired results.hence i request you to provide me a sql query code for search the database using all of the above fields or any two or even with one. the code must work independent of number of fields we entered. The subject could be a bit vague, but my problem is simple. (I think so) So I made a php test site that is quite similar to a forum. Where you see a title or a subject and when you click on it you will see more details about that subject. I made my database and script for inserting data into my mySQL database. I also did my output aswell, so every topic is posted on a webpage "archive" where you can see all the subjects. But now I want to see the full details of that type of subject by clicking on it. I have no idea how to make that happen googled it but didn't find any results...just wondering if it's even possible to do that. I'm a new guy here! Hey guys, I can't wrap my head around how to make this work right... I have three tables: Code: [Select] CREATE TABLE `games` ( `g_id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(150) DEFAULT NULL, PRIMARY KEY (`g_id`)); CREATE TABLE IF NOT EXISTS `game_player` ( `r_id` int(11) NOT NULL AUTO_INCREMENT, `p_id` int(11) DEFAULT NULL, `g_id` int(11) DEFAULT NULL, `bool` int(1) NOT NULL DEFAULT '0', PRIMARY KEY (`r_id`)); CREATE TABLE IF NOT EXISTS `players` ( `p_id` int(11) NOT NULL AUTO_INCREMENT, `playerid` varchar(150) NOT NULL, PRIMARY KEY (`p_id`), UNIQUE KEY `playerid` (`playerid`)); The players table is my list of users, and they're tied to the list of games via the game_player table. So here's my issue... I'm trying to show the full list of games, and then check mark each record where the player does play it. This is what I have so far - it shows all the games, but it's not checking the boxes. Code: [Select] $result = mysql_query("SELECT * FROM games") or die(mysql_error()); while($row = mysql_fetch_array($result)) { $newquery = "SELECT * FROM game_player, players WHERE game_player.p_id = players.p_id AND game_player.g_id = ".$row['g_id']. " AND players.playerid = {$userid}"; $query = mysql_query($newquery) or die(mysql_error()); if($query['bool'] == 1) { $set_checked = " CHECKED"; } else{ $set_checked = ""; } echo "<input type=\"checkbox\" name=\"box1\" value=\"".$query['g_id']."\"" . $set_checked . "/>".$row['name']."<br />\n"; } You: As a PHP expert, you find the prospect of building yet another brochure-ware website distressing; you want to get your hands dirty building an advanced, MVC based application in a fun and supportive environment where you will be constantly challenged, always learning and delivering a product used by millions of people every day.
Our company was founded and is managed by developers who wrote the original software the company was built upon; the technical team are the core of our business. As a member of that team, it will be you who decides upon the on-going development of our technical stack as well as the product itself. You will of course have complete control over your workstation.
Our stack:
Qualifications:
A passion for programming, solving problems and building software customers love.
Experience building web-based applications as distinct from brochure-ware websites.
An expert in OOP/MVC/ORM programming techniques and PHP (v5.3+) frameworks. We happen to use Symfony2 but any relevant experience is fine.
You can bend MySQL to your will.
Solid front-end development experience with XHTML, CSS, and Javascript. Our stack includes AngularJS, CoffeeScript, jQuery and LESS.
An appreciation for a beautiful GUI and excellent user experience.
Expectation of a fast moving, agile environment. We ship code to customers daily – we’d expect you contribute from day 1.
You can validate your skills for example with source code samples, a github profile, contributions to an open source project, developer blog, stackoverflow answers etc.
What you will do:
Design (with help) and develop new channels for our software. In particular we are looking at apps using twilio (for voice/sms), facebook and twitter as well as a web based screensharing tool.
Integrate our software into other 3rd party applications. This could both be via APIs (salesforce, jira, 37signals) or through digging directly into the source code (sugarCRM, xenforo etc).
Continue improve and refine our existing channels and product. We are never satisfied and always looking for that small improvement, refactor or redesign that can increase usability, speed and functionality for our customers.
Work on our backend systems including internal developer tools and deployment processes, our SaaS application stack or the tools we have to manage our business.
Work on our mobile apps, built using our API / HTML5 and PhoneGap
About us:
Our principle product is DeskPRO, the helpdesk software platform. We make it easy for organisations (companies – large and small, charities, public sector organisations) to communicate with their users via email, twitter, facebook, SMS, web forms, live chat (text and voice) as well as providing publishing self-help tools, sales management, co-working tools and community based question and answers. DeskPRO is a platform where customers install the helpdesk applications they need to manage their business.
We sell this software to a range of organisations including large companies (e.g. Tumblr, Xerox, T-mobile, Fujitsu, Valve Software and AT&T) universities and the public sector all the way through to small family businesses. We have a dual license model; selling licenses to software installed on our clients’ servers (we don’t encrypt the code – so your code will get read!) and offering a fully managed SaaS solution. Millions of people use our software every day and a lot of agents spend their whole working day using it constantly.
What we offer:
Competitive salary based upon experience.
Friendly work environment at the Innovation Warehouse in Farringdon: http://theiw.org/.
30" monitor and control over your workstation setup. No corporate bureaucracy here.
A mixture of autonomy over your role and real responsibilities to the team and business.
Varied work. The DeskPRO product is large with lots of modules and technologies.
Review our source code before even applying; just ask and we will add you to our github account. Never accept a job until you have seen the code you will be working with.
We plan to have a lot of fun on this journey – please bring a sense of humour.
Apply:
Please send your CV and either a link to your online profile, github account or some sample source code to: jobs@deskpro.com
Hi everyone this time I want to do something everyone here knows it is possible: when posting a message at a forum you can press buttons and text appears at your pointer. Now that is not exactly what I want to do. at some forum sites (not phpfreaks) when pressing a button while posting you get a popup with buttons which make things appear in the not popup-window. that is exactly what I need to do. This is not about posting messages, btw, but a list of contacts of which you can select 2 in a popup. any ideas? any help is appreciated Hi all, I'm having a hard time with strings... I am pulling data from an XML feed, and then trying to insert into my database. All the code is wrote, the problem is that some of the descriptions contain both ' and " so it is messing with my insert statement. I can get over the ' by doing this: \"$newstring\" however it then fails on " I have tried every function I can think of: str_replace, mysql_real_escape_string, htmlspecialchars, addslashes, stripslashes etc. etc. nothing seems to do the trick! I have attached the code in full, would someone be able to take a look and help me out? Any help would be greatly appreciated! many thanks Greens85 Hello all, been trying for over a day to get something to work and after searching and searching I could not find what I was looking for. I found people looking to do something similar, but the answers seemed more complicated than I would think they need to be. First off, I'm still horrible at arrays and loops so try not to laugh too hard if my code is waaaayyyy off...haha I am essentially trying to tie products and quantities to a reservation. The user has the ability to add items to the form. I'm using jquery .clone to create each new item product and quantity form fields. When the user submits the form jquery inputs the values of the cloned fields into 2 hidden text fields called "productsField" and "quantitiesField" The values of these fields look something like value="1,2,2,1,3" depending on how many products were added. What I want to do is explode both and then enter them into the database. Seems simple enough, but apparently I am not getting it. I thought something like this would work, but it is not. if (isset($_POST["reserve_button"])) { $theReservationID = $_SESSION['createdReservationID']; $items = explode (",",$_POST['productsField']); $quantities = explode (",",$_POST['quantitiesField']); // loop through array $number = count($items); for ($i=0; $i<=$number; $i++) { // store a single item number and quantity in local variables $itno = $items[$i]; $quant = $quantities[$i]; if ($items[$i] <> '') { mysql_query('INSERT INTO reservation_items (reservationID,productID,productQuantity) VALUES($theReservationID,$itno,$quant)'); } } } Any help would be greatly appreciated. Thanks in advance, Twitch Hi,
I currently have some html stored in a variable as below:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> Hello world </body> </html>This requires a "<div class='container'>" to be inserted directly after the opening body tag. My original thinking was to use str_replace on the <body> to be <body><div class="container"> however note that occasionally my body will require an ID or Class. I therefore need a way to make it appear after the body tag, even if it has an ID or Class on it :-\ . I assume this may be reg-ex, but am not sure if there is a simple way around this? Would anyone be able to clarify and point me in the right direction. Much appreciated. MoFish Hi everyone, I'm new to this group and new to php. I have created a multi-part form that allows the user the option to add multiple input fields to a form to upload images. Here is the form structu Code: [Select] <form action="Scripts/processreports2.php" method="post" enctype="multipart/form-data" name="report_form" target="uploader" class="reportfrm"> <fieldset> <legend>Upload your images</legend> <ol id="add_images"> <li> <input type="file" class="input" name="files[]" /> </li> <li> <input type="file" class="input" name="files[]" /> </li> <li> <input type="file" class="input" name="files[]" /> </li> </ol> <input type="button" name="addFile" id="addFile" value="Add Another Image" onclick="window.addFile(this);"/> </fieldset> <p>* indicates a required field.</p> <input name="submit" type="submit" id="submit" value="Send Info!" /> </form> Through php a maximum of three input fields are fed into an array that checks to make sure that the uploaded files are images and not some other type of file. The uploading porition of this script works. Now I am trying to get the values of the input fields as a string and insert them into the database as one record. Let's say the user has three files they want to upload. I have managed to get the files as a string ie; file1.jpg, file2.jpg, file3.jpg but what is happening is that I am getting three separate records with file1.jpg, file2.jpg, file3.jpg in them. If the user has only two files to upload then I get two separate records with file1.jpg and file2.jpg in them. (Hope that makes sense). I want one record. I have been struggling with this since Monnday and while every day I get closer, this is as close as I can get. Below is the php code. #connect to the database mysql_connect("localhost", "root", ""); mysql_select_db("masscic"); //Upload Handler to check image types function is_image($file) { $file_types = array('jpeg', 'gif', 'bmp'); //acceptable file types if ($img = getimagesize($file)){ //echo '<pre>'; //print_r($_FILES); used for testing //print_r($img); used for testing if(in_array(str_replace('image/', '', $img['mime']), $file_types)) return $img; } return false; } //form submission handling if(isset($_POST['submit'])) { //file variables $fname = $_FILES['files']['name']; $ftype = $_FILES['files']['type']; $fsize = $_FILES['files']['size']; $tname = $_FILES['files']['tmp_name']; $ferror = $_FILES['files']['error']; $newDir = '../uploads/'; //relative to where this script file resides for($i = 0; $i < count($fname); $i++) { //echo 'File name ' . $fname[$i] . ' has size ' . $fsize[$i]; used for testing if ($ferror[$i] =='UPLOAD ERR OK' || $ferror[$i] ==0) { if(is_image($tname[$i])) { //append the tmp_name($tname) to the file name ($fname) and upload to the server move_uploaded_file($tname[$i], ($newDir.time().$fname[$i])); echo '<li><span class="success">'.$fname[$i].' -- image has been accepted<br></span></li>'; }else echo '<li><span class="error">'.$fname[$i].' -- is not an accepted file type<br></span></li>'; } if (is_array($fname)) $files = implode(', ',$fname); //else $files = $fname; $sqlInsert = mysql_query("INSERT INTO files (file_names) VALUES('$files')") or die (mysql_error()); } } 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 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 I don't understand where the empty value is. I've substituted the variables for text and still have the same problem. Code: Code: [Select] $sql = "INSERT INTO courses (course#, name, subject, semester, ap)VALUES('$courseNum', '$courseName', '$subject', '$semester', '$ap')"; Error: 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 '' at line 1 well this is truely embarrising...i have a insert statement which works within phpmyadmin but when using mysqli_query it returns a error.
INSERT INTO users (username, timestamp) VALUES ('test', UTC_TIMESTAMP())Unknown column 'timestamp' in 'field list' i've been playing about with this for a few hours now ...tried changing the column name (timestamp), adding ` around column names as well as table name. the column exists which is the strangest part, and ive even checked there is no space after the column name in the db. whats going on please? I need help badly! What I want to do is insert into database the value from the selected radio group buttons.. All of them. There are 10 radio groups total (they can be less, but not more). Thanks! Code: [Select] <?php require_once('Connections/strana.php'); mysql_select_db($database_strana, $strana); ?> <link href="css/styles.css" rel="stylesheet" type="text/css" /> <table width="100%" height="100%" style="margin-left:auto;margin-right:auto;" border="0"> <tr> <td align="center"> <form action="" method="post" enctype="multipart/form-data" name="form1"> <table> <?php $tema = mysql_query("SELECT * from prasanja where tip=2")or die(mysql_error()); function odgovor1($string) { $string1 = explode("/", $string); echo $string1[0]; } function odgovor2($string) { $string1 = explode("/", $string); echo $string1[1]; } while ($row=mysql_fetch_array($tema)) { $id=$row['prasanje_id']; $prasanje=$row['prasanje_tekst']; $tekst=$row['odgovor']; ?> <tr> <td> </td> </tr> <tr> <td class="formaP"> <?php echo $prasanje?> </td> </tr> <tr> <td class="formaO"> <p> <label> <input type="radio" name="Group<?php echo $id?>" value="<?php odgovor1($tekst) ?>" /> <?php odgovor1($tekst) ?></label> <br /> <label> <input type="radio" name="Group<?php echo $id?>" value="<?php odgovor2($tekst) ?>" /> <?php odgovor2($tekst) ?></label> <br /> </p></td> </tr> <tr> <td> <br /> </td> </tr> <?php } ?> </table> <input align="left"type="submit" name="submit" value="Внеси" > </form> </td> </tr> </table> prasanje = question tekst/odgovor = answer The answer table: id - primary question_id - the questions ID whose answer is selected in the radio group user_id - cookie takes care of this answer - the value from radio group date - automatic I have this code: <?php $con = mysql_connect("localhost","hhh","hhh"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("hhh", $con); // -------------------- // Avatar insert check // -------------------- session_start(); $name = $_POST[name]; $group = $_POST[group]; $age = $_POST[age]; $usernameid = $_SESSION[id]; $result = mysql_query("SELECT * FROM avatars WHERE name='$_POST[name]'"); $num = mysql_numrows($result); if ($num == 0) { mysql_query("INSERT INTO avatars (id, usernameid, name, group, age, xp) VALUES ('', '$usernameid', '$name', '$group', '$age', '0')"); header( 'Location: me/' ) ; } else echo 'Sorry, please pick a new name'; ?> And it does everything but put the data into the datebase. If I add a session befor and after '$request' they both run, but the sql doesn't. No error returns, if just redirects to the other page. Any help? |