PHP - Checkbox Insert/validation Problem
Hello, I am trying phpfreaks out without much luck here. If anybody here truly knows how to validate checkboxes as a group please give some assistance. I had to remove the array from the 'name' attribute in my checkbox inputs in order to get the user's checked selections to be properly distributed into separate database columns (not all in one column as a string of text). I am now able to successfully get the entries into the database as "1" for selected and "0" for un-selected. Now however, since there is no array that is holding these input names my validation class method does not work. My validation is suppose to show an error if none of these checkboxes are selected. I had to change each input name to its own identity ( fruit_selection_apple, etc... ), then set my validation like (see code below). However, this is NOT OOP PHP. I had to hard code these values into the validation class. I am also now getting a notice, " Notice: Undefined index: fruit_selection ". Does anyone legitimately know their PHP enough to help with this issue? public function check($source, $items = array()) { foreach($items as $item => $rules) { foreach($rules as $rule => $rule_value) { $value = trim($source[$item]); $item = escape($item); $checkboxvalue = (isset($_POST['fruit_selection_apple'])) || (isset($_POST['fruit_selection_orange'])) || (isset($_POST['fruit_selection_banana'])) || (isset($_POST['fruit_selection_pear'])) || (isset($_POST['fruit_selection_kiwi']) ) if($rule === 'atleastone' && empty($checkboxvalue)) { $this->addError("{$item} You must select at least one checkbox."); } Similar TutorialsHi My problem is that I can't insert my information into my database. I was able to insert the information into my database last night but when I tried to use validation it's not working any more. Here is my code for the sign up Code: [Select] <?php require_once("validation.php"); ?> <!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" dir="ltr"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>yensdesign.com - Validate Forms using PHP and jQuery</title> <link rel="stylesheet" href="css/general.css" type="text/css" media="screen" /> </head> <body> <a id="logo" title="Go to yensdesign.com!" href="http://www.yensdesign.com"><img src="css/images/logo.jpg" alt="yensdesign.com" /></a> <div id="container"> <h1>Registration process</h1> <?if( isset($_POST['send']) && (!validateName($_POST['name']) || !validateEmail($_POST['email']) || !validatePasswords($_POST['pass1'], $_POST['pass2']) || !validateMessage($_POST['message']) ) ):?> <div id="error"> <ul> <?if(!validateName($_POST['name'])):?> <li><strong>Invalid Name:</strong> We want names with more than 3 letters!</li> <?endif?> <?if(!validateEmail($_POST['email'])):?> <li><strong>Invalid E-mail:</strong> Stop cowboy! Type a valid e-mail please :P</li> <?endif?> <?if(!validatePasswords($_POST['pass1'], $_POST['pass2'])):?> <li><strong>Passwords are invalid:</strong> Passwords doesn't match or are invalid!</li> <?endif?> <?if(!validateMessage($_POST['message'])):?> <li><strong>Ivalid message:</strong> Type a message with at least with 10 letters</li> <?endif?> </ul> </div> <?elseif(isset($_POST['send'])):?> <div id="error" class="valid"> <ul> <li><strong>Congratulations!</strong> All fields are OK ;)</li> </ul> </div> <?endif?> <form method="post" id="customForm" action="index.php"> <div> Name <input id="name" name="name" type="text" /> <!--<span id="nameInfo">What's your name?</span>--> </div> <div> <input id="email" name="email" type="text" /> <!--<span id="emailInfo">Valid E-mail please, you will need it to log in!</span>--> </div> <div> Password <input id="pass1" name="password" type="password" /> <span id="pass1Info">At least 5 characters: letters, numbers and '_'</span> </div> <div> Confirm Password <input id="pass2" name="pass2" type="password" /> <span id="pass2Info">Confirm password</span> </div> <!--<div> <label for="message">Message</label> <textarea id="message" name="message" cols="" rows=""></textarea> </div>--> <div> <input id="send" type="submit" value="Send" /> </div> </form> </div> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="validation.js"></script> </body> </html> <?php $host="localhost"; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name="test"; // Database name $tbl_name="emails"; // Table name // Connect to server and select database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // Get values from form $name=$_POST['name']; $email=$_POST['email']; $password=$_POST['password']; // Insert data into mysql $sql="INSERT INTO $tbl_name(name, email, password)VALUES('$name', '$email', 'password')"; $result=mysql_query($sql); // if successfully insert data into database, displays message "Successful". if($result){ echo "Successful"; echo "<BR>"; echo "<a href='insert.php'>Back to main page</a>"; } else { echo "ERROR"; } // close connection mysql_close(); ?> This is the validation.php Code: [Select] <?php function validateName($name){ //if it's NOT valid if(strlen($name) < 4) return false; //if it's valid else return true; } function validateEmail($email){ return ereg("^[a-zA-Z0-9]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$", $email); } function validatePasswords($pass1, $pass2) { //if DOESN'T MATCH if(strpos($pass1, ' ') !== false) return false; //if are valid return $pass1 == $pass2 && strlen($pass1) > 5; } function validateMessage($message){ //if it's NOT valid if(strlen($message) < 10) return false; //if it's valid else return true; } ?> And this is the validation.js Code: [Select] /***************************/ //@Author: Adrian "yEnS" Mato Gondelle & Ivan Guardado Castro //@website: www.yensdesign.com //@email: yensamg@gmail.com //@license: Feel free to use it, but keep this credits please! /***************************/ $(document).ready(function(){ //global vars var form = $("#customForm"); var name = $("#name"); var nameInfo = $("#nameInfo"); var email = $("#email"); var emailInfo = $("#emailInfo"); var pass1 = $("#pass1"); var pass1Info = $("#pass1Info"); var pass2 = $("#pass2"); var pass2Info = $("#pass2Info"); var message = $("#message"); //On blur name.blur(validateName); email.blur(validateEmail); pass1.blur(validatePass1); pass2.blur(validatePass2); //On key press name.keyup(validateName); pass1.keyup(validatePass1); pass2.keyup(validatePass2); message.keyup(validateMessage); //On Submitting form.submit(function(){ if(validateName() & validateEmail() & validatePass1() & validatePass2() & validateMessage()) return true else return false; }); //validation functions function validateEmail(){ //testing regular expression var a = $("#email").val(); var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/; //if it's valid email if(filter.test(a)){ email.removeClass("error"); emailInfo.text("Valid E-mail please, you will need it to log in!"); emailInfo.removeClass("error"); return true; } //if it's NOT valid else{ email.addClass("error"); emailInfo.text("Stop cowboy! Type a valid e-mail please :P"); emailInfo.addClass("error"); return false; } } function validateName(){ //if it's NOT valid if(name.val().length < 4){ name.addClass("error"); nameInfo.text("We want names with more than 3 letters!"); nameInfo.addClass("error"); return false; } //if it's valid else{ name.removeClass("error"); nameInfo.text("What's your name?"); nameInfo.removeClass("error"); return true; } } function validatePass1(){ var a = $("#password1"); var b = $("#password2"); //it's NOT valid if(pass1.val().length <5){ pass1.addClass("error"); pass1Info.text("Ey! Remember: At least 5 characters: letters, numbers and '_'"); pass1Info.addClass("error"); return false; } //it's valid else{ pass1.removeClass("error"); pass1Info.text("At least 5 characters: letters, numbers and '_'"); pass1Info.removeClass("error"); validatePass2(); return true; } } function validatePass2(){ var a = $("#password1"); var b = $("#password2"); //are NOT valid if( pass1.val() != pass2.val() ){ pass2.addClass("error"); pass2Info.text("Passwords doesn't match!"); pass2Info.addClass("error"); return false; } //are valid else{ pass2.removeClass("error"); pass2Info.text("Confirm password"); pass2Info.removeClass("error"); return true; } } function validateMessage(){ //it's NOT valid if(message.val().length < 10){ message.addClass("error"); return false; } //it's valid else{ message.removeClass("error"); return true; } } }); I also get that the name, email and password is undefined This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=352154.0 Hi all
The below validation code works fine when the form gets submit.
But i want to apply validation "onclick" of button instead of "onsubmit"
How can i apply validation "onclick" of button instead of "onsubmit"
<html> <head> <script language="javascript"> function checkForm(frm){ var destCount = frm.elements['dest[]'].length; var destSel = false; for(i = 0; i < destCount; i++){ if(frm.elements['dest[]'][i].checked){ destSel = true; break; } } if(!destSel){ alert('Select one or more destinations'); } return destSel; } </script> </head> <body> Select at least one destination <form action="" method="post" onSubmit="return checkForm(this);"> <input id="cx" type="checkbox" name="dest[]" value="CX" /> <label for="cx">Cox's Bazar</label><br /> <input id="su" type="checkbox" name="dest[]" value="SU" /> <label for="su">Sundarban</label><br /> <input id="sy" type="checkbox" name="dest[]" value="SY" /> <label for="sy">Sylhet</label><br /> <input id="ch" type="checkbox" name="dest[]" value="CH" /> <label for="ch">Chittagong</label><br /> <br /> <input type="submit" name="Go" value=" Go " /> </form> </body> </html>Thanks Vineet Hi, I have a website where users can log on and edit their profile pic, name, biography etc. I was wondering about the correct way to:- Add data to the database through forms (Register.php) Display the data on a page Using mysql escape sting, however, the way I am currently using will display a '\' before any ' symbol. So it's >> it\'s ... Here is a snippet of the code I am using... Code: [Select] //insert data $about1 = mysql_real_escape_string($_POST['about']); //get $query = mysql_query("SELECT * FROM `staff` WHERE username='$username'"); $row = mysql_fetch_array($query); $about = $row['about']; echo $about; Hello all, I am trying to learn OOP in PHP so please forgive my ignorance. I seem to be having difficulty inserting data into my database from checkbox items. My database has a column for each each fruit. I would like for each column to be populated with either a one(1) for checked or a zero(0) for not checked. Currently, my attempts have failed. I can either get all checkboxes to insert all zeros or I can get the first column to insert a one(1) while the others as zeros. Is there anybody here that can help me figure out what I am doing wrong and help me to re-work my code so I can get this to work? If anybody can help me using OOP methods that would be fantastic. Thank you all in advance.
$preffruit->create_preffruit(array( 'fruit_apple' => escape(Input::get(['fruit_selection'][0]) ? 1 : 0), 'fruit_orange' => escape(Input::get(['fruit_selection'][1]) ? 1 : 0), 'fruit_banana' => escape(Input::get(['fruit_selection'][2]) ? 1 : 0), 'fruit_pear' => escape(Input::get(['fruit_selection'][3]) ? 1 : 0), 'fruit_kiwi' => escape(Input::get(['fruit_selection'][4]) ? 1 : 0) )); <input type="checkbox" name="fruit_selection[]" value="fruit_apple"> <input type="checkbox" name="fruit_selection[]" value="fruit_orange"> <input type="checkbox" name="fruit_selection[]" value="fruit_banana"> <input type="checkbox" name="fruit_selection[]" value="fruit_pear"> <input type="checkbox" name="fruit_selection[]" value="fruit_kiwi"> public function insert_preffruit($table, $fields = array()) { $keys = array_keys($fields); $values = ''; $x = 1; foreach($fields as $field) { $values .= '?'; if($x < count($fields)) { $values .= ', '; } $x++; } $sql = "INSERT INTO preffruit (`user_id`, `" . implode('`, `', $keys) . "`) VALUES (LAST_INSERT_ID(), {$values})"; if(!$this->query($sql, $fields)->error()) { return true; } return false; } Edited September 23, 2020 by ke-jo I am using the following piece of code to open a new window when a checkbox is checked... <INPUT type="checkbox" name="name" value="YES" onClick="window.open('/somepage.php?do=something&id=<?php echo $SOMEID["id"] ?>','','width=600,height=350,left=100,top=100,screenX=100,screenY=100')"> The page opens ok when the checkbox is ticked (checked). PROBLEM: The page opens again if the checkbox is un-ticked (un-checked). I just want to open the page if the checkbox is ticked only but not sure how to do this? OTHER INFO: Seperate checkboxes are dynamically created on the page for each id=<?php echo $SOMEID["id"] ?> i have this code: foreach($product_names as $product_row) { ?> <tr> <td > </td><td width='200px'><?php echo $product_row->getName(); ?></td> <td width='200px'><input type="checkbox" name="graphic[]" value="<?php echo $product_row->getId();?>" /></td> <td width='200px'><input type="checkbox" name="text[]" value="<?php echo $product_row->getId();?>" /></td> </tr> <?php } ?> </table> <table> <tr> <td> <input type='hidden' name='submit' value='Submit'> <?php if ( (isset($graphic)) || (isset($text) )) { echo "checkboxes checked"; //show submit button } else { //hide submit botton and echo "no boxes check"; } ?> </td> </tr> </table> so if i want to loop through grapic[] with the code: line 36 $graphics_selected = $_POST['graphic']; line 37 foreach($graphics_selected as $val) { if there is something in array(thus any checkbox is checked) enable submit button else if no checkboxes are checked disable submit button } i get errors: Notice: Undefined index: graphic in /home/helloises/svn_wappool/apps/lpmanager/modules/doc/templates/productSuccess.php on line 36 Warning: Invalid argument supplied for foreach() in /home/helloises/svn_wappool/apps/lpmanager/modules/doc/templates/productSuccess.php on line 37 please help???? Hi gang, new to posting but I've read the forum on and off. I'm coding a small community and will have a lot of questions for you over time. The first one is about a search function. We'll have users of different nationalities and languages and you will be able to search, only I was thinking there could be a better way. They'll enter those posts through a dropdown list and when you search it you will use checkboxes. I just don't see the results I want when I pick the array for info. Like I have this right now as the form (which is sent to the php page itself as POST): Nationality: <br /> <input type="checkbox"" name="natBox[]" size="30" value="all"/> All<br /> <input type="checkbox"" name="natBox[]" size="30" value="weuro"/> W Europe<br /> <input type="checkbox"" name="natBox[]" size="30" value="eeuro"/> E Europe<br /> <input type="checkbox"" name="natBox[]" size="30" value="wafrica"/> W Africa<br /> And the thing I was doing was to check the boxes with if (isset) and then make the query longer and longer, butI figure there could be a smarter way. Like if I was going to enter 200 countries I can't really check for all can I? After the check (now deleted) it sets the query to this: $query = "SELECT * FROM user_criteria WHERE (age BETWEEN '$ageFr' AND '$ageTo') AND nationality='$nationality'"; ...and the part I don't have now is to pick the array natBox and add every value so @nationality becomes for instance weuro OR wafrica etc. Got a more elegant approach? I have problem with this code. It does absolutely nothing. When INSERT is over it should redirect to index.php but it does nothing. There is no error, when the submit is clicked the page just refresh itself and because of echo function it write all the values. What seems to be the problem (I going slightly mad ) Code: [Select] <?php require_once("public/includes/session.php"); ?> <?php require_once("public/includes/connection.php"); ?> <?php require_once("public/includes/functions.php"); ?> <?php include_once("public/includes/form_functions.php"); include_once("public/includes/header.php"); if (isset($_POST['submit'])) { // Form has been submitted. $errors = array(); $required_fields = array('nik', 'lozinka', 'ime', 'prezime', 'adresa', 'grad', 'postanskiBroj', 'fiskni', 'moblini', 'email'); $errors = array_merge($errors, check_required_fields($required_fields, $_POST)); $username = trim(mysql_prep($_POST['nik'])); $password = trim(mysql_prep($_POST['lozinka'])); $hashed_password = sha1($password); $ime = trim(mysql_prep($_POST['ime'])); $prezime = trim(mysql_prep($_POST['prezime'])); $adresa = trim(mysql_prep($_POST['adresa'])); $grad = trim(mysql_prep($_POST['grad'])); $postanskiBroj = trim(mysql_prep($_POST['postanskiBroj'])); $fiskni = trim(mysql_prep($_POST['fiksni'])); $moblini = trim(mysql_prep($_POST['mobilni'])); $email = trim(mysql_prep($_POST['email'])); echo $username . $hashed_password . $ime . $prezime . $adresa . $grad . $postanskiBroj . $fiskni . $moblini . $email; if ( empty($errors) ) { $query = " INSERT INTO `gume`.`korisnik` (`id`, `korisnicko_ime`, `lozinka`, `ime`, `prezime`, `adresa`, `grad`, `postanskiBroj`, `fiksni_telefon`, `mobilni_telefon`, `email`) VALUES (NULL, '$username', '$hashed_password', '$ime', '$prezime', '$adresa', '$grad', '$postanskiBroj', '$fiskni, $moblini', '$email' )"; $result = mysql_query($query, $connection) or die(mysql_error); if ($result) { redirect_to("index.php"); } else { $message = "The user could not be created."; $message .= "<br />" . mysql_error(); } } else { if (count($errors) == 1) { $message = "There was 1 error in the form."; } else { $message = "There were " . count($errors) . " errors in the form."; } } } else { // Form has not been submitted. $username = ""; $password = ""; } ?> <div id="telo"> <div id="kreiranjeNaloga"> <script src="SpryAssets/SpryValidationTextField.js" type="text/javascript"></script> <link href="SpryAssets/SpryValidationTextField.css" rel="stylesheet" type="text/css" /> <script src="SpryAssets/SpryValidationPassword.js" type="text/javascript"></script> <script src="SpryAssets/SpryValidationConfirm.js" type="text/javascript"></script> <link href="SpryAssets/SpryValidationPassword.css" rel="stylesheet" type="text/css" /> <link href="SpryAssets/SpryValidationConfirm.css" rel="stylesheet" type="text/css" /> <p>Polja sa * su obavezna</p> <form action="new_user.php" method="post"> <span id="sprytextfield1"> <label>Korisnicko ime: </label> <input type="text" name="nik" id="nik" size="40" value=""/> *<span class="textfieldMinCharsMsg">Korisnicko ime ne moze imati manje od 5 karaktera</span><span class="textfieldMaxCharsMsg">Korisnicko ime moze imati najvise 30 karaktera.</span></span><br /> <span id="sprypassword1"> <label>Lozinka:</label> <input type="password" name="lozinka" id="lozinka" size="40" value=""/> *<span class="passwordMinCharsMsg">Sifra mora sadrzati najmanje 5 karaktera.</span><span class="passwordMaxCharsMsg">Sifra moze imati najvise 30 karaktera.</span></span> <br /> <span id="spryconfirm1"> <label>Potvrdite lozinku:</label> <input type="password" name="password1" id="password1" size="40" value=""/> <span class="confirmRequiredMsg">*</span>Obe lozinke moraju da budu iste.</span> <br /> <span id="sprytextfield2"> <label>Ime:</label> <input type="text" name="ime" id="ime" size="40" value=""/> * </span> <br /> <span id="sprytextfield3"> <label>Prezima</label> <input type="text" name="prezime" id="prezime"size="40" value="" /> *</span> <br /> <span id="sprytextfield4"> <label>Adresa:</label> <input type="text" name="adresa" id="adresa" size="40" value=""/> * </span> <br /> <span id="sprytextfield7"> <label>Grad:</label> <input type="text" name="grad" id="grad" size="40" value="" /> * </span> <br /> </span><span id="sprytextfield9"> <label>Postanski Broj: </label> <input type="text" name="postanskiBroj" id="postanskiBroj" size="10" value=""/> * <span class="textfieldInvalidFormatMsg">Postanski broj nije pravilno upisan.</span></span><br /> <span id="sprytextfield5"> <label>Broj fiksnog telefona: </label> <input type="text" name="fiksni" id="Broj fiksnog telefona" size="40" value="" /> *<span class="textfieldInvalidFormatMsg">Broj telefona nije pravilno upisan</span></span> <br /> <span id="sprytextfield6"> <label>Broj mobilnog telefona: </label> <input type="text" name="mobilni" id="mobilni" size="40" value="" /> *<span class="textfieldInvalidFormatMsg">Broj telefona nije pravilno upisan</span></span><br /> <span id="sprytextfield10"> <label>Email:</label> <input type="text" name="email" id="email" size="40" value="" /> *<span class="textfieldInvalidFormatMsg">Email adresa nija pravilno upisana.</span></span><br /> <input name="submit" type="submit" id="submit" value="Kreiraj korisnika" /> </form> </div> </div> <?php include("public/includes/footer.php"); ?> I have done a simple insert query on a comment system but it works once and when i go back and try add another record it just doesnt work at all. Code: [Select] <?php include ("class.database.connection.php"); // the database connection class include ("settings.config.php"); // hostname, password ect $name = $_POST["UserName"]; $email = $_POST["UserEmail"]; $comment = $_POST["UserComment"]; $sql="INSERT INTO comments (name, email, comment)VALUES('$name', '$email', '$comment')"; $result=mysql_query($sql); ?> if anyone can help me with this i would be a happy chappy! I have search the net and at the end tried 2 things that didn't solved the problem. It is known that certain browsers can refresh th epage 2 times without us knowing bacause it's doing it all by himself and so fast we don't even see it blink ! So I have following code for the normal sql-insert : Code: [Select] $Opdracht = "INSERT INTO tbl_link(userid,linkcat,linksubid,linklang,linkactive,linktitle) VALUES('$userid',1,0,'$lang',1,'$newML')"; it was inserted 2 times... I did some session check : at the top of the page : Code: [Select] session_start(); if(isset($_SESSION['itel'])){ $_SESSION['itel'] = $_SESSION['itel']+ 1; } else { $_SESSION['itel'] = 1; } echo "<br>session: ". $_SESSION['itel']; And it gave me number 2 ! This means the page was loaded 2 times, thus inserted 2 times. ! Than I tried : Code: [Select] $Opdracht = "INSERT INTO tbl_link(userid,linkcat,linksubid,linklang,linkactive,linktitle) VALUES('$userid',1,0,'$lang',1,'$newML') ON DUPLICATE KEY UPDATE linkid=LAST_INSERT_ID(linkid), linktitle='$linktitle'"; I got no error back but again 2 rows were created instead of 1... These are the fields in the table tbl_link : linkid userid linkcat linksubid linksuborder linklang linkactive linktitle articleid Unfortunately certain fields may be double in multiple rows, the only unique key is "linkid" and that's AUTO_INCREMENT. The only thing I can use is that userid and linktitle may NOT be reproduced 2 times (inserted) !!! I have an old site written for PHP 5.4 and under and trying (very trying) to get it to work with PHP 7x without much luck. Due to all the changes in 7 my code is one big error message, but one thing at a time. I cannot get the follow code to work at all, even though it worked in PHP 5. Error:
QUERY 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 'viewuser.php?u=666' id='member'>THE PREDATOR [666] was added to the hit' at line 1 I have tried at least 20+ different ways of doing this but just can't get the right syntax to get it inserted into MySQL, the code below is just the latest version. If I echo the a href line out, it works perfect. I am sure it is something ridiculously simple, but I have been 4 hours and counting on this now. Thanks gangevent_add_2($gangdata['gangID'], "<a href='viewuser.php?u=".$r['userid']."' ".$csscode[$r['userlevel']-1].">".$r['username']."</a> [".$r['userid']."] was added to your hitlist"); function gangevent_add_2($gang, $text) { global $db; $csscode; $db->query("UPDATE users SET gangevent = gangevent + 1 WHERE gang={$gang}"); $db->query("INSERT INTO gangevents VALUES('','$gang', UNIX_TIMESTAMP(),'$text')"); }
Hi, I am trying to insert the contents of a csv file into a table, this is my code: public function InsertCSVFileToDB(){ $has_title_row = true; $not_done = array(); if(is_uploaded_file($_FILES['csvfile']['tmp_name'])){ $filename = basename($_FILES['csvfile']['name']); if(substr($filename, -3) == 'csv'){ $tmpfile = $_FILES['csvfile']['tmp_name']; if (($fh = fopen($tmpfile, "r")) !== FALSE) { $i = 0; while (($items = fgetcsv($fh, 10000, ",")) !== FALSE) { if($has_title_row === true && $i == 0){ // skip the first row if there is a tile row in CSV file $i++; continue; } $sql = "INSERT INTO ConfPaper SET CPRid = ".$items[0].", Pid = ".$items[1].", CPtitle = '".mysql_real_escape_string($items[2])."', CPabstract = '".mysql_real_escape_string($items[3])."', CPspage = ".mysql_real_escape_string($items[4]).", CPepage = ".mysql_real_escape_string($items[5]).", CPlastesited = now()"; if(!mysql_query($sql)){ $not_done[] = $items; } $i++; } } // if there are any not done records found: if(!empty($not_done)){ echo "<strong>There are some records could not be inserted</strong><br />"; print_r($not_done); } } else{ die('Invalid file format uploaded. Please upload CSV.'); } } else{ die('Please upload a CSV file.'); } } This is the csv file: http://www.prima.cse.salford.ac.uk:8080/~ibrarhussain/ConfPaper.csv But i keep getting this: Quote Array ( => Array ( => 9 [1] => 1 [2] => CSV1 [3] => 4 [4] => 4 [5] => 01625 584412 ) [1] => Array ( => 9 [1] => 1 [2] => CSV2 [3] => 14 [4] => 24 [5] => 01625 584412 ) ) Any ideas what the problem might be? Hope someone can help.. Thanks 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"; } } hi, i was having difficulty and i'm quite confused how to insert these values to the database before it will become as it is, based on this article: http://roshanbh.com.np/2008/01/populate-triple-drop-down-list-change-options-value-from-database-using-ajax-and-php.html what i did was putting/saving the values directly in the database (mysql). but now i want those values to be coming from the user's input:the country,state and city so the system will just get those values, store it to the database with the fields of each table having the same content like that from article above..i really need some help here.. This php file cant echo in the 2nd php code, can anyone help me about this? 1st php code to connect into the 2nd php code Code: [Select] <?php $Total = $Total + $Amount; } ?> </tr> <tr> <td colspan="3" align="Right">Total</td> <td align ="Center"><?php echo number_format($Total,2);?></td> </tr> 2nd php code Code: [Select] <?php $db = mysql_connect("localhost", "root", ""); mysql_select_db("vinnex",$db); $TransNo = $_POST['TransNo']; $Username = $_POST['Username']; $Date = $_POST['Date']; $Total = $_GET['Total']; echo $Total; $sqltransaction = " INSERT INTO transaction (TransNo, Username, Date, Total) VALUES ('$TransNo', '$Username', '$Date', '$Total')"; $resulttransaction = mysql_query($sqltransaction); ?> i have created my own code of custom shopping cart
i have viewcart.php working great, now when i want to insert the orders from viewcart.php with list of like 5 items, how can i insert 5 names of products into my database 1 row
example
names are
1. jean
2. mond
3. richard
4. gwen
list above is the results of my while loop, now i want to insert those names to my database column[order_productname] so that i can identity what products are paid by my clients.
i tried fetch_array but if i assign variable to fetch array result, it only shows 1 which is "jean"
i wish this is possible
dforth
Hi... Before I have no problem in using On Duplicate Key, but now i have because of using time function. Before I only have insert query: Code: [Select] $result = mysql_query("INSERT INTO regular_sum_hours(EMP_NO, Hours) SELECT EMP_NO, sec_to_time(SUM(time_to_sec(Rendered))) FROM regular_dtr_total GROUP BY EMP_NO") or die(mysql_error()); And now I think that I need to add a syntax for Update, so i revise my code: Code: [Select] $result = mysql_query("INSERT INTO regular_sum_hours(EMP_NO, Hours) SELECT EMP_NO, sec_to_time(SUM(time_to_sec(Rendered))) FROM regular_dtr_total GROUP BY EMP_NO ON DUPLICATE KEY EMP_NO = EMP_NO, Hours = sec_to_time(SUM(time_to_sec(Rendered)))") or die(mysql_error()); and I got a problem in this part: Hours = sec_to_time(SUM(time_to_sec(Rendered)))") Thank you |