PHP - Can't Insert Items Into Mysql
This is probably some obvious error I have made, but I cannot figure it out. I have made a few pages and now I am debugging them. My first page is called insert_purchase_order.php; on this page a person will enter some data in fields and hit the insert button. Then, the data is passed to another page, but when I try to insert into mysql it does not give me any errors, but I have no new rows either. The code for my 2nd page:
Code: [Select] <?php session_start(); $action=$_GET[action]; if ($action==insert){ $randid=$_POST['randid']; $vendor=$_POST["vendor"]; $purchase_order_date=$_POST["purchase_order_date"]; $ship=$_POST["ship"]; $fob=$_POST["fob"]; $terms=$_POST["terms"]; $buyer=$_POST["buyer"]; $freight=$_POST["freight"]; $req_date=$_POST["req_date"]; $confirming_to=$_POST["confirming_to"]; $remarks=$_POST["remarks"]; $tax=$_POST["tax"]; $con = mysql_connect("localhost","root","pass"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("main", $con); mysql_query("INSERT INTO purchase_order (randid, vendor, purchase_order, ship, fob, terms, buyer, freight, req_date, confirming_to, remarks, tax) VALUES ($randid, $vendor,$purchase_order_date,$ship, $fob, $terms, $buyer, $freight, $req_date, $confirming_to, $remarks, $tax)"); mysql_close($con); echo 'Data Accepted...'; echo '<br/>'; echo 'P.O. Inserted Successfully'; }else{ echo 'Error... Please Contact Bruce.'; echo 'Bruce, no data was passed from the insert_purchase_order.php page.'; } ?> <a href="http://localhost/insert_purchase_order_items.php?po= <?php echo $randid; ?>">Insert Purchase Order Items</a> I have permissions and everything. Thanks Similar TutorialsCan 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; Hello, In my Mysql database, it has a datetime field. and I have created a $today = date('Y-m-d H:i:s'); <- today's date and time How do I write a query to run in PHP in order to get all today's items by comparing datetime field and $today? Thanks! I currently have a page where I have each row in my table listed using: Code: [Select] $getinfo="SELECT * FROM tablename WHERE Closed='n'"; $result=mysql_query($getinfo); while ($row=mysql_fetch_array($result)){ ... // list of user information } That successfully displays my content. What I am trying to do is have a checkbox next to each user (row) that when I check them and hit submit at the bottom, it will change the value of each row on the 'Closed' column to 'y' so it will not be displayed when the page is refreshed. I want to be able to select multiple items to "close". And I would like it to come back to this page. I think I can use this page as the form action and have the code above my while loop to change the Closed column so it then would not be displayed when the while loop is called... is that right? How do I set this up? Not sure where to start the form tag and where to end it, and not sure how to...well...do any of it. I've been playing around with this code from http://v3.thewatchmakerproject.com/journal/276/building-a-simple-php-shopping-cart Objective: I'm trying to make the scripts work but without pulling the data from MySQL Database. Instead, I created an array and inserted some info there and trying to replicate the same results but getting confused. For example, on the Index.php file, I made the following changes: <?php // Start the session session_start(); // Include functions require_once('inc/functions.inc.php'); // Products multidimensional Array $products = array("book" => array( 'id' => '1', 'title' => 'Learn Your ABC\'s', 'author' => 'John Doe', 'price' => '14.95'), "video" => array('id' => '2', 'title' => 'Visual Guide to learn', 'author' => 'Adam Smith', 'price' => '21.38'), "puzzle" => array('id' => '3', 'title' => 'Can You Solve?', 'author' => 'Sara Brown', 'price' => '9.41'), "exam" => array('id' => '4', 'title' => 'Test Your Knowledge', 'author' => 'Kim Carver', 'price' => '11.15')); ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>PHP Shopping Cart Demo &#0183; Bookshop</title> <link rel="stylesheet" href="css/styles.css" /> </head> <body> <div id="shoppingcart"> <h1>Your Shopping Cart</h1> <?php echo writeShoppingCart(); ?> </div> <div id="booklist"> <h1>Books In Our Store</h1> <?php /* $sql = 'SELECT * FROM books ORDER BY id'; $result = $db->query($sql); $output[] = '<ul>'; while ($row = $result->fetch()) { $output[] = '<li>"'.$row['title'].'" by '.$row['author'].': $'.$row['price'].'<br /><a href="cart.php?action=add&id='.$row['id'].'">Add to cart</a></li>'; } $output[] = '</ul>'; echo join('',$output); */ ?> <?php $output[] = '<ul>'; foreach ($products as $product => $product_item) { // $flavor is the key and $piece is the value foreach ($product_item as $item => $piece) { if ($item == "id") { # Conditional logic defined to map specific keys to specified name value $row['id'] = $piece; // echo "The id is ". $id."<br />"; // set just to confirm value correct for variable } elseif ($item == "title") { # Conditional logic defined to map 1st key to price value $row['title'] = $piece; // echo "The title is ". $title."<br />"; // set just to confirm value correct for variable } elseif ($item == "author") { # Conditional logic defined to map 1st key to price value $row['author'] = $piece; // echo "The author is ". $author."<br />"; // set just to confirm value correct for variable } elseif ($item == "price") { # Conditional logic defined to map 1st key to shipping value $row['price'] = $piece; // echo "Price: ". $price."<br /><br />"; // set just to confirm value correct for variable } $output[] = '<li>"'.$row['title'].'" by '.$row['author'].': $'.$row['price'].'<br /><a href="cart.php?action=add&id='.$row['id'].'">Add to cart</a></li>'; $output[] = '</ul>'; echo join('',$output); } } ?> </div> </body> </html> And here's the original index.php before my edits which show the sql query to the db: <?php // Include MySQL class require_once('inc/mysql.class.php'); // Include database connection require_once('inc/global.inc.php'); // Include functions require_once('inc/functions.inc.php'); // Start the session session_start(); ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>PHP Shopping Cart Demo &#0183; Bookshop</title> <link rel="stylesheet" href="css/styles.css" /> </head> <body> <div id="shoppingcart"> <h1>Your Shopping Cart</h1> <?php echo writeShoppingCart(); ?> </div> <div id="booklist"> <h1>Books In Our Store</h1> <?php $sql = 'SELECT * FROM books ORDER BY id'; $result = $db->query($sql); $output[] = '<ul>'; while ($row = $result->fetch()) { $output[] = '<li>"'.$row['title'].'" by '.$row['author'].': £'.$row['price'].'<br /><a href="cart.php?action=add&id='.$row['id'].'">Add to cart</a></li>'; } $output[] = '</ul>'; echo join('',$output); ?> </div> </body> </html> Also, I included the zipped file of the entire script setup. Again, I'm trying to figure out how to make the cart work with using an array for the product instead of MySQL database. My goal is to remove ALL SQL statements from the scripts but stuck with the looping portion to display the title, author, and price from the array as shown above. 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 have a webpage where all the database items are displyes in a table format.The table also has a check box.Upon clicking the delete button i need to delete all the items whish has the checkbox checked. How will i do that 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 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 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? Hi. I think you all know me by now so I'll cut to the chase. Code: [Select] <?php $host="edited"; $username="edited"; $password="edited"; $db_name="edited"; $tbl_name="topic"; // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $name=$_POST['name']; $detail=$_POST['details']; $sql="INSERT INTO $tbl_name(topic, detail, datetime)VALUES('$name', '$detail', NOW())"; $result=mysql_query($sql); if($result){ header("location:site.html");} else{ echo("I have failed you master.");} ?> Displayed error: "I have failed you master." Anyone know a possible cause? Thanks. Bye. Hey guys for some reason this code is not working i can't see a problem myself could someone please have a look and point the issue out to me. what i mean by it not working is it won't insert into the database or show a mysql_error. thanks in advance Code: [Select] $guestip = $_SERVER['REMOTE_ADDR']; $time = date('G:i'); $date = date("y-m-d"); $query = mysql_query("SELECT * FROM IP_Address") or die(mysql_error()); while($row = mysql_fetch_assoc($query)){ if($guestip != $row['ip']){ //insert into db. mysql_query("INSERT INTO IP_Address(id, ip, date, time) VALUES(NULL,'$questip','$date','$time')") or die(mysql_error()); echo "inserted in to database"; echo mysql_error(); }else{ // add hit count and update time and date. echo "already in db"; } } how can i make this code to insert a single, multiple and update rows in the database. The code only insert new rows in the database. Code: [Select] if (($handle = fopen('inventorylist.csv', "r")) !== FALSE) { while (($data = fgetcsv($handle, 100000, ",")) !== FALSE) { $num = count($data); $sql="INSERT into inventory(itemNumber,itemDesc,quantityHand,category,Whse) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]')"; mysql_query($sql) or die(mysql_error()); } fclose($handle); } I've got Code: [Select] for ($i=1; $i<=5; $i++) { if(isset($_POST['partsusedqty'.$i]) && $_POST['partsusedqty'.$i] != "" && $_POST['partsusedqty'.$i] != "0.00") { mysql_query("INSERT INTO partsused (ptnumber, partqty, partdesc, partprice) VALUES ($ticket, '$partsusedqty'.$i, '$partsuseddesc'.$i, '$partsusedprice'.$i)") or die(mysql_error()); } } I need to know the correct formatting to put these variable variables as values in the mysql query. With this particular code, I get the 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 '.1, ''.1, ''.1)' at line 2" I've tried formatting this an endless number of ways, but I used this particular example because its the one I really thought should work. Everything I've tried that doesn't throw an error put the $partsusedqty in the partqty, partdesc, and partprice fields. Thanks for any help! Hi anyone here know how to insert $GET variable into mysql, i don't know how to put this variable between curly bracket, when i put on top insert query, i got error 'Could not insert admin'...please help Code: [Select] <?php mysql_connect("localhost","root","") or die(mysql_error()); mysql_select_db("healthsystem") or die(msql_error()); [color=red]//GET varibable $id = $_GET['id'];[/color] // file properties $file = $_FILES['image']['tmp_name']; if (!isset($file)) echo "Please select an image"; else { $image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); $image_name = addslashes($_FILES['image']['name']); $image_size = getimagesize($_FILES['image']['tmp_name']); if ($image_size==FALSE) echo "That's not an image."; else { $insert = "INSERT INTO image_tbl(m_id,name,image) VALUES ('$id','$image_name','$image')"; $insert2=mysql_query($insert) or die("Could not insert admin"); print "Personal Wellness Successfully Submitted"; } } ?> I have a problem where I am getting these errors after a form has been submitted from join.html Here are the errors: Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'scswccla'@'localhost' (using password: NO) in /home/scswccla/public_html/insert.php on line 9 Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /home/scswccla/public_html/insert.php on line 9 Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'scswccla'@'localhost' (using password: NO) in /home/scswccla/public_html/insert.php on line 9 Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /home/scswccla/public_html/insert.php on line 9 Here is the insert.php file http://pastebin.com/EVtgidQC And the join.html file - http://pastebin.com/hqDtGLe5 How would I fix those errors - I got the code from http://forum.hey0.net/showthread.php?tid=2509 The form is at scswc.com/join.html if you want to look at it. I really want to get this working so if you need any more info to help fix it just ask thanks! Hello every body,, i want to create a new database (auto generate duty assigned using form) in PHP and mysql..
i have four input fields:-
Name, Subject, Class & weekly lectures
now i want to insert name,subject & class into database, when i insert number of weekly lecture in field four..
insert automaticlly in database multiple time which i write in field four (weekly lecture)
database: table structure i have already is:::
id-name-subject-class-period-monday-tuesday-wednesday-thursday-friday-saturday
anybody please help me to create this database or just insert query ....
I am attempting something similar to the following: Code: [Select] mysql_query("UPDATE table SET name='$name' WHERE id=$id"); if (mysql_affected_rows()==0) { mysql_query("INSERT INTO table (id, name) VALUES ('$name',$id); } If the $id row does not exists in the table, mysql_affected_rows() returns 0 and a new $id row gets inserted but if the $id row already exists and UPDATE changes nothing, mysql_affected_rows() still returns 0 and gives an 'duplicate id' error as expected. I know I could use a SELECT to test for the existance of the $id row. In Perl there is an '0E0', 'zero but true', condition to handle this. Is there an equivilant in PHP? |