PHP - Inserting Into Php/mysql
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 Similar TutorialsHi 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 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 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 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 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 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, 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!? 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 Hello, me again. I have created a little forum - very very basic. main_forum.php : Code: [Select] <?php $host="localhost"; // Host name $username="yvonnedp"; // Mysql username $password="yvonne"; // Mysql password $db_name="forum"; // Database name $tbl_name="forum_question"; // Table name // Connect to server and select databse. mysql_connect('localhost', 'yvonnedp', 'yvonne')or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $sql="SELECT * FROM $tbl_name ORDER BY id"; // OREDER BY id DESC is order result by descending $result=mysql_query($sql); ?> <table width="90%" border="0" align="center" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC"> <tr> <td width="6%" align="center" bgcolor="#E6E6E6"><strong>#</strong></td> <td width="53%" align="center" bgcolor="#E6E6E6"><strong>Topic</strong></td> <td width="15%" align="center" bgcolor="#E6E6E6"><strong>Views</strong></td> <td width="13%" align="center" bgcolor="#E6E6E6"><strong>Replies</strong></td> <td width="13%" align="center" bgcolor="#E6E6E6"><strong>Date/Time</strong></td> </tr> <?php while($rows=mysql_fetch_array($result)){ // Start looping table row ?> <tr> <td bgcolor="#FFFFFF"><? echo $rows['id']; ?></td> <td bgcolor="#FFFFFF"><a href="view_topic.php?id=<? echo $rows['id']; ?>"><? echo $rows['topic']; ?></a><BR></td> <td align="center" bgcolor="#FFFFFF"><? echo $rows['view']; ?></td> <td align="center" bgcolor="#FFFFFF"><? echo $rows['reply']; ?></td> <td align="center" bgcolor="#FFFFFF"><? echo $rows['datetime']; ?></td> </tr> <?php // Exit looping and close connection } mysql_close(); ?> create_topic.php : Code: [Select] <table width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC"> <tr> <form id="form1" name="form1" method="post" action="add_topic.php"> <td> <table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF"> <tr> <td colspan="3" bgcolor="#E6E6E6"><strong>Create New Topic</strong> </td> </tr> <tr> <td width="14%"><strong>Topic</strong></td> <td width="2%">:</td> <td width="84%"><input name="topic" type="text" id="topic" size="50" /></td> </tr> <tr> <td valign="top"><strong>Detail</strong></td> <td valign="top">:</td> <td><textarea name="detail" cols="50" rows="3" id="detail"></textarea></td> </tr> <tr> <td><strong>Name</strong></td> <td>:</td> <td><input name="name" type="text" id="name" size="50" /></td> </tr> <tr> <td> </td> <td> </td> <td><input type="submit" name="Submit" value="Submit" /> <input type="reset" name="Submit2" value="Reset" /></td> </tr> </table> </td> </form> </tr> </table> add_topic.php : Code: [Select] <?php $host="localhost"; // Host name $username="yvonnedp"; // Mysql username $password="yvonne"; // Mysql password $db_name="forum"; // Database name $tbl_name="forum_question"; // Table name // Connect to server and select database. mysql_connect('localhost', 'yvonnedp', 'yvonne')or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // get data that sent from form $topic=$_POST['topic']; $detail=$_POST['detail']; $name=$_POST['name']; $datetime=date("d/m/y h:i:s"); //create date time $sql="INSERT INTO $tbl_name(topic, detail, name, datetime)VALUES('$topic', '$detail', '$name', '$datetime')"; $result=mysql_query($sql); if($result){ echo "Successful<BR>"; echo "<a href=main_forum.php>View your topic</a>"; $email_from = "forums@thenewme.co.za"; $email_to = "info@thenewme.co.za"; $email_subject = "The New Me - New Forum Topic"; $email_message = "A new topic has been posted on the Forum!\n"; $email_message .= "Check it out : http://www.thenewme.co.za/forum/main_forum.php"; $headers = 'From: '.$email_from."\r\n"; 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); } else { echo "ERROR"; } mysql_close(); ?> add_answer.php : Code: [Select] <?php $host="localhost"; // Host name $username="yvonnedp"; // Mysql username $password="yvonne"; // Mysql password $db_name="forum"; // Database name $tbl_name="forum_answer"; // Table name // Connect to server and select databse. mysql_connect('localhost', 'yvonnedp', 'yvonne')or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // Get value of id that sent from hidden field $id=$_POST['id']; // Find highest answer number. $sql="SELECT MAX(a_id) AS Maxa_id FROM $tbl_name WHERE question_id='$id'"; $result=mysql_query($sql); $rows=mysql_fetch_array($result); // add + 1 to highest answer number and keep it in variable name "$Max_id". if there no answer yet set it = 1 if ($rows) { $Max_id = $rows['Maxa_id']+1; } else { $Max_id = 1; } // get values that sent from form $a_name=$_POST['a_name']; $a_answer=$_POST['a_answer']; $datetime=date("d/m/y H:i:s"); // create date and time // Insert answer $sql2="INSERT INTO $tbl_name(question_id, a_id, a_name, a_answer, a_datetime)VALUES('$id', '$Max_id', '$a_name', '$a_answer', '$datetime')"; $result2=mysql_query($sql2); if($result2){ echo "Successful<BR>"; echo "<a href='view_topic.php?id=".$id."'>View your answer</a>"; // If added new answer, add value +1 in reply column $tbl_name2="forum_question"; $sql3="UPDATE $tbl_name2 SET reply='$Max_id' WHERE id='$id'"; $result3=mysql_query($sql3); $email_from = "forums@thenewme.co.za"; $email_to = "info@thenewme.co.za"; $email_subject = "The New Me - New Forum Answer"; $email_message = "A new answer to a forum topic has been posted on the Forum!\n"; $email_message .= "Check it out : http://www.thenewme.co.za/forum/main_forum.php"; $headers = 'From: '.$email_from."\r\n"; 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); } else { echo "ERROR"; } mysql_close(); ?> view_topic : Code: [Select] <?php $tbl_name2="forum_answer"; // Switch to table "forum_answer" $sql2="SELECT * FROM $tbl_name2 WHERE question_id='$id'"; $result2=mysql_query($sql2); while($rows=mysql_fetch_array($result2)){ ?> <table width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC"> <tr> <td><table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF"> <tr> <td bgcolor="#F8F7F1"><strong>ID</strong></td> <td bgcolor="#F8F7F1">:</td> <td bgcolor="#F8F7F1"><? echo $rows['a_id']; ?></td> </tr> <tr> <td width="18%" bgcolor="#F8F7F1"><strong>Name</strong></td> <td width="5%" bgcolor="#F8F7F1">:</td> <td width="77%" bgcolor="#F8F7F1"><? echo $rows['a_name']; ?></td> </tr> <tr> <td bgcolor="#F8F7F1"><strong>Answer</strong></td> <td bgcolor="#F8F7F1">:</td> <td bgcolor="#F8F7F1"><? echo $rows['a_answer']; ?></td> </tr> <tr> <td bgcolor="#F8F7F1"><strong>Date/Time</strong></td> <td bgcolor="#F8F7F1">:</td> <td bgcolor="#F8F7F1"><? echo $rows['a_datetime']; ?></td> </tr> </table></td> </tr> </table><br> <? } $sql3="SELECT view FROM $tbl_name WHERE id='$id'"; $result3=mysql_query($sql3); $rows=mysql_fetch_array($result3); $view=$rows['view']; // if have no counter value set counter = 1 if(empty($view)){ $view=1; $sql4="INSERT INTO $tbl_name(view) VALUES('$view') WHERE id='$id'"; $result4=mysql_query($sql4); } // count more value $addview=$view+1; $sql5="update $tbl_name set view='$addview' WHERE id='$id'"; $result5=mysql_query($sql5); mysql_close(); ?> the problem is. With add_answer, I am not able to insert an answer. This has worked for the very first question, but all subsequent questions, I am unable to add answers. It keeps telling me ERROR. This is where the live forum is : http://www.thenewme.co.za/forum/main_forum.php Can it be an issue with the field that gets autmatically incremented? i have echo'd the data which get entered in when someone types in an answer, and everything is perfect! Can anyone help me? hello dear experts
good day dear friend - i need your help. import urllib import urlparse import re # import peewee import json from peewee import * #from peewee import MySQLDatabase ('cpan', user='root',passwd='rimbaud') db = MySQLDatabase('cpan', user='root',passwd='rimbaud') class User(Model): name = TextField() cname = TextField() email = TextField() url = TextField() class Meta: database = db # this model uses the cpan database User.create_table() #ensure table is created url = "http://search.cpan.org/author/?W" html = urllib.urlopen(url).read() for lk, capname, name in re.findall('<a href="(/~.*?/)"><b>(.*?)</b></a><br/><small>(.*?)</small>', html): alk = urlparse.urljoin(url, lk) data = { 'url':alk, 'name':name, 'cname':capname } phtml = urllib.urlopen(alk).read() memail = re.search('<a href="mailto:(.*?)">', phtml) if memail: data['email'] = memail.group(1) data = json.load('email') #your json data file here for entry in data: #assuming your data is an array of JSON objects user = User.create(name=entry["name"], cname=entry["cname"], email=entry["email"], url=entry["url"]) user.save() guess that there a data-file must exist: one that have been created by the script during the parsing... is this right? ) martin@linux-70ce:~/perl> python cpan_100.py Traceback (most recent call last): File "cpan_100.py", line 47, in <module> data = json.load('email') #your json data file here File "/usr/lib/python2.7/json/__init__.py", line 286, in load return loads(fp.read(), AttributeError: 'str' object has no attribute 'read' martin@linux-70ce:~/perl> this script does not work ) martin@linux-70ce:~/perl> python cpan_100.py Traceback (most recent call last): File "cpan_100.py", line 47, in <module> data = json.load('email') #your json data file here File "/usr/lib/python2.7/json/__init__.py", line 286, in load return loads(fp.read(), AttributeError: 'str' object has no attribute 'read' martin@linux-70ce:~/perl>well i suppose that in the first part of the script - the parser - part we parse data and - therefore we should create a file. I guess that this file is taken up within the second part of the script... load data . well why the script does not work!? Hello, i made a text site, so you can text from a website. i was making a database of the texted numbers and i found that the mysql line is not inserting the correct number, its going to the max php one. Here the code: if (array_key_exists($carrier, $carriers)) { $correctCarrier = $carriers[$carrier]; $i = 0; while($i < $_POST['amount']){ $i++; $formatted_number = $to.$correctCarrier; $result = ("$i of Your Messages Has been sent to the number ". $_POST['to'] . ".<br>" . mail("$formatted_number", "$subject", "$message") . ""); } mysql_query("INSERT INTO `msgssent` (`number`, `numberofmsg`, `subject`, `message`) VALUES (". $_POST['to'] .", '". $i ."', '". $subject ."', '". $message ."')") Or die(mysql_error()); Echo $result; } 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 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. hello friends, actually i am trying to insert data in mysql database. here is my code <?php include_once("../includes/database.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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Insert Product</title> </head> <body> <form action="insert_product.php" method="post" enctype="multipart/form-data"> <table align="center" width="600"> <tr align="center"> <td colspan="8"><h2> Insert New Post</h2></td> </tr> <tr> <td align="right"><b>Product Title :</b></td> <td><input type="text" name="product_title" size="50" style="background-color:#06C; color:#FFF" /></td> </tr> <tr> <td align="right"><b>Product Category :</b></td> <td> <select name="product_cat" style="background-color:#06C; color:#FFF" > <option>Select A Category </option> <?php $get_cats = "SELECT * FROM categories"; $run_cats = mysqli_query($con, $get_cats); while($row_cats = mysqli_fetch_array($run_cats)){ $cat_id = $row_cats['cat_id']; $cat_title = $row_cats['cat_title']; echo "<option value='$cat_id'>$cat_title</option>"; } ?> </select> </td> </tr> <tr> <td align="right"><b>Product Platform :</b></td> <td> <select name="product_brand" style="background-color:#06C; color:#FFF" > <option>Select A Platform </option> <?php $get_brands = "SELECT * FROM brands"; $run_brands = mysqli_query($con, $get_brands); while($row_brands = mysqli_fetch_array($run_brands)){ $brand_id = $row_brands['brand_id']; $brand_title = $row_brands['brand_title']; echo "<option value='$brand_id'>$brand_title</option>"; } ?> </select> </td> </tr> <tr> <td align="right"><b>Product Image :</b></td> <td><input type="file" name="product_image" /></td> </tr> <tr> <td align="right"><b>Product Price :</b></td> <td><input type="text" name="product_price" style="background-color:#06C; color:#FFF" /></td> </tr> <tr> <td align="right" valign="top"><b>Product Description :</b></td> <td><textarea name="product_desc" cols="50" rows="10" style="background-color:#06C; color:#FFF" ></textarea></td> </tr> <tr> <td align="right"><b>Product Keywords :</b></td> <td><input type="text" name="product_keywords" size="50" style="background-color:#06C; color:#FFF" /></td> </tr> <tr align="center"> <td colspan="8"><input type="submit" name="insert_post" value="Submit Now" /></td> </tr> </table> </form> </body> </html> <?php if(isset($_POST['insert_post'])){ $product_title = $_POST['product_title']; $product_cat = $_POST['product_cat']; $product_brand = $_POST['product_brand']; $product_price = $_POST['product_price']; $product_desc = $_POST['product_desc']; $product_keywords = $_POST['product_keywords']; $product_image = $_FILES['product_image']['name']; $product_image_tmp = $_FILES['product_image']['tmp_name']; move_uploaded_file($product_image_tmp,"product_image/$product_image"); $sql = "INSERT INTO products (product_cat,product_brand,product_title,product_price,product_desc,product_image,product_keywords) VALUES ('$product_cat','$product_brand','$product_title','$product_price','$product_desc','$product_image','$product_keywords')"; $query = mysqli_query($con, $sql); if($query){ echo "<script>alert('Product Has Been Inserted')</script>"; echo "<script>windoow.open('insert_product.php','_self')</script>"; exit(); }else{ echo "<script>alert('errror')</script>"; } } ?>but somehow its not inserting data into my table can somebody tell wherre m i doing mistake. the categories and brands are displaying from database. But its not inserting data here is my database script. <?php $con = mysqli_connect("localhost","root","","sg"); ?> 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 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 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 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(); } ?> 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. |