PHP - Insert Php + Mysql Data Into A Form
Hi.
I'm making a private webpage for my self where i can post news, games, music titles and movies. I'm made it so that i can post and delete them from my page. Also i wanted to have the option to edit them. So i made a action that shows me a list og the posts in each category. And then i want the option to hit UPDATE, and then it should open the form with the info's from MySQL. I've made those two options as the following: Code: [Select] elseif ( $action == "EditNews" ) { // EDIT NEWS START if ( !$_GET['id'] ) { ?> <div id="content"> <?php $sql = mysql_query("SELECT * FROM news") or die(mysql_error()); while ( $row = mysql_fetch_assoc($sql) ) { echo "<a href=\"?page=Admin&action=UpdateNews&id=" . $row['news_id'] . "\">Update</a> | " . $row['subject'] . "<br>"; } echo "</div>"; } else { $type = $_GET['type']; $id = $_GET['id']; } // EDIT NEWS END } elseif ( $action == "UpdateNews" ) { // UPDATE NEWS START if ( !$_POST['submit'] ) { $id = $_GET['id']; $sql = mysql_query("SELECT * FROM news WHERE news_id='$id'") or die(mysql_error()); $user_id = $_SESSION['uid']; $subject = $_row['subject']; $body = nl2br($_row['body']); ?> <div id="content"> <form action="?page=Admin&action=EditNews" method="post"> <div id="">Subject</div> <div id=""><input id="input" type="text" name="subject"></div> <div id="">Message</div> <div id=""><textarea id="input" name='body' cols='15' rows='4'></textarea></div> <div id=""><input id="submit" class="input" type="submit" name="submit" value="Post News"></div> </form> </div> <?php } else { ?> <div id="content">Not Working!</div> <?php } // UPDATE NEWS END } - I know i miss something, but i've tried to get to the point, where i only have the form as blank, and need some help from there. I hope someone can help me with my problem. MOD EDIT: [code] . . . [/code] tags added. Similar TutorialsNot sure exactly what my problem is here, but i have looked at this at least a hundred times and I just can't figure out what is going on. Everything works great except for the sending the email part. It displays the error "There was a problem sending the mail". The form field checking works fine, the insert into mysql works fine - - but it won't send the email. I have tried using double quotes and single quotes for the email information ($to, $subject, etc...) I have even eliminated the form data from the email information and it still doesn't send. I am hopelessly stuck at this point Any ideas?? Code below: <html> <body bgcolor = 'blue'> <div align = 'center'> <h1>test FORM</h1> </div> <p> <?php If ($_POST['submit']) //if the Submit button pressed { //collect form data $fname = $_POST['FName']; $lname = $_POST['LName']; $email = $_POST['Email']; $tel = $_POST['Tel']; $mess = $_POST['Mess']; $errorstring = ""; if (!$fname) $errorstring = $errorstring."First Name<br>"; if (!$lname) $errorstring = $errorstring."Last Name<br>"; if (!$email) $errorstring = $errorstring."Email<br>"; if ($errorstring !="") echo "<div align = 'center'><b>Please fill out the following fields:</b><br><font color = 'red'><b>$errorstring</b></font></div>"; else { $fname = mysql_real_escape_string($fname); $lname = mysql_real_escape_string($lname); $email = mysql_real_escape_string($email); $tel = mysql_real_escape_string($tel); $mess = mysql_real_escape_string($mess); $con = mysql_connect("localhost","user","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("mec", $con); $sql="INSERT INTO formtest (FName, LName, Title, Tel, Email, Mess) VALUES ('$fname','$lname','$title','$tel','$email','$mess')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } $to = 'myemailaddress'; $subject = 'test form'; $message = 'Hello'; $headers = 'From Me'; $sent = mail($to, $subject, $message, $headers); if($sent) {print "Email successfully sent";} else {print "There was an error sending the mail";} mysql_close($con); } } ?> <p> <form action= 'testmecform.php' method= 'POST'> <table width = '640' border = '0' align = 'center'> <tr> <td align = 'right'><b>First Name</b></td> <td><input type = 'text' name = 'FName' value = '<?php echo $fname; ?>' size = '25'></td> <td><div align = 'right'><b>Telephone</b></div></td> <td><input type = 'text' name = 'Tel' value = '<?php echo $tel; ?>' size = '25'></td> </tr> <tr> <td align = 'right'><b>Last Name</b></td> <td><input type = 'text' name = 'LName' value = '<?php echo $lname; ?>' size = '25'></td> <td> </td> <td> </td> </tr> <tr> <td align = 'right'><b>Email</b></td> <td><input type = 'text' name = 'Email' value = '<?php echo $email; ?>' size = '25'></td> <td> </td> <td> </td> </tr> <tr> <th colspan = '4'><b>Please enter any additional information he </b></th> </tr> <tr> <th colspan = '4'><textarea name = 'Mess' cols = '50' rows = '10'><?php echo $mess; ?></textarea></th> </tr> <tr> <th colspan = '4'><b>Please make sure all information is correct before submitting</b></th> </tr> <tr> <th colspan = '4'><input type = 'submit' name = 'submit' value = 'Submit Form'></th> </tr> </table> </form> </body> </html>
Array ( [data] => Array ( [0] => Array ( [latitude] => 22.934566 [longitude] => 79.08728 [type] => county [distance] => 44.328 [name] => Narsinghpur [number] => [postal_code] => [street] => [confidence] => 0.5 [region] => Madhya Pradesh [region_code] => MP [county] => Narsinghpur [locality] => [administrative_area] => [neighbourhood] => [country] => India [country_code] => IND [continent] => Asia [label] => Narsinghpur, India ) ) ) Hi guys, I have an array: array ( [apple]=> red, [orange] => orange, [banana] => yellow ) That I want to insert into the apidata table, the PDO connection is good so I guess my code is wrong: $mykeys = implode(', ', array_keys($newarr)); $myplaceholders[] = '(' . implode (", ", array_fill(0, count($newarr), '?')) . ')'; $values = array_values($newarr); $res = $db->prepare("INSERT INTO apidata (item, value) VALUES $myplaceholders") ; $res->execute([$mykeys, $values]); The apidata table has three fields id (auto_increment) item and value, where am I going wrong? Thanks I am trying to display data from mysql. Each row from the mysql database shows up under rows. I want the rows of data from mysql to appear in colums of 4. can some one help please. <?php $sql = 'SELECT * FROM dbtable ORDER BY id'; $result = $db->query($sql); $output[] = '<ul>'; while ($row = $result->fetch()) { $output[] = '<table>'; $output[] = '<tr>'; $output[] = '<td class="style10"><strong>'.$row['item'].'</strong></td>'; $output[] = '</tr>'; $output[] = '<tr>'; $output[] = '<td><img src="images/'.$row['pic'].'" width="100" height="150" /></td>'; $output[] = '</tr>'; $output[] = '<tr>'; $output[] = '<td>'.$row['description'].'</td>'; $output[] = '</tr>'; $output[] = '</table>'; } echo join('',$output); ?> Hi, I'm having trouble adding data to the database (test) that i created. I just can't see where I'm going wrong. need some other peoples opinions. I have tried taking the id out of the SQL statement completely as it is an auto increment, but that doesn't seem to work either. Thanks in advance... <?php $fname = $_POST['fname']; $sname = $_POST['sname']; $email = $_POST['email']; $pword = $_POST['password']; $gender = $_POST['gender']; $user_name = "root"; $password = ""; $database = "test"; $server = "127.0.0.1"; $db_handle = mysql_connect($server, $user_name, $password); $db_found = mysql_select_db($database, $db_handle); if ($db_found) { $SQL = "INSERT INTO members (id, fname, sname, email, password, gender) VALUES (NULL, $fname, $sname, $email, $pword, $gender);"; $result = mysql_query($SQL); mysql_close($db_handle); print "Thanks for joining us ".$fname."."; print "<br /><br />"; print $fname . "<br />"; print $sname . "<br />"; print $email . "<br />"; print $pword . "<br />"; print $gender . "<br />"; } else { print "Database NOT Found"; mysql_close($db_handle); } ?> Hi there, hope u guys able to help. I'm have created a enquiry form where I want these actions to run when a button is submitted: 1. Insert data from form fields into my database 2. When data is inserted into database, then send an e-mail (multiple email user) to the address with the form fields. The e-mail is carrying the form fields. so ...what I need now is how to send the form field to email. Insert the data into my table in my database,then send en e-mail. Code: [Select] <? // Connects to your Database mysql_connect("xxxxxx","xxxxxx","xxxxxx") or die(mysql_error()); mysql_select_db("xxxxxx") or die(mysql_error()); // now we insert it into the database $insert = "INSERT INTO enquiry (name, email, cont_number, subject, msg) VALUES ('".$_POST['name']."', '".$_POST['email']."', '".$_POST['cont_number']."', '".$_POST['subject']."','".$_POST['msg']."')"; $add_member = mysql_query($insert); ?> <?php function error_bool($error, $field) { if($error[$field]) { print("<td style=color:red>"); } else { print("<td>"); } } function show_form() { global $HTTP_POST_VARS, $print_again, $error; ?> <h2 align="center"> Enquiry Form</h2> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <table align="center" cellpadding="3"> <tr> <?php error_bool($error, "name"); ?> Name </td> <td>:<input name="name" type="text" id="name" SIZE="33" value="<? echo $_POST["name"]; ?>"></td> </tr> <tr> <?php error_bool($error, "email"); ?> Email </td> <td>:<input name="email" type="text" id="email" SIZE="33" value="<? echo $_POST["email"]; ?>"></td> </tr> <tr><td>Contact No. </td><td> :<input type="text" name="cont_number" SIZE="33" maxlength="10"> </td></tr> <tr><td>Subject </td><td> :<input type="text" name="subject" SIZE="33" maxlength="25"> </td></tr> <tr><td>Your Message :</td><td> <textarea name="msg" cols="27" rows="5" wrap="virtual"></textarea> </td></tr> <tr> <td><th colspan=4 align="right"> <input type="reset" value="CLEAR"><input type="submit" name="Submit" value="Submit"></td> </th><td> </td> </tr> </table> </form> <? } if(isset($_POST["Submit"])) { check_form(); } else { show_form(); } function check_email_address($email) { // First, we check that there's one @ symbol, and that the lengths are right if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) { // Email invalid because wrong number of characters in one section, or wrong number of @ symbols. return false; } // Split it into sections to make life easier $email_array = explode("@", $email); $local_array = explode(".", $email_array[0]); for ($i = 0; $i < sizeof($local_array); $i++) { if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) { return false; } } if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name $domain_array = explode(".", $email_array[1]); if (sizeof($domain_array) < 2) { return false; // Not enough parts to domain } for ($i = 0; $i < sizeof($domain_array); $i++) { if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) { return false; } } } return true; } function check_form() { global $HTTP_POST_VARS, $error, $print_again; $error['name'] = false; if($_POST["name"]=="") { $error['name'] = true; $print_again = true; $message="The name field is empty<br>"; } if(!check_email_address($_POST['email'])) { $error['email'] = true; $print_again = true; $message.="Either Field Empty or Invalid Email ID <br>"; } if($print_again) { show_form(); } else { show_form(); $message="Thank You !! <br> Form has been submitted"; } echo "$message"; } ?> </body> </html> How do i do this? Thank you in advanced and sorry for bad English. Best regards, Desmond Hi all. Here is the code:(thanks to jcbones) Code: [Select] if (($handle = fopen($source_file, "r")) !== FALSE) { $columns = fgetcsv($handle, $max_line_length, ","); foreach ($columns as &$column) { $column = str_replace(".","",$column); } while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) { while(count($data) < count($columns)) { array_push($data, NULL); } $c = count($data); for($i = 0; $i < $c; $i++) { $data[$i] = "'{$data[$i]}'"; } $sql[] = '(' . implode(',',$data) . ','.$_POST[group].')'; } $sql = implode(',',$sql); $query = "INSERT INTO mytable (".mysql_real_escape_string(implode(",",$columns)).",Custgroup,user_id) VALUES " . $sql . "\n"; mysql_query($query) or trigger_error(mysql_error()); fclose($handle); } } If my csv file is: lastname,firstname,gender bob,ah,male So now the query will be : INSERT INTO mytable (lastname,firstname,gender) VALUES ('bob',ah','male'). But how if I want to insert extra data into mysql together with the data in csv file? Such as I have a value $_POST['group'] = 'family', so I tried: Code: [Select] $sql[] = '(' . implode(',',$data) . ','.$_POST[group].')'; $query = "INSERT INTO $target_table (".mysql_real_escape_string(implode(",",$columns)).",custgroup) VALUES " . implode(',',$sql) . "\n"; But in the query it will become : INSERT INTO mytable (lastname,firstname,gender,custgroup) VALUES ('bob',ah','male',family). It didn't have single quote , so I have error to insert the record.Can I know how to solve this problem? Thanks. Hi all . In my scripts , there is a textarea that allow user to enter multiple phone number , message and date . If there are 3 phone numbers in textarea , how can I insert 3 of them into sql with the same data of message and date? Such as : phone number : 0102255888,0235544777,0896655444 message:hello all date:10/10/2011 and when it's insert into table , it will become: 1. 0102255888 | hello all | 10/10/2011 2. 0235544777 | hello all | 10/10/2011 3. 0896655444 | hello all | 10/10/2011 Here is the code I tried , but it will just save the last phone number . Code: [Select] $cellphonenumber = explode(',', $_POST['cellphonenumber']); $message = $_POST['inputtext']; $date = $_POST['datetime']; foreach($cellphonenumber as $value) { $sql="INSERT INTO esp( Recipient , Message , Date) VALUES ('$value','$message','$date')"; } mysql_query($sql) or die ("Error: ".mysql_error()); echo "Database updated."; Any hints or advices ? Thanks for every reply . Hi to everybody I need ur help because I’m trying to make a script in php to write the same data but with different date in MySQL depending on the splitting ($data06).... like a schedule...
For example if $data06 = annual and $data03 = “2019/01/01” programm must create in MySQL : 2019/01/01 2020/01/01 2021/01/01 2022/01/01 2023/01/01
if $data06=“half year” will create 10 date , increasing 6 moths ...
But I have a problem at finish of code switch ($data06) { case 'annual': $numrate = 5; $aumdata = "+12 months"; break; case 'half year': $numrate = 10; $aumdata = "+6 month"; break;
default: echo "error"; $sql = "INSERT into $nometb ( name, scadenza ) values ( '$data01', '$data03' )"; if ($conna->query($sql) === TRUE) {} else {die('ERROR'. $conna->error); }
//IMPORT NEXT AND NEW DATE $newDate = date_create($data03); for ($mul = 2; $mul <= $numrate; ++$mul) {
$datanuova = date_create($data03); $datanuova->modify($aumdata); $datanuova->format('yy/m/d'); $newDate = $datanuova->format('yy/m/d');
$sql = "INSERT into $nometb ( name, scadenza ) values ( '$data01', '$newDate' )"; if ($conna->query($sql) === TRUE) {} else {die('ERROR'. $conna->error); }
//HERE THERE IS ERROR $data03 = $newDate;
if ($conna->query($sql) === TRUE) {} else {die('ERRORE NELL\'IMPORTAZIONE'. $conna->error); } }
} }
}
How I can resolve ?
many thanks Francesco Hi I have been trying to grab some data from an XML feed parse it and then insert it into a database. I will only need to do this on one occasion so no update or deletes. Sample of xml structu Code: [Select] <property> <id>34935</id> <date>2009-11-03 06:52:45</date> <ref>SVS0108</ref> <price>450000</price> <currency>EUR</currency> <price_freq>sale</price_freq> </property> Using xml2array class to parse the feed: <?php /** * xml2array Class * Uses PHP 5 DOM Functions * * This class converts XML data to array representation. * */ class Xml2Array { /** * XML Dom instance * * @var XML DOM Instance */ private $xml_dom; /** * Array representing xml * * @var array */ private $xml_array; /** * XML data * * @var String */ private $xml; public function __construct($xml = '') { $this->xml = $xml; } public function setXml($xml) { if(!empty($xml)) { $this->xml = $xml; } } /** * Change xml data-to-array * * @return Array */ public function get_array() { if($this->get_dom() === false) { return false; } $this->xml_array = array(); $root_element = $this->xml_dom->firstChild; $this->xml_array[$root_element->tagName] = $this->node_2_array($root_element); return $this->xml_array; } private function node_2_array($dom_element) { if($dom_element->nodeType != XML_ELEMENT_NODE) { return false; } $children = $dom_element->childNodes; foreach($children as $child) { if($child->nodeType != XML_ELEMENT_NODE) { continue; } $prefix = ($child->prefix) ? $child->prefix.':' : ''; if(!is_array($result[$prefix.$child->nodeName])) { $subnode = false; foreach($children as $test_node) { if($child->nodeName == $test_node->nodeName && !$child->isSameNode($test_node)) { $subnode = true; break; } } } else { $subnode = true; } if ($subnode) { $result[$prefix.$child->nodeName][] = $this->node_2_array($child); } else { $result[$prefix.$child->nodeName] = $this->node_2_array($child); } } if (!is_array($result)) { $result['#text'] = html_entity_decode(htmlentities($dom_element->nodeValue, ENT_COMPAT, 'UTF-8'), ENT_COMPAT,'ISO-8859-15'); } if ($dom_element->hasAttributes()) { foreach ($dom_element->attributes as $attrib) { $prefix = ($attrib->prefix) ? $attrib->prefix.':' : ''; $result["@".$prefix.$attrib->nodeName] = $attrib->nodeValue; } } return $result; } /** * Generated XML Dom * */ private function get_dom() { if(empty($this->xml)) { echo 'No XML found. Please set XML data using setXML($xml)'; return false; } $this->xml_dom = @DOMDocument::loadXML($this->xml); if($this->xml_dom) { return $this->xml_dom; } echo 'Invalid XML data'; exit; } } ?> My results page: <?php require_once('classes/xml2array.php'); require_once('conn.php'); function curlURL($url) { $ch= curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2) Gecko/20070219 Firefox/2.0.0.2'); $output = curl_exec($ch); return $output; } $curlResults = curlURL("http://localhost/alphashare_dump/property.xml"); $xml = $curlResults; $converter = new Xml2Array(); $converter->setXml($xml); $xml_array = $converter->get_array(); $array = ($xml_array['root']['property']); echo "<pre>"; print_r($array); echo "</pre>"; ////////////// INSERT DATA INTO DB //////////////////////////////////////////////////// ?> My array structure looks like this: Code: [Select] Array ( [0] => Array ( [id] => Array ( [#text] => 34935 ) [date] => Array ( [#text] => 2009-11-03 06:52:45 ) [ref] => Array ( [#text] => SVS0108 ) [price] => Array ( [#text] => 450000 ) [currency] => Array ( [#text] => EUR ) [price_freq] => Array ( [#text] => sale ) [part_ownership] => Array ( [#text] => 0 ) Can somebody help with actually getting this into some format that will enable me to insert this into my database please GT how i can make a insert using this fuctions I m learning php, as using this functions (mysqli abstract) but after update wont work any more.
/** insert data array */ public function insert(array $arr) { if ($arr) { $q = $this->make_insert_query($arr); $return = $this->modifying_query($q); $this->autoreset(); return $return; } else { $this->autoreset(); return false; } }complement /** insert query constructor */ protected function make_insert_query($data) { $this->get_table_info(); $this->set_field_types(); if (!is_array(reset($data))) { $data = array($data); } $keys = array(); $values = array(); $keys_set = false; foreach ($data as $data_key => $data_item) { $values[$data_key] = array(); $fdata = $this->parse_field_names($data); foreach ($fdata as $key => $val) { if (!$keys_set) { if (isset($this->field_type[$key])) { $keys[] = '`' . $val['table'] . '`.`' . $val['field'] . '`'; } else { $keys[] = '`' . $val['field'] . '`'; } } $values[$data_key][] = $this->escape($val['value'], $this->is_noquotes($key), $this->field_type($key), $this->is_null($key), $this->is_bit($key)); } $keys_set = true; $values[$data_key] = '(' . implode(',', $values[$data_key]) . ')'; } $ignore = $this->ignore ? ' IGNORE' : ''; $delayed = $this->delayed ? ' DELAYED' : ''; $query = 'INSERT' . $ignore . $delayed . ' INTO `' . $this->table . '` (' . implode(',', $keys) . ') VALUES ' . implode(',', $values); return $query; }before update this class i used to insert data like this $db = Sdba::table('users'); $data = array('name'=>'adam'); $db->insert($data);this method of insert dont works on new class. if i try like this i got empty columns and empty values. thanks for any help complete class download http://goo.gl/GK3s4E I'm Trying to INSERT Data into mysql which is generated from biomatric attendance device. what i wanted to do is to save these data into mysql database. <?php include 'db.php'; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script> <!-- <script type="text/javascript" src="load.js"></script> --> <link rel="stylesheet" href="style.css"> <title>Live Attendance</title> </head> <?php include("zklib/zklib.php"); $zk = new ZKLib("192.168.1.3", 4370); $ret = $zk->connect(); sleep(1); if ( $ret ): $zk->disableDevice(); sleep(1); ?> <body> <table border="1" cellpadding="5" cellspacing="2" style="float: left; margin-right: 10px;"> <tr> <th colspan="5">Data User</th> </tr> <tr> <th>UID</th> <th>ID</th> <th>Name</th> <th>Role</th> <th>Password</th> </tr> <?php try { //$zk->setUser(1, '1', 'Admin', '', LEVEL_ADMIN); $user = $zk->getUser(); sleep(1); while(list($uid, $userdata) = each($user)): if ($userdata[2] == LEVEL_ADMIN) $role = 'ADMIN'; elseif ($userdata[2] == LEVEL_USER) $role = 'USER'; else $role = 'Unknown'; ?> <tr> <td><?php echo $uid ?></td> <td><?php echo $userdata[0] ?></td> <td><?php echo $userdata[1] ?></td> <td><?php echo $role ?></td> <td><?php echo $userdata[3] ?> </td> </tr> <?php endwhile; } catch (Exception $e) { header("HTTP/1.0 404 Not Found"); header('HTTP', true, 500); // 500 internal server error } //$zk->clearAdmin(); if (isset($_POST['create_post'])) { $query = "INSERT INTO attendance(idx)"; $query .= "VALUES ($id)"; $submittodbquery = mysqli_query($con,$query); if (!$submittodbquery) { die("Failed up upload " . mysqli_error($con)); }else { echo "updated"; } } ?> </table> <button id="submit" type="submit" name="create_post" class="btn btn-danger">Submit New Post</button> <?php $name = $userdata[1]; $attendance = $zk->getAttendance(); sleep(1); while(list($idx, $attendancedata ) = each($attendance)): if ( $attendancedata[2] == 1 ) $status = 'Check Out'; else $status = 'Check In'; ?> <?php $idx ?> <?php $attendancedata[0] ?> <?php $attendancedata[1] ?> <?php $status ?> <?php date( "d-m-Y", strtotime( $attendancedata[3] ) ) ?> <?php date( "H:i:s", strtotime( $attendancedata[3] ) ) ?> <?php // custom code if (isset($_POST['submit'])) { $query = "INSERT INTO attendance(idx)"; $query .= "VALUES ($idx)"; $submittodbquery = mysqli_query($con,$query); if (!$submittodbquery) { die("Failed up upload " . mysqli_error($con)); }else { echo "updated"; } } ?> <?php endwhile ?> </table> <input type="submit" name="submit" value="Update Database"> <?php $zk->enableDevice(); sleep(1); $zk->disconnect(); endif ?> </body> </html> Thanks for reading my question ..
Hello guys, im using this code atm and it's working, but the new rows created are put in the end of the table. I want them to stack up from the beginning pushing older rows down. What should i do to make that work? <?php $con = mysql_connect("localhost","*****","*******"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("ananaz_se", $con); $sql="INSERT INTO stuff (adult, namn, url) VALUES ('$_POST[adult]','$_POST[namn]','$_POST[url]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 row added"; mysql_close($con) ?> I have a form on our website that a user can fill out for custom product. I want the form data to be 1) stored into a mysql database AND after storing said data, 2) email the same data to our sales department. 1) The form data DOES get stored into mysql database (except for the first two fields, for some weird reason) 2) I added a "mail" section to the php file that stores the data into the database, but it is not working correctly. I have stripped the email portion down to sending just one of the fields in the "message" to make it easier for troubleshooting I have included here, both the form section of the html file, and the formdata.php file that processes the data for your analysis. I am relatively new to php so there are going to be some issues with security, but I can work on those after I get the store & email process to work correctly. Please review my code and see if anyone can be of assistance. I looked through the forums and couldn't find another issue that was the same as mine. If I just overlooked, please tell me the thread post #. Thanks THE FORM WHICH COLLECTS THE DATA ******************************* <form method=POST action=formdata.php> <table width="640" border=0 align="center"> <tr> <td align=right><b>First Name</b></td> <td><input type=text name=FName size=25></td> <td><div align="right"><b>Telephone</b></div></td> <td><input type=text name=Tel size=25></td> </tr> <tr> <td align=right><b>Last Name</b></td> <td><input type=text name=LName size=25></td> <td><div align="right"><b>Fax</b></div></td> <td><input type=text name=Fax size=25></td> </tr> <tr> <td align=right><b>Title</b></td> <td><input type=text name=Title size=25></td> <td><div align="right"><b>Email</b></div></td> <td><input type=text name=Email size=50></td> </tr> <tr> <td align=right><b>Company</b></td> <td><input type=text name=Comp size=25></td> <td> </td> <td> </td> </tr> <tr> <td align=right><b>Address</b></td> <td><input type=text name=Addr size=25></td> <td><div align="right"><b>Estimated Annual Volume</b></div></td> <td><input type=text name=EAV size=25></td> </tr> <tr> <td align=right><b>City</b></td> <td><input type=text name=City size=25></td> <td> </td> <td> </td> </tr> <tr> <td align=right><b>State/Province</b></td> <td><input type=text name=SProv size=25></td> <td><div align="right"><b>Application</b></div></td> <td><input type=text name=Appl size=25></td> </tr> <tr> <td align=right><b>Country</b></td> <td><input type=text name=Ctry size=25></td> <td><div align="right"><b>Type of System</b></div></td> <td><input type=text name=Syst size=25></td> </tr> <tr> <td align=right><b>Zip/Postal Code</b></td> <td><input type=text name=ZPC size=25></td> <td> </td> <td> </td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right> </td> <td><div align="right"><strong><font color="#FFFF00" face="Arial, Helvetica, sans-serif">COIL DESIGN</font></strong></div></td> <td><font color="#FFFF00" face="Arial, Helvetica, sans-serif"><strong>PARAMETERS</strong></font></td> <td> </td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right><b>Primary Resistance (ohms)</b></td> <td><input type=text name=Pres size=25></td> <td><div align="right"><b>Primary Inductance (mH)</b></div></td> <td><input type=text name=Pind size=25></td> </tr> <tr> <td align=right><b>Secondary Resistance (ohms)</b></td> <td><input type=text name=Sres size=25></td> <td><div align="right"><b>Secondary Inductance (H)</b></div></td> <td><input type=text name=Sind size=25></td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right><b>Peak Operating Current (Amps)</b></td> <td><input type=text name=POC size=25></td> <td> </td> <td> </td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right><b>Output Energy (mJ)</b></td> <td><input type=text name=Egy size=25></td> <td><div align="right"><b>Output Voltage (kV)</b></div></td> <td><input type=text name=Volt size=25></td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right><b># HV Towers per Coil</b></td> <td><input type=text name=TPC size=25></td> <td><div align="right"><b># of Coils per Package</b></div></td> <td><input type=text name=CPP size=25></td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <th colspan=4><b>Please enter any additional information he </b></th> </tr> <tr> <th colspan=4><textarea name=Mess cols=50 rows=10 id="Message"></textarea></th> </tr> </table> </dl> <div align="center"> <p> <input type=hidden name=BodyTag value="<body bgcolor="#484589" text="#FFFFFF" link="#FFFF00" alink="#FFFFFF" vlink="#FF7F00">"> <input type=hidden name=FA value=SendMail> </p> <p><font color="#FFFF00" face="Arial, Helvetica, sans-serif"><strong>PLEASE MAKE SURE ALL INFORMATION<br> IS CORRECT BEFORE SUBMITTING</strong></font></p> <p> <input type=submit value="Submit Form"> </p> </div> </form> THE FILE THAT PROCESSES THE FORM DATA (formdata.php) *********************************************** <?php $con = mysql_connect("localhost","XXX","XXX"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("customform", $con); $sql="INSERT INTO formdata (Fname, Lname, Title, Comp, Addr, City, SProv, Ctry, ZPC, Tel, Fax, Email, EAV, Appl, Syst, Pres, Pind, Sres, Sind, POC, Egy, Volt, TPC, CPP, Mess) VALUES ('$_POST[Fname]','$_POST[Lname]','$_POST[Title]','$_POST[Comp]','$_POST[Addr]','$_POST[City]','$_POST[SProv]','$_POST[Ctry]','$_POST[ZPC]','$_POST[Tel]','$_POST[Fax]','$_POST[Email]','$_POST[EAV]','$_POST[Appl]','$_POST[Syst]','$_POST[Pres]','$_POST[Pind]','$_POST[Sres]','$_POST[Sind]','$_POST[POC]','$_POST[Egy]','$_POST[Volt]','$_POST[TPC]','$_POST[CPP]','$_POST[Mess]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "Your Information Was Successfully Posted"; mysql_close($con); $to = "recipient email address here"; $subject = "Custom Form"; $email = $_POST['Email'] ; $message = $_POST['Comp'] ; $headers = "From: $Email"; $sent = mail($to, $subject, $message, $headers) ; if($sent) {print "Your mail was sent successfully"; } else {print "We encountered an error sending your mail"; } ?> hi there..im new to php mysql and im having trouble inserting a string data to mysql from a php date() function. here's my code: Code: [Select] $year = date('Y'); echo $year; $insertSQL = sprintf("INSERT INTO tbl_elections (election_id=$year)"); mysql_select_db($database_organizazone_db, $organizazone_db); $Result1 = mysql_query($insertSQL, $organizazone_db) or die(mysql_error()); when i try to output the $year variable on a webpage, it returns "2012" but when i try to insert this data into my database table, it returns an error like this: check the manual that corresponds to your MySQL server version for the right syntax to use near '=2012)' is there a way to convert "2012" into a normal string data type? I am not sure if the title is correct; I tried my best.
I'm a PHP/MySQL beginner and I really need some help.
I have a small script that I am using for sending SMS. I recently added a phonebook. The problem with the phonebook right now is that it's available to all users, i.e. they can all update and delete all rows. What I would like to do is make it so that each user can update and delete only their own contacts.
I have a table call contacts. Inside that table there is first name, last name, company and phonenumber.
How can I accomplish this with PHP & MySQL?
CREATE TABLE IF NOT EXISTS `contacts` ( `contact_id` int(10) NOT NULL AUTO_INCREMENT, `firstname` varchar(255) NOT NULL, `lastname` varchar(255) NOT NULL, `company` varchar(255) NOT NULL, `cell_no` text NOT NULL, PRIMARY KEY (`contact_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ; CREATE TABLE IF NOT EXISTS `users` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `users_name` varchar(30) NOT NULL, `uname` varchar(30) NOT NULL, `u_pass` varchar(60) NOT NULL, `utype` varchar(30) NOT NULL, `timezone` varchar(30) NOT NULL, `uapi_user` varchar(30) NOT NULL, `uapi_pass` varchar(60) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=20 ; <?php if (isset($_POST['submit'])){ //form has been submitted1 $firstname = trim($_POST['firstname']); $lastname = trim($_POST['lastname']); $company = trim($_POST['company']); $cellno = trim($_POST['cell_no']); if($firstname == ''){ echo '<div class="alert alert-danger">First Name is not Valid!</div>'; exit; }elseif($lastname == ''){ echo '<div class="alert alert-danger">Last Name is not Valid!</div>'; exit; }elseif($company == ''){ echo '<div class="alert alert-danger">Company is not Valid!</div>'; exit; }elseif($cellno == ''){ echo '<div class="alert alert-danger">Cellphone Number is not Valid!</div>'; exit; }else{ $query = "Select cell_no from contacts where cell_no = '".$cellno."' "; $result = mysql_query($query); if (!mysql_num_rows($result)) { $sql = "INSERT INTO contacts(firstname, lastname, company, cell_no) values('{$firstname}','{$lastname}', '{$company}', '{$cellno}')"; $result = mysql_query($sql); confirm_query($result); //echo '<div class="alert alert-success">Successfully added.</div>'; //exit; ?> <script type="text/javascript"> window.location = "contact_list.php"; </script> <?php } else{ echo '<div class="alert alert-danger">Username. already exist!.</div>'; echo '<p><a href="new_contact.php" class="btn btn-success"> Back </a></p>'; exit; }} }else{ $firstname = ""; $lastname = ""; $company = ""; $cellno = ""; } ?> HI first timer here so please forgive me if this is in the wrong section. Anyway, here goes. I have 2 tables Table 1 Levels LevelID LevelName Table 2 Members MemberID FirstName LastName Birthdate LevelID I have a form that has the LevelID populated from table 1 with a query. When I enter all my data and hit submit the data gets written to the members table. However, the LevelID is written as 0 for each and everyone record that I have entered. So the question is what am I missing? As mentioned I am very new at this so any help would be greatly appreciated. Please see below for my code. Thanks in advance <?php require_once 'dblogin1.php'; $db_server = mysql_connect($db_hostname, $db_username, $db_password); if (!$db_server) die("Unable to connect to MySQL: " . mysql_error()); mysql_select_db($db_database) or die("Unable to select database: " . mysql_error()); $sql = "SELECT\n" . "levels.LevelID,\n" . "levels.LevelName\n" . "FROM\n" . "levels\n"; $result = mysql_query($sql) or die(mysql_error()); $options=""; while($row = mysql_fetch_array($result)){ $LevelId=$row["LevelID"]; $LevelName=$row["LevelName"]; $options.="<OPTION VALUE=\"$LevelID\">".$LevelName.'</option>'; } ?> <style type="text/css"> <!-- body p { color: #F00; } --> </style> <table width="500" border="1" align="center" cellpadding="0" cellspacing="1" > <tr> <td> <form name="form1" method="post" action="insert_ac.php"> <table width="100%" border="1" cellspacing="1" cellpadding="3"> <tr> <td colspan="3"><div align="center"> <p><strong>Myers Player Registration Form</strong></p> </div></td> </tr> <tr> <td>First Name</td> <td><div align="center">:</div></td> <td><input name="firstname" type="text" id="firstname"></td> </tr> <tr> <td>Last Name</td> <td><div align="center">:</div></td> <td><input name="lastname" type="text" id="lastname"></td> </tr> <tr> <td>Birthdate (yyyy-mm-dd)</td> <td><div align="center">:</div></td> <td><input name="birthdate" type="text" id="birthdate"> </td> </tr> <tr> <td>Level</td> <td><div align="center">:</div></td> <td><select name="LevelID"> <OPTION VALUE="0">Choose <?php echo $options?> </select></td> </tr> </form> </td> </tr> </table> I almost have it but I am missing something. The form is being sent and the row is being created but there is not data. It is blank. I know it is something simple I am missing but I cannot figure it out
If anyone can look at my code below and tell me what I am missing to make the inputed info be seen, I would sure appreciate it.
<?php include_once('class/class_email.php'); // contact to database $connect = mysql_connect("localhost", "admin", "password") or die ("Error , check your server connection."); mysql_select_db("database"); $fname = $_POST['fname']; $lname = $_POST['lname']; $email = $_POST['email']; $company = $_POST['company']; $telephone = $_POST['telephone']; $comments = $_POST['comments']; $EID = $_POST['eid']; extract ($_POST); // Pick up the form data and assign it to variables // $id = intval($id); $fname = strip_tags($fname); $lname = strip_tags($lname); $email = strip_tags($email); $company = strip_tags($company); $telephone = intval($telephone); $query="INSERT INTO users(`id`, `fname`, `lname`, `email`,`company`,`telephone`) VALUES('$id','$fname','$lname','$email','$company','$telephone')"; echo $query; mysql_query($query) or die(mysql_error()); echo mysql_error(); $SQL_GetEquipment = "SELECT * FROM `new_equip` WHERE `id`='$EID' LIMIT 1;"; $result = mysqli_query($connect,$SQL_GetEquipment); $row = mysqli_fetch_assoc($result); $EmailBody = "$fname $lname has requested a quote from NAPE on Item $EID\n Information on quote request: \n Name: $fname $lname \n Email: $email \n Company: $company \n Number: $telephone \n Comments: $comments \n \n Information Requested for: {$row['itemname']}\n The URL to {$row['itemname']} is: http://www.mydomain.com.com/new-product.php?Item=$EID \n Click to send a quote now:\n http://www.mydomain.com.com/Admin/send-quote.php?id=$EID "; $e = new email(); //First value is the URL of your server, the second the port number $e->set_server( 'mail.mydomain.com.com', 26); //First value is your username, then your password $e->set_auth('noreply@mydomain.com', '112233'); //Set the "From" setting for your e-mail. The Name will be base64 encoded $e->set_sender( 'Quote Requested', 'noreply@mydomain.com' ); //for one recipient //$send_to = array('myemail@mydomain.com','myemail2@mydomain.com'); $send_to = ('myemail@gmail.com'); //you may also specify multiple recipients by creating an array like this: //$send_to = array('foo1@localhost.local', 'foo2@localhost.local', 'foo3@localhost.local'); $subject = 'Quote Request from NAPE'; $body = "$EmailBody"; if( $e->mail($send_to, $subject, $body, $headers) == true ) { //message was received by the smtp server //['last'] tends to contain the queue id so I like to save that string in the database echo 'last: '.htmlspecialchars($e->srv_ret['last']).''; }else{ //something went wrong echo 'all: '.nl2br(htmlspecialchars($e->srv_ret['all'])).''; echo 'full:'.nl2br(htmlspecialchars($e->srv_ret['full'])).''; } ?> Hi,
I created a form that inserts first - last name, address, and email address into a mysql databse table.
The record inserts correctly - No problems here.
The problem is I only want to insert the data if the email and address doesn't exist.
I set it up for just the email right now to try to get this to work but have failed.
When the form is submitted and the record exists it inserts the record anyway and sends the email which it's not suppose to do.
The form is suppose to after submitting -
1. validate
2. insert only if the record doesn't exist
3. send the email.
Here's the code
<?php $to = "email@email.com"; if(isset($_POST['submit'])) { // VALIDATION if(empty($_POST['firstName'])) { $errorfirstName .= "First Name Required"; } if(empty($_POST['lastName'])) { $errorfirstName .= "Last Name Required"; } if(empty($error)) # No error go ahead and email it. { $to = "$to"; $subject = 'the form'; $msg .="<html><head> <meta http-equiv='Content-Type' content='text/html; charset=utf-8' /> <title>The Form</title> </head> <body> <table> <tr> <td>Email sent for confirmation</td> </tr> </table> </body> </html>"; $mail($to, $subject, $headers, $msg); if(!$result) { $error = "<div id='errors'>There was an unknown error </div>"; } else { include('connection.php'); $firstName = mysqli_real_escape_string($con, $_POST['firstName']); $lastName = mysqli_real_escape_string($con, $_POST['lastName']); $address = mysqli_real_escape_string($con, $_POST['address']); $email = mysqli_real_escape_string($con, $_POST['email']); $email = $_POST['email']; $sql = "SELECT * FROM table WHERE `email` = '{$email}'"; $result = mysql_query($sql); if ( mysql_num_rows ( $result ) > 0 ) { $error = "Email Exists."; } else { $error = "Email does not exist. Insert it!!!"; $sql="INSERT INTO table (firstName, lastName, address, email) VALUES ('$_POST[firstName]','$_POST[lastName]','$_POST[address]', '$_POST[email]')"; } if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); } mysqli_close($con) { } } } } ?> <!-- Form --> <html> <head></head> <body> <section> <form method="POST" action="theform" name="for" onsubmit="return validateForm(this)"> <?php if(!empty($error)) { echo "$error"; } ?> This where the inputs would go not going to include them because not having an issue with the form </form> </section> </body> </html> Edited by barkly, 26 October 2014 - 06:54 PM. I'm creating a report page and can't figure out how to retrieve multiple rows from a table and display them in html. There are 5 data elements in each row and I'm thinking that using a form in the html might be the best way as I'm totally ignorant about tables in html. I'm a newbie to php and can't figure out how to accomplish this. Here's the code that I have so far: <?php $filename = NULL; session_start(); // start of script every time. // setup a path for all of your canned php scripts $php_scripts = '../php/'; // a folder above the web accessible tree // load the pdo connection module require $php_scripts . 'PDO_Connection_Select.php'; //******************************* // Begin the script here // Connect to the database if (!$con = PDOConnect("foxclone")): { echo "Failed to connect to database" ; exit; } else: { $sql = 'SELECT COUNT(IP_ADDRESS) FROM download WHERE FILENAME IS NOT NULL'; $sql1 = 'Update download t2, ip_lookup t1 set t2.country = t1.country, t2.area = t1.area, t2.city = t1.city where ((t2.IP_ADDRESS) = (t1.start_ip) OR (t2.IP_ADDRESS) > (t1.start_ip)) AND ((t2.IP_ADDRESS) = (t1.end_ip) OR (t2.IP_ADDRESS) < (t1.end_ip)) AND (t2.FILENAME is not null and t2.country is null)'; $sql2 = 'SELECT (IP_ADDRESS, FILENAME, country, area, city) from download where FILENAME is not null'; // Update the table $stmt = $con->prepare($sql1); $stmt->execute(); // Get count of rows to be displayed in table $stmt = $con->prepare($sql); $stmt->execute() ; $cnt = $stmt->fetch(PDO::FETCH_NUM); // retrieve one row at a time $i = 1; while($i <= $cnt){ $stmt = $con->prepare($sql2); $row->execute(array('')); // Do I need an array here? // from here on, I'm lost $i++; I'd appreciate any guidance you can provide or understandable tutorials you can point me to. Larry |