PHP - Mysql Database Insert Validation, And Displaying Info
Hi,
I have a website where users can log on and edit their profile pic, name, biography etc. I was wondering about the correct way to:- Add data to the database through forms (Register.php) Display the data on a page Using mysql escape sting, however, the way I am currently using will display a '\' before any ' symbol. So it's >> it\'s ... Here is a snippet of the code I am using... Code: [Select] //insert data $about1 = mysql_real_escape_string($_POST['about']); //get $query = mysql_query("SELECT * FROM `staff` WHERE username='$username'"); $row = mysql_fetch_array($query); $about = $row['about']; echo $about; Similar TutorialsHello I'm trying to set up a user area for my site where it displays the current logged in users ranking and other information in the future. <? ini_set('display_errors', 1); require_once "header.php"; $sql = "SELECT * FROM users WHERE username = ?"; if($stmt = mysqli_prepare($link, $sql)){ mysqli_stmt_bind_param($stmt, 's', $_SESSION['username']); if(mysqli_stmt_execute($stmt)){ $info = mysqli_fetch_array($stmt); echo "Current rank:" . $info['rank']; } else { echo "Can't find user"; } } mysqli_stmt_close($stmt); ?> That's the code I currently have but it gives me the error "but get an error message of mysqli_fetch_array() expects parameter 1 to be mysqli_result" How can i use single quote for values? $qry='insert into tablename values('a','b');'; Hi Im having some trouble implementing info into a database Hi there. I have this simple code which displays 5 results. How can i grab each element separately instead of displaying all the results at once. Thanks:) Code: [Select] <?php $query = mysql_query("SELECT product_name, product_price FROM products WHERE product_type = 'laptop' LIMIT 5"); $numrows = mysql_num_rows($query); if ($numrows != 0) { while ($row = mysql_fetch_assoc($query)) { $product_name = $row['product_name']; $product_price = $row['product_price']; echo $product_name . '<br />'; echo $product_price . '<br /><br />'; } } ?> well I know the standard way of retrieving mysql data was through the following codes: Code: [Select] $query = "SELECT * FROM {$tablename} WHERE columnmame = '{$var}'"; $result = mysql_query($query); $row = mysql_fetch_array($result); This will return all properties inside a table row by an associative array indexed by column names. I am, however, wondering if there is an easier way to retrieve database info from more than one table. For now, what I am doing is: Code: [Select] $result = mysql_query( "SELECT * FROM {$tablename} WHERE columnmame = '{$var}'"); $row = mysql_fetch_array($result); $result2 = mysql_query( "SELECT * FROM {$tablename2} WHERE columnmame2 = '{$var2}'"); $row2 = mysql_fetch_array($result2); which is a bit tedious and can cause problems when two or more coders work on the same project(it will be difficult to tell what is $row1, $row2 and $row3...). Is there away to write a simpler code than the one above? I mean, if it is possible to run mysql_fetch_array only once and retrieve database info from multiple tables? Hi there, I am using this code to send the users email address to the database. That works fine, but i keep getting blank info added to the database. Does anyone know how i can stop this? <?php $con = mysql_connect("*","*","*"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("ogs_mailinglist1", $con); $sql="INSERT INTO mailinglist (email) VALUES ('$_POST[rec_email]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } mysql_close($con); ?> Thanks, hi guys so i have this add contacts page and the form is divided into 3 different froms 1) primary contact 2)spouse 3)child and the child form data is inserted as array into database because in the primary contact part of the form there is a "Children ?" with yes and no radio button and if yes a drop down list is enabled where if user chooses say 2 then there would be 2 child form that appears. and since theres 2 children then in the database a new row and data will be added accordingly.
image attached to be clearer.
from2.jpg 24.15KB
0 downloads
i got it inserted into database but in the specified field it says array: |child_name|dob|house_add1|mobile|office|email| inserted: |array|array-array-array|array|array|array|array| query: "INSERT INTO child VALUES('','".$childsalutations." $childfname $childlname',' ".$cday."-".$cmonth."-$cyear ','$childline1','$childline2','$childm','$childoff','$childemail')"in a stackoverflow question(not my own question) someone says: information stating arrays need to be split, before inserting into the table. does that mean something like this?: $cday = ($_POST['cday']); $cmonth = ($_POST['cmonth']); $cyear = ($_POST['cyear']); $childsalutations = ($_POST['child-salutations']); $childfname = ($_POST['child-fname']); $childlname = ($_POST['child-lname']); $childline1 = ($_POST['child-line1']); $childemail = ($_POST['child-email']); $childm = ($_POST['child-mobile']); $childoff = ($_POST['child-office']); $info = array('c_name' => $childsalutation $childfname $childlname, 'c_dob' => $cday-$cmonth-$cyear, 'c_line1' => $childline1, 'c_mobile' => $childm, 'c_office' => $childoff, 'c_email' => $childemail)just in case u wanted to c the html child form(warning its abit long,very!): <table class="prime"> <tbody> <br> <tr><td style="font-size:20px;font-weight:bold">Child <span id="number"></span></td></tr> <tr> <td>Salutation :</td> <td><select name="child-salutations[]" id="child-salutations"> <option value="" disabled selected>Salutations</option> <option value="Datin">Datin</option> <option value="Datin Paduka">Datin Paduka</option> <option value="Dato Paduka">Dato Paduka</option> <option value="Dato'">Dato'</option> <option value="Dato' Seri">Dato' Seri</option> <option value="Datuk">Datuk</option> <option value="Datuk Seri">Datuk Seri</option> <option value="Dr.">Dr.</option> <option value="Haji">Haji</option> <option value="Hajjah">Hajjah</option> <option value="HM">HM</option> <option value="HRH">HRH</option> <option value="Miss">Miss</option> <option value="Mrs.">Mrs.</option> <option value="Mr.">Mr.</option> <option value="Pehin">Pehin</option> <option value="Professor">Professor</option> <option value="Raja">Raja</option> <option value="Tan Sri">Tan Sri</option> <option value="Tengku">Tengku</option> <option value="Tuanku">Tuanku</option> <option value="Tun">Tun</option> <option value="Tunku">Tunku</option> <option value="Ungku">Ungku</option> </select> </td> </tr> <tr><td colspan="2"><label class="label" style="color:Red">*If a person has many salutations, choose the highest form of salutation</label></td></tr> <tr><td>First Name :</td><td><input type="text" name="child-fname[]" id="child-fname" class="style" /></td> <td>Last Name :</td><td><input type="text" name="child-lname[]" id="child-lname" class="style" /></td></tr> <tr> <td>Date of Birth : </td> <td> <select name="cday[]"> <option value=""selected disabled>Day</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="cmonth[]"> <option value="" selected disabled>Month</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> Year : <input type="text" name="cyear[]" maxlength="4" size="4" class="year"> </td> </tr> <tr><td>Where do they live ?</td><td colspan="3"><input type="radio" name="living[]" id="living-me" class="living-me"/>With Me<input type="radio" name="living[]" id="living-other" class="living-other"/>With Other Parent<input type="radio" name="living[]" id="living-own" class="living-own"/>Own</td></tr> <tr><td>House Address</td></tr> <tr><td>Line 1 :</td><td><input type="text" name="child-line1[]" id="child-line1" size="20" class="style" /></td> <td>Mobile No :</td><td><input type="text" name="child-mobile[]" id="child-mobile" class="style" /></td></tr> <tr><td>Office No :</td><td><input type="text" name="child-office[]" id="child-office" class="style" /></td> <td>Email Address : </td><td><input type="email" name="child-email[]" id="email" class="style" /></td></tr> </tbody> </table> 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); } ?> 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); ?> Hello, I'm having some frustrations right now. I have built an application form where an applicant inputs their info and then uploads their resume. Even though the resume gets uploaded to a directory on the server i would also like the file name of the resume to get inserted into the mysql database so that I can easily see which resume matches which applicant...if that makes sense. At any rate I'm able to get everything else to work, the applicant's info gets inserted into the database, the resume gets uploaded to the directory, i just can't seem to get the resume file name to also insert into the database. Most of the info i have found on this subject through googleing and the like has been a little over my head and/or a little more complex than what i'm looking for. Here is an extremely simplified version of what I have right now. I have excluded the 'connect to database' code since it's working fine and really doesn't have anything to do with this issue: Code: [Select] <?php $target_path = "docs/"; $target_path = $target_path . basename( $_FILES['resume']['name']); $first_name=$_POST['first_name']; $last_name=$_POST['last_name']; $middle_init=$_POST['middle_init']; $resume=$_POST['resume']; mysql_query("INSERT INTO `intern` VALUES ('$first_name', '$last_name', '$middle_init', '$resume')") ; if (move_uploaded_file($_FILES['resume']['tmp_name'], $target_path)); ?> HTML begins after that. At any rate, any info, help, etc. you could provide would be GREATLY appreciated! Thanks! 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 Code: [Select] <?php require "db/config.php"; $fname = $_POST['fname']; $lname = $_POST['lname']; $country = $_POST['country']; $state = $_POST['state']; $city = $_POST['city']; $zcode = $_POST['zcode']; $address = $_POST['address']; $ppemail = $_POST['ppemail']; $pnumber = $_POST['pnumber']; $cemail = $_POST['cemail']; $url = $_POST['url']; $price = "$5.00"; $query = "INSERT INTO custpackage1000( id, FirstName, LastName, Country, State, City, ZipCode, Address, PayPalEmail, PhoneNumber, PrimaryEmail, WebsiteURL) VALUES ( '1', '$fname', '$lname', '$country', '$state', '$city', '$zcode', '$ppemail', '$pnumber', '$cemail', '$url')"; mysql_connect($host, $user, $pass) or die("<br /><br /><h1>Fatal error. Please contact support if this persists.</h1>"); mysql_select_db($dbname); mysql_query($query) or die ("could not open db".mysql_error()); sleep(2); ?> Why won't the code insert into my database upon submission of data? What am I doing wrong? Hi I have got results being displayed after clicking the search button in a form on my home page but it brings up all the results which is ok but how do I get onlt the results a user searches for for example a location or property type etc as its for a property website The coding is below for the results page Also sorry how do I add a background image to the php page, I tried using css but wouldn't work Code: [Select] <style type="text/css"> body {background-image:url('images/greybgone.png');} </style> <?php mysql_connect ("2up2downhomes.com.mysql", "2up2downhomes_c","mD8GsJKQ") or die (mysql_error()); mysql_select_db ("2up2downhomes_c"); echo $_POST['term']; $sql = mysql_query("select * from properties where typeProperty like '%$term%' or location like '%$term%'"); while ($row = mysql_fetch_array($sql)){ echo 'Type of Property: '.$row['typeProperty']; echo '<br/> Number of Bedrooms: '.$row['bedrooms']; echo '<br/> Number of Bathrooms: '.$row['bathrooms']; echo '<br/> Garden: '.$row['garden']; echo '<br/> Description: '.$row['description']; echo '<br/> Price: '.$row['price']; echo '<br/> Location: '.$row['location']; echo '<br/> Image: '.$row['image']; echo '<br/><br/>'; } ?> Hi, I'm a researcher (and complete coding noob), and am planning a longitudinal study that requires e-mail follow-up with subjects taking an initial survey. For purposes of ethics/anonymity due to sensitive survey data, I'd like the acquired e-mails to be saved uncoupled from the survey responses; this is simple to deal with, and I use a basic PHP e-mail form, which injects the email address in a table in MySQL in a different server than the one used for the survey. The issue is that the e-mails are saved in the MySQL database in order of injection, thus it is still theoretically possible for me to link the e-mails back to the survey responses (which have a time stamp that I cannot remove). Ideally I would like not to be able (at all) to link the e-mails to the survey responses, and one way to do that (since I don't save the e-mail injection timestamps in MySQL) might be to have the e-mails saved in MySQL in a random order. Not sure if this is possible, and not even sure if this would be via PHP or MySQL side of things. The server is on godaddy and uses Starfield interface for MySQL but I cannot find an option for random insert/saving of table items (emails). They are saved in order of injection. Any solution for this? Thanks, Hi, This has been baffling me for a couple hours now and i cant seem to figure it out. I have some code which creates an array and gets info from a mysql database and then displays in a list. This works great but after adding more and more rows to my database the list is now becoming quite large and doesnt look great on my site. Is it possible to split the list into multiple columns of about 25 and if possible once 3 or 4 columns have been created start another column underneath. To help explain i would be looking at a layout as follows: Code: [Select] line 1 line 1 line 1 line 2 line 2 line 2 ... ... ... line 25 line 25 line 25 line 1 line 1 line 1 line 2 line 2 line 2 ... ... ... line 25 line 25 line 25Im guessing there should be some sort of if statement to check how many items are being displayed and to create a new column if necessary. Is this correct? Thanks, Alex Hello everyone I need code for this question
would you help me please..?
Not really sure how to get the images I have stored in MySQL into a html form. I can call-up the text fields from the database but it cannot seem to find the index for the images. Here is my code:- <?php session_start(); mysql_connect("localhost","root","abc") or die ("Error! Cannot connect to database"); mysql_select_db("theimageworks") or die ("Cannot find database"); $query = "SELECT * FROM jobs"; $result = mysql_query($query) or die (mysql_error()); ?> <?php //display data in html table echo "<table>"; echo "<tr><td>Username</td><td align='center'>Message</td><td>Product Image</td></tr>"; while($row = mysql_fetch_array($result)) { echo "</td><td>"; echo $row['username']; echo "</td><td>"; echo $row['message']; echo "</td></tr>"; echo $row['image']; } echo "</table>"; ?> The error message I get is "Notice: Undefined index: image in....." Thanks in advance! This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=308347.0 I have a standard form that displays users current data from a mysql database once logged in(code obtained from the internet). Users can then edit their data then submit it to page called editform.php that does the update. All works well except that the page does not display the updated info. Users have to first logout and login again to see the updated info. even refreshing the page does not show the new info. Please tell me where the problem is as i am new to php.
my form page test.php
<?PHP require_once("./include/membersite_config.php"); if(!$fgmembersite->CheckLogin()) { $fgmembersite->RedirectToURL("login.php"); exit; } ?> <form action="editform.php?id_user=<?= $fgmembersite->UserId() ?>" method="POST"> <input type="hidden" name="id_user" value="<?= $fgmembersite->UserId() ?>"><br> Name:<br> <input type="text" name="name" size="40" value="<?= $fgmembersite->UserFullName() ?>"><br><br> Email:<br> <input type="text" name="email" size="40" value="<?= $fgmembersite->UserEmail() ?> "><br><br> Address:<br> <input type="text" name="address" size="40" value="<?= $fgmembersite->UserAddress() ?> "><br><br> <button>Submit</button>my editform.php <?php $con = mysqli_connect("localhost","root","user","pass"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } mysqli_query($con,"UPDATE fgusers3 SET name = '".$_POST['name']."', email= '".$_POST['email']."', address= '".$_POST['address']."' WHERE id_user='".$_POST['id_user']."'"); header("Location: test.php"); ?> This is a multiplication test for students to take and when they finish they click the score button. after they click the score button it tells them what their score is, with the opportunity to take it again. What I am trying to do is make this able to keep the recent score and just post the next score. Right now my app just gives the first score and then when I take the test again it just refreshes and gives the new score. I want it to play the new score under the old score. I can't seem to figure out how to do this. If someone could help point me in the right direction. Would appreciate the help. Here is my code for my app.... Code: [Select] <?php require_once('database.php'); define ('ROWS', 3); define ('COLS', 3); define ('MAX_NUMBER', 12); date_default_timezone_set('America/New_York'); if (isset($_POST['btn_score'])) { $result_name= $_POST['result_name']; $correct = 0; //print_r ($_POST); $time1 = $_POST['ts']; $time1_object = new DateTime($time1); $now = new DateTime(); $time_span = $now->diff($time1_object); $minutes = $time_span->format('%i'); $seconds = $time_span->format('%s'); $seconds+= $minutes * 60; echo "It took $seconds seconds to complete the test<hr />"; foreach ($_POST as $problem => $answer) { if ($problem <> "btn_score" && $problem <> "ts" && $problem <> "result_name") { //echo "$problem -- $answer <br />"; $problem = explode('_', $problem); $num1 = $problem[2]; $num2 = $problem[3]; $right = $num1 * $num2; if ($answer != $right) { echo "$num1 * $num2 = $answer , The right answer is $right<br />"; }else { $correct = $correct + 1; } } } $result_score= 0; $result_score= ($correct / 9) * 100; echo "your score is <br/>$result_score<br/>"; } $sql = "INSERT INTO results (result_name, result_score, result_date_time) VALUES ('$result_name','$result_score', NOW());"; ?> <h1>Multiplication Test</h1> <form name="lab5" method="post" action="lab5b.php"> <?php $now = new DateTime(); //echo $now->format('Y-m-d H:i:s'); echo "<input type='hidden' name='ts' value='" . $now->format('Y-m-d H:i:s') . "'>"; ?> <table border="1" cellspacing="5" cellpadding="5"> <?php $no_of_problems = 0; for ($row=0; $row<ROWS; $row++) { echo "<tr>"; for ($col=0; $col<COLS; $col++) { $num1 = mt_rand(1,MAX_NUMBER); $num2 = mt_rand(1,MAX_NUMBER); echo "<td>$num1 * $num2 </td>"; echo "<td><input type='text' size='2' name=${no_of_problems}_mult_${num1}_${num2}></td>"; $no_of_problems++; } echo "</tr>"; } $colspan = 2 * COLS; echo "<tr><td colspan=$colspan align='right'><input type='submit' value='Score' name='btn_score'></td></tr>"; ?> |