PHP - Inserting ' Or " Into Mysql
Hi All,
I'm trying to insert a HTML code into one of the fileds so when you load the page it reads that code and shows you the picture that code is pointing you as you can see below but the problem is I have too many " and ' s so PHP wont pass it. $name = $_POST['name']; $title = $_POST['title']; $ext = $_POST['ext']; $cell = $_POST['cell']; $sec = $_POST['sec']; $emp = $_POST['emp']; $con = mysql_connect("localhost","root","PA55ss"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("movedb", $con); $sql="INSERT INTO sheet1sa (ext, F2, cell, name, dep, F6, empno) VALUES ('$ext', '$sec', '$cell', '$name', '$dep', '<img src='./pics/$empno.jpg' width="80" height='90' />", '$empno')"; BTW i need to make this code so it takes the "empno" value and insert it into that code before .JPG so when browser reads my database it will read it as "./pics/777788.JPG" Thanks for your help Similar TutorialsHi everyone, I have the task of building a PHP page where users can enter or remove as many records as they like into different categories. This then makes the number of records entered unknown, and therefore it becomes more complicated. To make this clearer, I have attached an image of what I am trying to do. Two questions: - Before submitting the form, how can each record entry be matched with the correct category? (maybe hidden form fields somehow?) - What is the best way of inserting each record (and it's associated category) into a MySQL database table from a single form submit? I want to try and keep this as simple as possible as the data will later be updated, removed etc. I'm experiencing a brain fart and just cannot picture the best way of going about this Any help and advice is much appreciated! Thanks in advance. Code: [Select] Basic table schema example... CATEGORY TABLE ---------------------------- | catid | category | ---------------------------- | 1 | Category A | | 2 | Category B | etc. etc. ---------------------------- DATA ENTRY TABLE ---------------------------- dataid | catid | data | -------------------------------- | 1 | 2 | data xyz | | 2 | 1 | data zyx | etc. etc etc. -------------------------------- I'm attempting to set up a script that will choose a "random" image from a directory and then place it in an article when it's posted. I currently have a php file that randomly assigns a picture on each refresh, however my employer wants the image to be static after posting. So I guess the short of my question is, what would be the best way to go about something like that or is it even doable with PhP. Can someone please help me with an array problem i can not figure out. I need the array to be numbered from 1 to how ever many fields that are needed in the form and have a mysql field name and the title of the field also in the array. 1, "mysql_field_name", "Title of form field" 2, "", "" and so on then the form will be shown based on the array. I have the following draft code which I am working with. any suggestions on how i may do this array ? Code: [Select] <?php $options = array( '1'=> array('fieldtext'=>'option1', 'mysqlfield'=>'option1'), '2'=> array('fieldtext'=>'option2', 'mysqlfield'=>'option2'), '3'=> array('fieldtext'=>'option3', 'mysqlfield'=>'option3'), '4'=> array('fieldtext'=>'option4', 'mysqlfield'=>'option4'), ); // $options = array(1 => "option1", "option2", "option3", "option4"); // the line above works but i want to include the name of the mysql field as well. $userid = 1; ?> <div style="align: center; margin: 12px; font-family:Tahoma;"> <br><br><?php if ($_POST['Update'] != "Update") { // check if form submitted yet, if not get data from mysql. $res = db_query("SELECT * FROM `users` WHERE `userid` = '" . $userid . "'"); foreach($options as $key => $value) { $_POST[$key] = mysql_result($res, 0, $value); } $ok_to_update = "no"; } elseif ($_POST['Update'] == "Update") { // check if form submitted yet, if so get POST data. // error checking // foreach($options as $key => $value) { // $_POST[$i] = ""; // } $ok_to_update = "yes"; } if ($_POST['Update'] == "Update" && $ok_to_update == "yes") { // $res = db_query("INSERT INTO `users` () VALUES ()"); // add user details to database. ?><p><br><br><br>Thank you for updating</p><?php } else { ?><form name="form1" method="post" action=""> <?php foreach($options as $key => $value) { ?><p><?php echo($value); ?>: <input type="text" name="<?php echo($key); ?>" value="<?php echo($_POST[$key]);?>"></p> <?php } ?> <input name="Update" type="submit" value="Update"> </form> <?php } ?> </div> Hi, Does anyone have any idea how to insert an entire php or html pages into mysql once the page has being created with php? E.g. np1.php <form action="np2.php" method="post"> Name of New Page: <input type="text" name="newpage_name" /> <input type="submit" /> </form> np2.php <?php $newpage_name = $_POST[ 'newpage_name' ]; $newpage_initial = "Input Contents Here."; //echo $editor_data; $newpage_file = "test/" . $newpage_name . ".php"; $newpage_save = fopen($newpage_file, 'w'); fwrite($newpage_save, $newpage_initial); fclose($newpage_save); ?> I have managed to create a new file with php but I also want it when I click on the submit button, it will also auto save that new php file or html file into mysql. Regards Jas Thanks for reading my post, Can someone point me to the right direction here; Am trying to insert a record in a text area field into PHP/MYSQl. This time around, I am reading what the user entered into the textarea before inserting. Take a look at this: TEXTAREA -> row 1: BOY row 2: GIRL Can I make it two rows in my database as opposed to one? I don't have a problem inserting, just how to insert as multiple if there are two rows. Thanks in advance Hi guys I am using the code found here http://www.elated.com/articles/cms-in-an-afternoon-php-mysql/ with some alterations to try and insert data in a database via a php form, i have completed the example shown on that site and it works perfect, but I am now trying to adjust the code so that i have a user and admin section, but the form will not submit to the database. Here is the for my form, page know as editArticles: Code: [Select] <?php include "templates/include/header.php" ?> <div id="userHeader"> <h2><spanH1>Advertise!</spanH1> Place an advert for your book</h2> <p>You are logged in as <b><?php echo htmlspecialchars( $_SESSION['username']) ?></b>. <a href="user.php?action=logout"?>Log out</a></p> </div> <h1><?php echo $results['pageTitle']?></h1> <form action="user.php?action=newArticle" method="post"> <input type="hidden" name="articleId" value="<?php echo $results['article']->id ?>"/> <?php if ( isset( $results['errorMessage'] ) ) { ?> <div class="errorMessage"><?php echo $results['errorMessage'] ?></div> <?php } ?> <ul> <li> <label for="booktitle">Book Title</label> <input type="text" name="booktitle" id="booktitle" placeholder="Title of the book" required autofocus maxlength="100" value="<?php echo htmlspecialchars( $results['article']->booktitle )?>" /> </li> <li> <label for="author">Book Author</label> <input type="text" name="author" id="author" placeholder="Author of the book" required autofocus maxlength="50" value="<?php echo htmlspecialchars( $results['article']->author )?>" /> </li> <li> <label for="edition">Edition</label> <input type="text" name="edition" id="edition" placeholder="Edition" required autofocus maxlength="2" value="<?php echo ( $results['article']->edition )?>" /> </li> <li> <label for="category">Category</label> <input type="text" name="category" id="category" placeholder="Book Category E.G Buisness" required autofocus maxlength="30" value="<?php echo htmlspecialchars( $results['article']->category )?>" /> </li> <li> <label for="module">Module</label> <input type="text" name="module" id="module" placeholder="Module" required autofocus maxlength="30" value="<?php echo ( $results['article']->module )?>" /> </li> <li> <label for="price">Price</label> <input type="text" name="price" id="price" placeholder="Price" required autofocus maxlength="30" value="<?php echo ( $results['article']->price )?>" /> </li> <li> <label for="condition">Condition</label> <input type="text" name="condition" id="condition" placeholder="condition" required autofocus maxlength="30" value="<?php echo ( $results['article']->condition )?>" /> </li> <li> <label for="description">Description</label> <textarea name="description" id="description" placeholder="Description of the book including condition and associated modules" required maxlength="500" style="height: 15em;"> <?php echo htmlspecialchars( $results['article']->description )?></textarea> </li> <li> <label for="Image">Image</label> <input type="file" name="Image" id="Image" /> </li> <li> <label for="pdate">Sale Date</label> <input type="date" name="pdate" id="pdate" placeholder="YYYY-MM-DD" required maxlength="10" value="<?php echo $results['article']->pdate ? date( "Y-m-d", $results['article']->pdate ) : "" ?>" /> </li> </ul> <div class="buttons"> <input type="submit" name="saveChanges" value="Save Changes" /> <input type="submit" formnovalidate name="cancel" value="Cancel" /> </div> </form> <?php if ( $results['article']->id ) { ?> <p><a href="admin.php?action=deleteArticle&articleId=<?php echo $results['article']->id ?>" onclick="return confirm('Delete This Article?')">Delete This Article</a></p> <?php } ?> <?php include "templates/include/footer.php" ?> This is the form for the php, as you can see the form action is "new article" This is the code for the action new article Code: [Select] function newArticle() { $results = array(); $results['pageTitle'] = "New Article"; $results['formAction'] = "newArticle"; if ( isset( $_POST['saveChanges'] ) ) { // User has posted the article edit form: save the new article $article = new Article; $article->storeFormValues( $_POST ); $article->insert(); header( "Location: admin.php?status=changesSaved" ); } elseif ( isset( $_POST['cancel'] ) ) { // User has cancelled their edits: return to the article list header( "Location: admin.php" ); } else { // User has not posted the article edit form yet: display the form $results['article'] = new Article; require( TEMPLATE_PATH . "/admin/editArticle.php" ); } } As you can see the template is set to the above form page editArticle Below is the code for the class "article" which contains the insert function and other functions such as construct, the storeFormValues which can is used in the "newArticle" function, and of course the insert function Code: [Select] class Article { public $id = null; public $booktitle = null; public $author = null; public $edition = null; public $category = null; public $module = null; public $price = null; public $condition = null; public $description = null; public $image = null; public $pdate = null; public function __construct( $data=array() ) { if ( isset( $data['id'] ) ) $this->id = (int) $data['id']; if ( isset( $data['booktitle'] ) ) $this->booktitle = preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['booktitle'] ); if ( isset( $data['author'] ) ) $this->author = preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['author'] ); if ( isset( $data['edition'] ) ) $this->edition = $data['edition']; if ( isset( $data['category'] ) ) $this->category = $data['category']; if ( isset( $data['module'] ) ) $this->module = $data['module']; if ( isset( $data['price'] ) ) $this->price =(int) $data['price']; if ( isset( $data['condition'] ) ) $this->condition = $data['condition']; if ( isset( $data['description'] ) ) $this->description = $data['description']; if ( isset( $data['image'] ) ) $this->image = $data['image']; if ( isset( $data['pdate'] ) ) $this->pdate = (int) $data['pdate']; } public function storeFormValues ( $params ) { // Store all the parameters $this->__construct( $params ); // Parse and store the publication date if ( isset($params['pdate']) ) { $sdate = explode ( '-', $params['pdate'] ); if ( count($pdate) == 3 ) { list ( $y, $m, $d ) = $pdate; $this->pdate = mktime ( 0, 0, 0, $m, $d, $y ); } } } public function insert() { // Does the Article object already have an ID? if ( !is_null( $this->id ) ) trigger_error ( "Article::insert(): Attempt to insert an Article object that already has its ID property set (to $this->id).", E_USER_ERROR ); // Insert the Article $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); $sql = "INSERT INTO books ( booktitle, author, edition, category, module, price, condition, description, image, pdate ) VALUES ( :booktitle, :author, :edition, :category, :module, :price, :condition, :description, :image, FROM_UNIXTIME(:pdate) )"; $st = $conn->prepare ( $sql ); $st->bindValue( ":booktitle", $this->booktitle, PDO::PARAM_STR ); $st->bindValue( ":author", $this->author, PDO::PARAM_STR ); $st->bindValue( ":edition", $this->edition, PDO::PARAM_STR ); $st->bindValue( ":category", $this->category, PDO::PARAM_STR ); $st->bindValue( ":module", $this->module, PDO::PARAM_STR ); $st->bindValue( ":price", $this->price, PDO::PARAM_INT ); $st->bindValue( ":condition", $this->condition, PDO::PARAM_STR ); $st->bindValue( ":description", $this->description, PDO::PARAM_STR ); $st->bindValue( ":image", $this->image, PDO::PARAM_STR ); $st->bindValue( ":pdate", $this->pdate, PDO::PARAM_INT ); $st->execute(); $this->id = $conn->lastInsertId(); $conn = null; } I would truly appreciate if someone is able to figure out what is going wrong, btw i dont get any errors when i click the save it takes mw to the next page and show a message i have set saying the changes have been saved but it doesnt actually save to me database. If you have any questions or i need to explain more please let me know Thanks in advance Hello I have a text list that looks like this: Code: [Select] ACACIA-Acacia spp.-Australia AMANITAS-Amanita muscaria-Siberia AYAHUASCA-Yage-Amazon Basin ... continues... i am trying to create a script that if i placed that text like that in a textarea and submitted the form it would explode each line one at a time by the "-" and add it into a mysql database (COMMON_NAME, GENUS_SPECIES, NATIVE_TO) I dont want to have to submit these one at a time and im sure this is very simple to do just im not understanding how to explode each line. maybe a code like; 1. counts the total number of lines and places it in a variable called lines 2. do while $lines > 0 3. for each $line explode by "-" 4. insert each piece of the exploded line into the database as (COMMON_NAME, GENUS_SPECIES, NATIVE_TO) as piece 0,1, & 2 5. after inserted subtract 1 from $lines or something similar to that effect. any help is greatly appreciated1 hey, here is the code I am using. Code: [Select] mysql_connect("localhost","XXXXXX","XXXXXX") or die("Could not connect."); mysql_select_db("XXXXXX"); $query="SELECT * FROM VIDEO_SESSIONS"; $result=mysql_query($query); while ($db_field = mysql_fetch_assoc($result)) { $timeslider = $db_field['timeslider']; } $message=$_POST['message']; $name=$me['first_name']; if(isset($_POST['submit'])){ if(strlen($message)<1) { print "You did not input a message"; } else if(strlen($name)<1) { print "Please login with Facebook to post a message"; } else { $insertmessage="INSERT INTO CHAT_SESSIONS (user_id,user_message,current_time) VALUES ('$name', '$message', '$timeslider')"; mysql_query($insertmessage); echo mysql_error(); } } ?> I am getting this error everytime I try and INSERT into the database " 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 'current_time) VALUES ('Luke', 'Hello?', '00:23:00')' at line 2 " it works fine without the '$timeslider' which is a time stored on the database in the format 00:00:00 why does it not want to store the time back in a different table.. same format!? Hi guys, This is my first time to insert PDF into MySQL BLOB. Below is my form that i used Code: [Select] <?php <form enctype="multipart/form-data" name="frmUploadFile" action="ulf-exec.php" method="post"> <select name="title" id="title"> <option>xxx</option> <option>yyy</option> <option>zzz</option> </select> </label> <input name="des" type="text" class="dropdownlists1" id="des"></td> <input name="fileUpload" type="file" class="dropdownlists1" id="fileUpload" size="20" border=""></td> <input type="submit" name="button" id="button" value="Submit"> </form> ?> I have prepared my database based on the required but decided to test with echo just to confirm there's no issue with the code The action="ulf-exec.php" : Code: [Select] <?php function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } //Sanitize the POST values $title = clean($_POST['title']); $des = clean($_POST['des']); $fileUpload = $_POST['fileUpload']; if(empty($des) || $fileUpload == "none") die("You must enter both a description and file"); $fileHandle = fopen($fileUpload, "r"); $fileContent = fread($fileHandle, $fileUpload_size); $fileContent = addslashes($fileContent); $date = date('d').'-'.date('m').'-'.date('y'); $time = date('h').':'.date('i').':'.date('s'); echo "<h1>File Uploaded</h1>"; echo "The details of the uploaded file are shown below:<br><br>"; echo "<b>File name:</b> $fileUpload_name <br>"; echo "<b>File type:</b> $fileUpload_type <br>"; echo "<b>File size:</b> $fileUpload_size <br>"; echo "<b>Uploaded to:</b> $fileUpload <br><br>"; echo "<a href='uploadfile.php'>Add Another File</a>"; ?> This is the error: Code: [Select] Warning: fopen() [function.fopen]: Filename cannot be empty in /ulf-exec.php on line 30 Warning: fread(): supplied argument is not a valid stream resource in ulf-exec.php on line 31 Hey Guys, I have to insert some data in MySQL but it wont work . Please have a look. <?php // to values are set to empty $vatsim=""; $ivao=""; // values from form in other page are set if(isset($_POST["pilotid"])) $pilotid=$_POST["pilotid"]; if(isset($_POST["network"])) $network=$_POST["network"]; if(isset($_POST["vid"])) $vid=$_POST["vid"]; if(isset($_POST["pilot"])) $pilot=$_POST["pilot"]; // if value is that copy data in this value, otherways in that value if ($network == "IVAO") { $ivao="$vid";} if ($network == "VATSIM") { $vatsim="$ivao";} // connect db include(dbconnect.inc.php); // first sql to update some data in one table $sql = "UPDATE `360283`.`jos_users` SET `IPS` = \'1\' WHERE `jos_users`.`id` = \'$pilotid\'"; $result1 = mysql_query($sql); // 2nd sql to insert some data in other table $sql2 = "INSERT INTO `360283`.`IPS_Pilots` (`ID`, `Name`, `Hours`, `Flights`, `LastFlight`, `IVAO`, `VATSIM`, `Enabled`, `Rating`) VALUES ('$pilotid', '$pilot', NULL, NULL, NULL, '$ivao', '$vatsim', '1', '0');"; $result2 = mysql_query($sql2); // sql to check if it was succesful $sql3 = "SELECT * FROM `IPS_Pilots` WHERE `ID` = '$pilotid' LIMIT 0, 30 "; $result3 = mysql_query($sql3); $num3 = mysql_numrows($result3); // echo succesfull or not if (!$num3) { echo "Sorry, but I failed to apply this pilot."; } else { echo "Pilot succesfully applied."; } ?> Thanks Hallo I'm having a problem inserting $messageorder into mysql datebase. Otherwise works good. So there is no problem with database itself or mysql command too. I suspect there must be something in this code that mysql doesnt like. Also have to say that im able to sent email with $messageorder. Please take a look at the codee. Code: [Select] $messageorder = "\r\n" . 'Order:' . '<br><br><table>' . "\r\n"; $result3 = mysql_query("SELECT * FROM orderslist WHERE supplier='$supplier'") or die(mysql_error()); $data = array(); $data['' . $row3['id']] = $_POST['' . $row3['id']]; while($row3=mysql_fetch_array($result3)) { $value = $_POST['' . $row3['id']]; if ( $value == ""){ } else { $messageorder .= " <tr> <td class='H4'><strong>$row3[name]</strong></td> <td class='H4' align='center'>$value</td> <td class='H4'>$row3[unit]</td> </tr> "; } } $messageorder .= "</table>"; echo $messageorder; date_default_timezone_set('Europe/London'); $supplier=$_GET['order']; $delivery=$_POST['delivery']; $timestamp = date("H:i:s"); $datestamp = date('Y/m/d'); mysql_query ("INSERT INTO orders (id, datestamp, timestamp, supplier, ordertext, delivery ) VALUES ('', '$datestamp', '$timestamp', '$supplier', '$messageorder', '$delivery')"); If someone could help to find a solution I will appriciate ! Thank you very much [/code] Hi //open the connection $conn = mysql_connect("localhost", "techhom1_test", "pro176"); //pick the database to use mysql_select_db("testDB", $conn); //create the sql statement $sql = "INSERT INTO master_name values ('', '$firstname')"; //execute if (mysql_query($sql,$conn)){ echo "Record Added!"; } else{ echo "Somethin went wrong"; } the code above is insert code and working with out any errors but when i am submitting text into data using method below it is sending echo back Somethin went wrong.I think i am confused with the write name of the user table database is ***_test my tables are duty_number master_name in this _test user i am trying to add first name in master_name field so here is the submit code Code: [Select] <FORM ACTION=insert.php METHOD=POST> <P>text to add:<br> <input type=text name=master_name size=30> <p><input type=submit name=submit value=Insert Record></p> </FORM> My table below in Data base [code]Field Type Null Default Comments name_id smallint(5) Yes NULL name_dateaddedn datetime Yes NULL name_datemodified datetime Yes NULL firstname varchar(75) Yes NULL lastname varchar(75) Yes NULL can someone please look at the code and find the error for me Thanks Hello, i'm trying to server-side validate input from POST to insert it into mysql if the requirements for the insert are met. i was using jquery before but this isn't reliable at all, i want the data to get inserted into mysql only if the length is 19 chars and only if it starts with 3227580 the next 12 digits can be any number. So basically: IF chars=19 and data=3227580* insert into mysql -- else show error Thank you for help. Hi all I am trying to write a script that takes the filename and username from a form and adds it into a mySQL database. At the moment only the username is added? Here's my code: <?php include('includes/connection.php'); $username = $_POST['username']; date_default_timezone_set('Europe/London'); // Change time zone to GMT $date = date ('D M j G:i:s'); // Set date format $path= "/home/cndvizp/public_html/prints2impress.co.uk/images/uploads/".$HTTP_POST_FILES['ufile']['name']; if($ufile !=none) { if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path)) { //insert new query $filename = $_FILES['ufile']['name']; $pfw_strQuery = "INSERT INTO `uploads`(`username`,`url`,`date_entered`)VALUES (\"$username\",\"$filename\",\"$date\")" ; $pfw_result = mysql_query($pfw_strQuery); if (!$pfw_result) { die('Invalid query: ' . mysql_error()); } //include ('payment.php'); echo 'done'; } else { //include ('error.php'); echo 'error!'; exit; } } ?> Can anyone help me get the filename and the date to be added? Cheers Pete. Hi Guys Clearly I still have lots to learn... I am trying to insert (using mysqli) multi-dimensional array values into the database, but when i do the value that gets stored ends up as "$Array[1][1]". Here's the test query i am running: Code: [Select] $sql = "INSERT INTO teams (company) VALUES ('$myarray[1][1]')"; $mysqli->query($sql); So do i need to break the data out of the multidimensional array for the insert? Or is there some syntax thing i've missed? Or worse still do i actually need to do: Code: [Select] $value1 = $myarray[0][0]; Any help would be very much appreciated! Drongo Hi People i'm a newb at this so bare with me but i currently have a php file called Newkpi.php which has a select statement in. this selects data from a table called "StaffList". this then populates the page with a html table with 14 records (this will increase/decrease over time) i then have some extra text boxes to enter more detail into like service amaount service date and so on. when i click the submit button i want it to cycle through each row and insert the data into a separate table called "Services". however i cannot for the life of me get this to work and need some help with it. people find attached the code for Newkpi and see if you can help me with this. in total i want it to take the names from stafflist and populate Services with the names and the extra detail which is entered on the page Much Thanx in advance SLOWIE I'm sorry to be back so soon, but I'm up against another mystery. I'm using the code below to enter a bunch of css data from a spreadsheet into a mysql table. I think the data file is OK. The array created by the script checks out with print_r. (There are many more records than shown. I truncated it to save space.) The problem is that I get this error regarding my sql statement, not the data or anything else: Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'check, name, phone, email, entry_fee, print_fee, image_name, description, med...' at line 1 in /Users/studio/Sites/BannerProject/b-as/_test_site/csv_to_array.php:242 Stack trace: #0 /Users/studio/Sites/BannerProject/b-as/_test_site/csv_to_array.php(242): PDO->prepare('INSERT INTO tbl...') #1 {main} thrown in /Users/studio/Sites/BannerProject/b-as/_test_site/csv_to_array.php on line 242 I've typed it in a dozen times to make sure there are no errors and keep getting the same error. I tried running a test file and gradually increasing the number of placeholders and at some point I always end up getting the same error, I can delete the most recent addition and it works again. Then I can add another placeholder exactly as before and it works the second time. It feels like a ghost in the machine. Any idea what I am doing wrong? An I typing something I don't see? <?php require '__classes/Db.php'; $csvData = '1,FALSE,Carol Lettko,,,TRUE,FALSE,Carol_Lettko-DSC_3022.jpg,Baby Herons/Brickyard,photo,,, ,,,925-285-0320,cjl164@aol.com,,,Carol_Lettko-DSC_0164.JPG,Heron/Brickyard,photo,,, ,,,,,,,Carol_Lettko-IMG_5723.jpg,Kayaker/Brickyard,photo,,, ,,,,,,,,,,,, 2,FALSE,Louise Williams,,,TRUE,FALSE,Louise_Williams-BirdsOfAFeatherAOPR.jpg,Alligator with Words,Book Excerpt,,, ,,,510-232-9547,lkw@louisekwilliams.com,,,Louise_Williams-Hope-TheFairyChickenAOPR.jpg,Hope The Fairy Chicken,,,, ,,,The d exatrfrfvct/.*tygrvurr,,,,,,,,, ,,,,,,,,,,,, 3,TRUE,Dorothy Leeland,,lelanddorothy@gmail.com,TRUE,FALSE,DJ_Lee-bridge at dusk 700px width.jpg,Bridge,photo,,, ,,,,,,,DJ_Lee-friends 700px width.jpg,Friends,photo,,, ,,,,,,,DJ_Lee-hybiscus 700 px wide.jpg,Hibiscus,photo,,, ,,,,,,,,,,,, 4,FALSE,Rita Gardner,,,TRUE,FALSE,Rita_Gardner-Explosion - Gardner photo.JPG,Explosion,photo,,, ,,,,tropicrita@msn.com,,,Rita_Gardner-Ferry Point tables and chair - Gardner.JPG,Ferry Point Tables,photo,, , ,,,,,,,Rita_Gardner-Forks - Gardner photo.JPG,Forks,photo,,, ,,,,,,,,,,,, '; $lines = explode(PHP_EOL, $csvData); $array1 = array(); foreach ($lines as $line) { $array1[] = str_getcsv($line); } $stmt = $pdo->prepare("INSERT INTO tbl_person_data (number, check, name, phone, email, entry_fee, print_fee, image_name, description, medium, select, orient, site) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"); foreach ($array1 as $row) { $stmt->execute('$row'); } echo '<pre>'; print_r($array1); echo '</pre>'; ?>
I built a series of insertion forms to put entries into a mysql database. Everything is working fine, except that I just now realized my checkboxes don't put any entry in. It's just leaving it's respective smallint field as a default "0". Being new, I've must've overlooked how to handle these. The form's checkboxes have a bit of code in the value that remembers what users chose in case they have to backtrack and redo their form. How would I solve the problem and keep this code? Here's what all the checkboxes are written like: Code: [Select] <input type="checkbox" name="green_leaf" value="<?php if(isset($_POST['1'])) echo $_POST['1']; ?>" > green Hello everyone, Once again i need your help this time i want to know that, if I inserting multiple row by single insert query with the help of foreach (loop) then how to insert another cell value according to the name wise so that's way i send my hole code to you. <?php //include configuration file for connection include_once('config.php'); $sql = "select * from CLASS_STUDENT ORDER BY STUDENT_NAME ASC "; $result=mysql_query($sql); $count=mysql_num_rows($result); ?> <form name="form1" method="post" action=""> <table style="text-align: left; padding: 5px;" cellpadding="0px" cellspacing="0px"> <tbody> <tr> <th style="text-align: center; padding: 5px; border: 1px #000000 solid;">Student Name</th> <th style="text-align: center; padding: 5px; border: 1px #000000 solid;">Student Class</th> <th style="text-align: center; padding: 5px; border: 1px #000000 solid;">Student Section</th> <th style="text-align: center; padding: 5px; border: 1px #000000 solid;">Current Date</th> <th style="text-align: center; padding: 5px; border: 1px #000000 solid;">Student Present</th> <th style="text-align: center; padding: 5px; border: 1px #000000 solid;">Student Absent</th> <th style="text-align: center; padding: 5px; border: 1px #000000 solid;">Comment</th> </tr> <?php while($rows=mysql_fetch_array($result)) { ?> <tr> <td class="table1"> <? $id[] = $rows['STUDENT_NAME']; ?><? echo $rows['STUDENT_NAME'];?> </td> <td class="table1"> <input name="class[<? echo $rows['STUDENT_NAME']; ?>]" type="text" value="<? echo $rows['STUDENT_CLASS']; ?>"> </td> <td class="table1"> <input name="section[<? echo $rows['STUDENT_NAME']; ?>]" type="text" value="<? echo $rows['STUDENT_SECTION']; ?>"> </td> <td class="table1"> <input name="date[<? echo $rows['STUDENT_NAME']; ?>]" type="text" value="<? echo $rows['PRESENT_DATE']; ?>"> </td> <td id="present"> <input type="radio" name="present[<? echo $rows['STUDENT_NAME']; ?>]" checked="checked" value="PRESENT">Present </td> <td id="absent"> <input type="radio" name="present[<? echo $rows['STUDENT_NAME']; ?>]" value="ABSENT">Absent </td> <td style="text-align: left; padding: 5px; border: 1px #000000 solid; height: 33px;"> <input name="comment[<? echo $rows['STUDENT_NAME']; ?>]" type="text" value="<? echo $rows['COMMENT'];?>"> </td> </tr> <?php }?> <tr> <td colspan="7" style="vertical-align:middle; text-align: center;"><br><br> <input id="Submit" type="submit" name="Submit" value="Insert" style="text-align: center; background-color: #000000; color: #ffffff; border: 1px #000000 solid;"> </td> </tr> </tbody> </table> </form> <?php if(isset($_POST['Submit'])) { foreach($_POST['present'] as $id => $value) { $class=$_POST['class']; $section=$_POST['section']; $date=$_POST['date']; $comment=$_POST['comment']; $sql = "INSERT INTO ATTENDANCE(STUDENT_NAME, STUDENT_CLASS, STUDENT_SECTION, PRESENT_DATE, STUDENT_PRESENT, COMMENT) VALUES ('".$id."', '$class[$value]', '$section[$value]', '$date[$value]', '".$value."', '$comment[$value]') "; $result = mysql_query($sql); } } if($result) { header("location:Tea_home.php"); } else { //print_r ($_POST); echo "Your entry is not completed at this time............."; } ?> My result is comming just like that STUDENT_ID || STUDENT_NAME || STUDENT_CLASS || STUDENT_SECTION || PRESENT_DATE || STUDENT_PRESENT ||COMMENT 231 || PRASHANT KUMAR || || || 1/1/0001 12:00:00 AM || ABSENT || 230 || JYOTI NANDA || || || 1/1/0001 12:00:00 AM || PRESENT || 229 || TARUN NANDA || || || 1/1/0001 12:00:00 AM || PRESENT || 228 || RAVI KUMAR || || || 1/1/0001 12:00:00 AM || PRESENT || 227 || RAJIV KUMAR || || || 1/1/0001 12:00:00 AM || PRESENT || 226 || PRASHANT KUMAR || || || 1/1/0001 12:00:00 AM || ABSENT || 225 || JYOTI NANDA || || || 1/1/0001 12:00:00 AM || PRESENT || can you help me where i am writing wrong code I have two webpages, login_success.php and formentered.php login_success.php is a page where i am entering new information and enteredvalues.php is supposed to be a script to enter the information into mysql. So far I got the login_success page to redirect to enteredvalues.php when submit is clicked but the information in the fields isn't transferring to mysql and neither is the page redirecting back to login_success. Here are both my codes Login_success.php <? session_start(); if(!session_is_registered(myusername)){ header("location:main_login.php"); } ?> <html><title>ChronoServe - Saving Time</title> <link href="style.css" rel="stylesheet" type="text/css"> <body> <table width="100%" border="0" cellpadding="0" cellspacing="0" class="container"> <tr> <td><form name="form2" method="post" action="entervalues.php"> <table width="335px" height="50%" border="1" align="center" cellpadding="0" cellspacing="0" class="centered"> <tr> <td><table width="100%" border="0" align="center" cellpadding="3" cellspacing="10"> <tr> <td colspan="2"><div align="center" class="font2">Activation Information</div></td> </tr> <tr> <td colspan="2"></td> </tr> <tr> <td width="40%" class="font3">First Name :</td> <td width="60%"> <div align="center"> <input name="firstname" type="text" class="font3" id="firstname" /> </div></td> </tr> <tr> <td class="font3">Last Name :</td> <td> <div align="center"> <input name="lastname" type="text" class="font3" id="lastname" /> </div></td> </tr> <tr> <td height="28" class="font3">Phone Number :</td> <td> <div align="center"> <input name="pnumber" type="text" class="font3" id="pnumber" /> </div></td> </tr> <tr> <td class="font3">Personnel Activated :</td> <td> <div align="center"> <input name="numbactivated" type="text" class="font3" id="numbactivated" /> </div></td> </tr> <tr> <td height="37" colspan="2"></td> </tr> <tr> <td colspan="2"><div align="center"> <input name="insert" type="submit" class="font3" value="Submit" /> </div></td> </tr> </table></td> </tr> </form> </table> </td> </tr> </table> </body> </html> Here is enteredvalues.php <?php $host=""; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name=""; // Database name $tbl_name=""; // Table name // 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"); // Define $myusername and $mypassword $firstname=$_POST['firstname']; $lastname=$_POST['lastname']; $pnumber=$_POST['pnumber']; $numberactivated=$_POST['numberactivated']; // To protect MySQL injection (more detail about MySQL injection) $firstname = stripslashes($firstname); $lastname = stripslashes($firstname); $firstname = mysql_real_escape_string($firstname); $lastname = mysql_real_escape_string($lastname); $pnumber = stripslashes($pnumber); $numberactivated = stripslashes($numberactivated); $pnumber = mysql_real_escape_string($pnumber); $numberactivated = mysql_real_escape_string($numberactivated); $sql="INSERT INTO $tbl_name (firstname, lastname, pnumber, numberactivated,) VALUES ('$firstname','$lastname','$pnumber','$numberactivated')")or die(mysql_error()); $r = mysql_query($sql); if(!$r) { $err=mysql_error(); print $err; header("location:login_success.php"); exit(); } ?> |