PHP - Error Encoding Utf From Php Code And Sql Database
Similar Tutorialsi am trying to insert data into a database with the following code <?php $first_name=$_POST['first_name']; $middle_name=$_POST['middle_name']; $last_name=$_POST['last_name']; $gender=$_POST['gender']; $file_number=$_POST['file_number']; $character=$_POST['character']; $diagnosis=$_POST['diagnosis']; $description=$_POST['description']; $day = $_POST['day']; $month = $_POST['month']; $year = $_POST['year']; $date = date("Y-m-d", mktime(0,0,0,$month, $day, $year)); $con = mysql_connect("localhost","fathersh_search","f33321rh"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("fathersh_childsearch", $con); $sql="INSERT INTO child_info (first_name,middle_name,last_name,gender,birthdate,character,diagnosis,description,file_number) VALUES ('$_POST[first_name]','$_POST[middle_name]','$_POST[last_name]','$_POST[file_number]','$_POST[gender]','$date','$_POST[character]','$_POST[diagnosis]','$_POST[description]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con) ?> the error i get is Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'character,diagnosis,description,file_number) VALUES ('James','Anthony','Peters',' at line 1 I have a field gmap the data would be a variation of this, the gmap data to place the map on the site. The rest of the string is in my code because I want to size the iframe etc. Whean I use an input form to update this field using Null data and using a simple text line like yellow, the script works, when I try and add data as below I get a 403 error, how can I resolve this? https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3573.197380400117!2d28.465316315605516!3d-26.41710627907957!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x1e94d9c942963de9%3A0xc560ec1cd5d52b74!2sArrie%20Nel%20Nigel%20Pharmacy!5e0!3m2!1sen!2sza!4v1603786030983!5m2!1sen!2sza>
Code Hi A really basic question, with regards to best practice, but I can't find an answer anywhere. Should the charset in my website be set to match the charset used by my database? E.g. Database is utf-8, so website should be set to utf-8? I submit text to my MySQL database using a form on my site. When I look at the text in my database, sometimes, there are strange characters. The strange characters are caused by quotation marks, em dashes, apostrophes and foreign letters of the alphabet. I think that this only happens when the source of the text is a Windows program. I understand that this is a character encoding issue, but I don't fully understand the subject. I've spent the last few hours researching it, but it's only confused me.
My site uses UTF-8 encoding:
<meta http-equiv="content-type" content="text/xml; charset=utf-8" />The collation of my database is utf8_general_ci. My form looks like this: <form action="" method="post"> </form>As you can see, an accept-charset="utf-8" attribute has not been specified. Questions 1) I am guessing that my problem is that the Windows characters are being misinterpreted by my UTF-8 setup. Is that correct? 2) If so, is there a way that I can safely convert the Windows characters to UTF-8 during the submission process? 3) Should I also specify an accept-charset="utf-8" attribute on the form? 4) When I paste the Windows text directly into my database without using the form, the characters save without turning into the strange characters. But they don't render properly on my site. Can't browsers identify Windows characters? Hi all, On my project some PDF documents and images are storage outside the web public folder, so I just can't reach then just with a simple link and I need to display then on a page. $fileDir = '../data/contas'; For images I use the code below (this solution I found on web): Code: [Select] $fileDir = '../data/contas/'; function data_uri($conta, $mime) { $contents = file_get_contents($conta); $base64 = base64_encode($contents); return "data:$mime;base64,$base64"; ) <img src="<?php echo data_uri($conta, 'image/png');?>" width="720"> When I see the HTML code I got <img src="data:image/png;base64,/9j/4AAQSkZJRgABA...(huge amount of string)...FXYq/wD/2Q==" width="720"> and the images are displayed correctly. The problem occurs on PDF files, I use the same function, as follow below and the PDF document is not displaying, there is no error message just a gray background where the document were to be shown. Code: [Select] <EMBED SRC='<?php echo data_uri($conta, 'application/pdf');?>#view=FitH,top&toolbar=1&navpanes=0&scrollbar=1&zoom=scale' WIDTH="720" HEIGHT="900" ALIGN="TOP"></EMBED> When I look at the HTML code it shows: <EMBED SRC='data:application/pdf;base64,JVBERi0xLjIK...(huge amount of string)...YK#view=FitH,top&toolbar=1&navpanes=0&scrollbar=1&zoom=scale' WIDTH="720" HEIGHT="900" ALIGN="TOP"></EMBED> Any ideia how can I show the PDF files? Or there is another way to access the files outside web public folder on server to display then? Thankx Danilo Jr. Advance thank you. Can you help please. The error..... Warning: mysql_fetch_assoc() expects parameter 1 to be resource, string given in C:\wamp\www\test_dabase.php on line 24 code. Code: [Select] <?php //database connection. $DB = mysql_connect("localhost","root") or die(mysql_error()); if($DB){ //database name. $DB_NAME="mysql"; //select database and name. $CON=mysql_select_db($DB_NAME,$DB)or die(mysql_error()."\nPlease change database name"); // if connection. }if($CON){ //show tables. $mysql_show="SHOW TABLES"; //select show and show. $mysql_select2="mysql_query(".$mysql_show.") or die(mysql_error())"; } //if allowed to show. if($mysql_select2){ //while it and while($data=mysql_fetch_assoc($mysql_select2)){ //show it. echo $data; } } ?> okay this sounds strange I know but but apart from html code in pure php the database values display correctly but when I combine with HTML code i get an offset error when retrieving certain values example results from database file no HTML coding: February10 2012 5pm MY EVENT NEW YORK ERROR when combined with HTML: February MYEVENT 2012 NewYork A friend of mine must of changed something on the site while I was asleep last night and now all the site says when you go to it is: Error Database query error Warning: mail() [function.mail]: SMTP server response: 530 SMTP authentication is required. in C:\xampp\htdocs\inc\utils.inc.php on line 449 I'm not exactly sure what he did since I can't contact him. Can anyone help me fix this? Hey guys, I am using this script to connect to mysql database. Here it is the code: <?php define('DB_HOST', 'localhost'); define('DB_USER', 'myusername'); define('DB_PASSWORD', 'mypassword'); define('DB_DATABASE', 'mydatabase'); session_start(); $errmsg_arr = array(); $errflag = false; $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } $login = clean($_GET['login']); $password = clean($_GET['password']); if($login == '') { $errmsg_arr[] = 'Login ID missing'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'PS ID missing'; $errflag = true; } if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); echo "ERROR"; exit(); } $qry="SELECT level FROM users WHERE login='$login' AND passwd='$password'"; if($result) { $result=mysql_query($qry); echo $result; exit(); }else { die("Query failed"); } ?> However, I have received an error which I catch from this line: echo "ERROR"; I have input the correct username, password and the name of the database. Do you have any idea why I have received an error, guess if I have missing something? Hi, I've uploaded my website to the server and I'm getting this error:- Code: [Select] Parse error: syntax error, unexpected T_VARIABLE in /home/c/h/chichesterag/public_html/Connections/gary.php on line 9 This is the first 9 lines of code:- Code: [Select] <?php session_start(); ?> <?php require_once('Connections/gary.php'); ?> <?php ini_set ("display_errors", "1"); error_reporting(E_ALL); $gary = mysql_connect("localhost", "root") or die("Error connecting to database<br /><br />".mysql_error()); mysql_select_db("people") or die("Error selecting database<br /><br />".mysql_error()); This is my connecting code:- Code: [Select] <?php # FileName="Connection_php_mysql.htm" # Type="MYSQL" # HTTP="true" $hostname_gary = "localhost"; $database_gary = "chichesterag"; $username_gary = "chichesterag"; $password_gary = "xxxxxx"; $gary = mysql_pconnect($hostname_localhost, $username_chichesterag, $password_xxxxxx) or trigger_error(mysql_error(),E_USER_ERROR); ?> The server's owner doesn't know what the problem is so I'm hoping someone here can help. Thanks, Gary well i got a few checbox (look below for code) i want to make it so that if i click the checkbox's it sends all the check box value to one column with "," in between them Code: [Select] <input type="checkbox" name="genre" value="fighting" id="genre"/>fighting <input type="checkbox" name="genre" value="school life" id="genre" />school life <input name="genre" type="checkbox" id="genre" value="king" id="genre" />king <input name="genre" type="checkbox" id="genre" value="him" />him Hello i have some problems i hope some one can help me, first i want add new field data for like (data number) but if i add $name=$_POST['NR']; and make new <td><div align="left">Your number</div></td> <td><input name="NR" type="text" size="40"></td> and $query=( "INSERT INTO user (uname, pw,email,NR,date_joined,ip,level) VALUES ('$name',password('$pw1'),'$email',NOW(),'$ip','Normal')"); i get no result to database what could be the problem (database table exsist) Code: [Select] <?php if(isset($_POST['Submit'])){ //NEED TO CHECK IF FIELDS ARE FILLED IN if( empty($_POST['name']) && (empty($_POST['email']))){ header("Location:Messages.php?msg=3"); exit(); } if( empty($_POST['pw1']) && (empty($_POST['pw2']))){ header( "Location:Messages.php?msg=4" ); exit(); } $name=$_POST['name']; $email=$_POST['email']; $pw1=$_POST['pw1']; $pw2=$_POST['pw2']; if("$pw1" !== "$pw2" ){ header( "Location:Messages.php?msg=5" ); exit(); } $ip = $_SERVER['REMOTE_ADDR']; //connect to the db server , check if uname exist include('config.php'); $query=("Select * from user where uname='$name'"); $result= mysql_query($query); $num=mysql_num_rows($result); if ($num > 0) {//Username already exist header( "Location:Messages.php?msg=6" ); exit(); }else{ //if username does not exist insert user details $query=( "INSERT INTO user (uname, pw,email,date_joined,ip,level) VALUES ('$name',password('$pw1'),'$email',NOW(),'$ip','Normal')"); if (@mysql_query ($query)) { header("location:login.php?reg=1"); exit; } } mysql_close(); } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html><!-- InstanceBegin template="/Templates/Auth.dwt.php" codeOutsideHTMLIsLocked="false" --> <head> <!-- InstanceBeginEditable name="doctitle" --> <title>Registration</title> <!-- InstanceEndEditable --> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <!-- InstanceBeginEditable name="head" --> <!-- InstanceEndEditable --> <link href="styleLog.css" rel="stylesheet" type="text/css"> </head> <body> <table width="100%" border="0" cellspacing="7" cellpadding="0"> <tr class="temptitle"> <td><!-- InstanceBeginEditable name="EditRegion4" -->New User Registration <!-- InstanceEndEditable --></td> </tr> <tr> <td><!-- InstanceBeginEditable name="EditRegion3" --> <form name="form1" action="register.php" method="post"> <table width="657" border="0"> <tr> <td width="122"><div align="left">Name</div></td> <td width="525"><input name="name" type="text" size="40"></td> </tr> <tr> <td><div align="left">Email</div></td> <td><input name="email" type="text" size="40"></td> </tr> <tr> <td><div align="left">Password</div></td> <td><input name="pw1" type="password" size="40"></td> </tr> <tr> <td ><div align="left">Confirm Password </div></td> <td><input name="pw2" type="password" size="40"></td> </tr> <tr> <td></td> <td> <input name="Submit" type="submit"></td> </tr> </table> </form> <!-- InstanceEndEditable --></td> </tr> <tr> <td><div align="center">Copyright 2005 </div></td> </tr> </table> </body> <!-- InstanceEnd --></html> I have this script that is supposed to upload a csv file to a mysql database but I am getting the following error: Successfully uploaded. sending Data...The used command is not allowed with this MySQL version ERROR, could not add the CSV data to your database. Any help would be much appreciated. Thanks! Here is the code: <?php // error_reporting(E_ALL); include_once "config.inc"; $php_self = $_SERVER['PHP_SELF']; $file_open = 0; $page = "<center> <div align='center' style='border: 1px solid #000000; background-color: #000000;padding: 5px; color: #071bfd; width: 550px; font-family: verdana, arial, sans-serif;' > <table align='center' style='border: 1px solid #eff7c2; background-color: #e2feea;padding: 10px; color: #071bfd;' cellspacing=5><tbody> <tr><td style='background-color: #000000;padding: 5px'><u><b><h3><font color='#ffffff'><center>AGTC - CSV Upload Script v1.0a ©2006</center></font></h3></u></b></td></tr> <tr><td><span style=\"font-family: arial, sans-serif;\"><i><b>Instructions on use:</b></i> <br /> Before using this script please read the <a href='README.html'>README.html</a> file to check you have installed it correctly.<br /> Please make sure you are trying to upload a TXT or CSV file only with the extension .txt or .csv at the end of the file name. <br /> Do not exceed the maximum upload size of 2mb.<br /> You can create your files using MS-Excel or similar CSV creator.<br /><br /></td></tr> <tr><td style='background-color: #000000;padding: 5px'> <form enctype='multipart/form-data' action='$php_self' method='post' onSubmit='Alert()'> <input type='hidden' name='MAX_FILE_SIZE' value='2000000' /> <input type='hidden' name='option' value='yes' /> <font color='#ffffff' size='-1'>Locate CSV File: <br /></font><input name='csvfile' type='file' size='70' /> <br /> <center><input type='submit' value='Upload CSV File' /> </td></tr></tbody></table></div></center>"; if(!isset($_POST['option'])){ echo $page; } elseif($_POST['option'] == "yes"){ $uploaddir = './uploads/'; $uploadfile = $uploaddir . $_FILES['csvfile']['name']; if (move_uploaded_file($_FILES['csvfile']['tmp_name'], $uploadfile)) { print "<font face='arial'>Successfully uploaded. "; $notice = 1; chmod($uploadfile, 0777); } else { print "<font face='arial'>ERROR: Upload Failed. "; $notice = 0; } $notice = 1; if ($notice == 1) { echo "\n sending Data..."; flush(); echo "</font>"; if (file_exists($uploadfile)) { $fp = fopen($uploadfile, 'r') or die (" Cannot open the file"); $fileopen = 1; $length = calculate_length($uploadfile); } $replace = "REPLACE"; $field_terminater = ","; $enclose_option = 1; $enclosed = '"'; $escaped = '\\\\'; $line_terminator = 1; $local_option = 1; $sql_query = 'LOAD DATA'; if ($local_option == "1") { $sql_query .= ' LOCAL'; } $sql_query .= ' INFILE \'' . $uploadfile . '\''; if (!empty($replace)) { $sql_query .= ' ' . $replace; } $sql_query .= ' INTO TABLE ' . "`csv_test`"; if (isset($field_terminater)) { $sql_query .= ' FIELDS TERMINATED BY \'' . $field_terminater . '\''; } if (isset($enclose_option) && strlen($enclose_option) > 0) { $sql_query .= ' OPTIONALLY'; } if (strlen($enclosed) > 0) { $sql_query .= ' ENCLOSED BY \'' . $enclosed . '\''; } if (strlen($escaped) > 0) { $sql_query .= ' ESCAPED BY \'' . $escaped . '\''; } if (strlen($line_terminator) > 0){ $sql_query .= ' LINES TERMINATED BY \'' . '\n' . '\''; } $result = mysql_query ($sql_query); echo mysql_error() ; if(mysql_affected_rows() > 1) { echo " <div align=left><b><font color='#071bfd' face='arial'>The CSV data has been added to your database.<br><br> <a href='javascript:history.back()'><<< Return to CSV Upload Script</a></font></div> "; } else { error_log(mysql_error()); echo " <div align=left><b><font color='#e42127' face='arial' > ERROR, could not add the CSV data to your database.</font></div>"; } if ($file_open ==1) { fclose($fp) or die("ERROR: Could not close the file"); } } } function calculate_length($fp) { $length = 1000; $array = file($fp); for($i=0;$i<count($array);$i++) { if ($length < strlen($array[$i])) { $length = strlen($array[$i]); } } unset($array); return $length; } ?> <script language="Javascript"> function Alert() { var question = alert("Confirm this is a CSV file no more than 2mb in size!"); return question; } </script> Hey guys.. I've been setting up a database for a contact page and I have everything working for it except the following error on my update contact page.. can anyone help me figure it out?? The error lines are the ones where I have my mysql_result's. Errors: No Records Found Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 3 in /home/jonnyp22/public_html/a5/update_contact.php on line 103 Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 3 in /home/jonnyp22/public_html/a5/update_contact.php on line 104 Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 3 in /home/jonnyp22/public_html/a5/update_contact.php on line 105 Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 3 in /home/jonnyp22/public_html/a5/update_contact.php on line 106 Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 3 in /home/jonnyp22/public_html/a5/update_contact.php on line 107 Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 3 in /home/jonnyp22/public_html/a5/update_contact.php on line 108 Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 3 in /home/jonnyp22/public_html/a5/update_contact.php on line 109 Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 3 in /home/jonnyp22/public_html/a5/update_contact.php on line 110 Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 3 in /home/jonnyp22/public_html/a5/update_contact.php on line 111 Code: [Select] <!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 content="text/html; charset=utf-8" http-equiv="Content-Type" /> <title>Update Contact</title> <script type="text/javascript"> function Validateform(){ var email=document.form1.email; var firstname=document.form1.firstname; var lastname=document.form1.lastname; var state=document.form1.state; var reEmail = /^(?:\w+\.?)*\w+@(?:\w+\.)*\w+$/; if ((email.value==null)||(email.value=="")){ alert("Please enter email address"); email.focus(); return false; } if (reEmail.test(email.value)==false){ alert ("Please enter valid email address"); email.focus(); return false; } if ((firstname.value=="")||(firstname.value==null)) { alert("Please enter first name"); firstname.focus(); return false; } if ((lastname.value=="")||(lastname.value==null)) { alert("Please enter last name"); lastname.focus(); return false; } if (state.selectedIndex==0) { alert("Select state"); state.focus(); return false; } return true; } </script> <style type="text/css"> .style1 { text-align: center; color: #F8B57E; font-size: x-large; } .style2 { text-align: center; } .style3 { text-align: right; color: #F8B57E; } .style4 { text-align: left; } .style6 { text-align: center; color: #F8B57E; font-size: medium; } .style7 { color: #FFFFFF; } </style> </head> <body style="color: #FFFFFF; background-color: #102541"> <div class="style2"> <p class="style1"><strong>Update Contact</strong></p> <p class="style6">* Indicates a Required Field</p> <?php include("dl.php"); // If the form has not been submitted then show it if(!$_POST['Submit']) { $email=$_GET['email']; $query="SELECT * FROM person WHERE Email = '$email'"; $result=mysql_query($query) or die('Error: ' . mysql_error()); $num=mysql_numrows($result); mysql_close(); if ($num == 0) { echo "<b><center>No Records Found</center></b>"; } $lastname=mysql_result($result,0,"Last_Name"); $email=mysql_result($result,0,"Email"); $firstname=mysql_result($result,0,"First_Name"); $address1=mysql_result($result,0,"address1"); $address2=mysql_result($result,0,"address2"); $city=mysql_result($result,0,"city"); $state=mysql_result($result,0,"state"); $zip=mysql_result($result,0,"zip"); $phone=mysql_result($result,0,"phone"); ?> <form action="<?=$_SERVER['PHP_SELF']?>" method="post"> <table style="width: 100%"> <tr> <td style="width: 219px; height: 26px" valign="top" class="style3">E-mail Address:</td> <td style="height: 26px" class="style4"> <input name="email" style="width: 363px" type="text" value="<? echo $email; ?>" readonly="readonly" /> </td> </tr> <tr><td class="style3">First Name:</td><td class="style4"><input type="text" name="firstname" id="firstname" size="30" width="250px" value="<? echo $firstname; ?>"/></td></tr> <tr> <td class="style3" >Last Name:</td><td class="style4" ><input name="lastname" id="lastname" type="text" size="30" width="250px" value="<? echo $lastname; ?>"/></td> </tr> <tr><td class="style3">Phone:</td><td class="style4"><input type="text" name="phone" id="phone" size="15" width="250px" value="<? echo $phone; ?>"/></td></tr> <tr> <td class="style3">Address Line 1:</td><td class="style4"><input type="text" name="address1" id="address1" size="50" width="250px" value="<? echo $address1; ?>" /></td></tr> <tr> <td class="style3">Address Line 2:</td><td class="style4"><input type="text" name="address2" id="address2" size="50" width="250px" value="<? echo $address2; ?>"/></td></tr> <tr><td class="style3">City:</td><td class="style4"><input type="text" name="city" id="city" size="50" width="250px" value="<? echo $city; ?>"/></td></tr> <tr><td class="style3">State:</td><td class="style4"><select name="state" id="state"> <option <? if ($state=="NJ") echo selected ;?> >NJ</option> <option <? if ($state=="NY") echo selected ;?> >NY</option> </select></td></tr> <tr><td class="style3">Zip:</td><td class="style4"><input type="text" name="zip" id="zip" size="5" value="<? echo $zip; ?>"/></td></tr> </table> <p class="style2"><input name="Submit" type="submit" value="Update" /> <a href="show_contacts.php"><span class="style7">Show Contacts</span></a> <br /> </p> </form> <?php } else { // The form has been submitted so process it $email=$_POST['email']; $lastname=$_POST['lastname']; $firstname=$_POST['firstname']; $phone=$_POST['phone']; $address1=$_POST['address1']; $address2=$_POST['address2']; $city=$_POST['city']; $state=$_POST['state']; $zip=$_POST['zip']; $query="UPDATE person SET Last_Name='$lastname',FIRST_Name='$firstname',Phone='$phone', Address1='$address1', Address2='$address2', city='$city', state='$state',zip='$zip' WHERE Email='$email'"; if (!mysql_query($query,$con)) { die('Error: ' . mysql_error()); } else { echo "<center><b> Contact info $lastname updated successfully </b><a href='show_contacts.php'>show contacts</a></center>"; } mysql_close(); } ?> </div> </body> </html> here's the class im using Code: [Select] <?php # Name: Database.singleton.php # File Description: MySQL Singleton Class to allow easy and clean access to common mysql commands # Author: ricocheting # Web: http://www.ricocheting.com/ # Update: 2010-07-19 # Version: 3.1.4 # Copyright 2003 ricocheting.com /* This program is free softwa you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ //require("config.inc.php"); //$db = Database::obtain(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); //$db = Database::obtain(); ################################################################################################### ################################################################################################### ################################################################################################### class Database{ // debug flag for showing error messages public $debug = true; // Store the single instance of Database private static $instance; private $server = ""; //database server private $user = ""; //database login name private $pass = ""; //database login password private $database = ""; //database name private $error = ""; ####################### //number of rows affected by SQL query public $affected_rows = 0; private $link_id = 0; private $query_id = 0; #-############################################# # desc: constructor private function __construct($server=null, $user=null, $pass=null, $database=null){ // error catching if not passed in if($server==null || $user==null || $database==null){ $this->oops("Database information must be passed in when the object is first created."); } $this->server=$server; $this->user=$user; $this->pass=$pass; $this->database=$database; }#-#constructor() #-############################################# # desc: singleton declaration public static function obtain($server=null, $user=null, $pass=null, $database=null){ if (!self::$instance){ self::$instance = new Database($server, $user, $pass, $database); } return self::$instance; }#-#obtain() #-############################################# # desc: connect and select database using vars above # Param: $new_link can force connect() to open a new link, even if mysql_connect() was called before with the same parameters public function connect($new_link=false){ $this->link_id=@mysql_connect($this->server,$this->user,$this->pass,$new_link); if (!$this->link_id){//open failed $this->oops("Could not connect to server: <b>$this->server</b>."); } if(!@mysql_select_db($this->database, $this->link_id)){//no database $this->oops("Could not open database: <b>$this->database</b>."); } // unset the data so it can't be dumped $this->server=''; $this->user=''; $this->pass=''; $this->database=''; }#-#connect() #-############################################# # desc: close the connection public function close(){ if(!@mysql_close($this->link_id)){ $this->oops("Connection close failed."); } }#-#close() #-############################################# # Desc: escapes characters to be mysql ready # Param: string # returns: string public function escape($string){ if(get_magic_quotes_runtime()) $string = stripslashes($string); return @mysql_real_escape_string($string,$this->link_id); }#-#escape() #-############################################# # Desc: executes SQL query to an open connection # Param: (MySQL query) to execute # returns: (query_id) for fetching results etc public function query($sql){ // do query $this->query_id = @mysql_query($sql, $this->link_id); if (!$this->query_id){ $this->oops("<b>MySQL Query fail:</b> $sql"); return 0; } $this->affected_rows = @mysql_affected_rows($this->link_id); return $this->query_id; }#-#query() #-############################################# # desc: does a query, fetches the first row only, frees resultset # param: (MySQL query) the query to run on server # returns: array of fetched results public function query_first($query_string){ $query_id = $this->query($query_string); $out = $this->fetch($query_id); $this->free_result($query_id); return $out; }#-#query_first() #-############################################# # desc: fetches and returns results one line at a time # param: query_id for mysql run. if none specified, last used # return: (array) fetched record(s) public function fetch($query_id=-1){ // retrieve row if ($query_id!=-1){ $this->query_id=$query_id; } if (isset($this->query_id)){ $record = @mysql_fetch_assoc($this->query_id); }else{ $this->oops("Invalid query_id: <b>$this->query_id</b>. Records could not be fetched."); } return $record; }#-#fetch() #-############################################# # desc: returns all the results (not one row) # param: (MySQL query) the query to run on server # returns: assoc array of ALL fetched results public function fetch_array($sql){ $query_id = $this->query($sql); $out = array(); while ($row = $this->fetch($query_id)){ $out[] = $row; } $this->free_result($query_id); return $out; }#-#fetch_array() #-############################################# # desc: does an update query with an array # param: table, assoc array with data (not escaped), where condition (optional. if none given, all records updated) # returns: (query_id) for fetching results etc public function update($table, $data, $where='1'){ $q="UPDATE `$table` SET "; foreach($data as $key=>$val){ if(strtolower($val)=='null') $q.= "`$key` = NULL, "; elseif(strtolower($val)=='now()') $q.= "`$key` = NOW(), "; elseif(preg_match("/^increment\((\-?\d+)\)$/i",$val,$m)) $q.= "`$key` = `$key` + $m[1], "; else $q.= "`$key`='".$this->escape($val)."', "; } $q = rtrim($q, ', ') . ' WHERE '.$where.';'; return $this->query($q); }#-#update() #-############################################# # desc: does an insert query with an array # param: table, assoc array with data (not escaped) # returns: id of inserted record, false if error public function insert($table, $data){ $q="INSERT INTO `$table` "; $v=''; $n=''; foreach($data as $key=>$val){ $n.="`$key`, "; if(strtolower($val)=='null') $v.="NULL, "; elseif(strtolower($val)=='now()') $v.="NOW(), "; else $v.= "'".$this->escape($val)."', "; } $q .= "(". rtrim($n, ', ') .") VALUES (". rtrim($v, ', ') .");"; if($this->query($q)){ return mysql_insert_id($this->link_id); } else return false; }#-#insert() #-############################################# # desc: frees the resultset # param: query_id for mysql run. if none specified, last used private function free_result($query_id=-1){ if ($query_id!=-1){ $this->query_id=$query_id; } if($this->query_id!=0 && !@mysql_free_result($this->query_id)){ $this->oops("Result ID: <b>$this->query_id</b> could not be freed."); } }#-#free_result() #-############################################# # desc: throw an error message # param: [optional] any custom error to display private function oops($msg=''){ if(!empty($this->link_id)){ $this->error = mysql_error($this->link_id); } else{ $this->error = mysql_error(); $msg="<b>WARNING:</b> No link_id found. Likely not be connected to database.<br />$msg"; } // if no debug, done here if(!$this->debug) return; ?> <table align="center" border="1" cellspacing="0" style="background:white;color:black;width:80%;"> <tr><th colspan=2>Database Error</th></tr> <tr><td align="right" valign="top">Message:</td><td><?php echo $msg; ?></td></tr> <?php if(!empty($this->error)) echo '<tr><td align="right" valign="top" nowrap>MySQL Error:</td><td>'.$this->error.'</td></tr>'; ?> <tr><td align="right">Date:</td><td><?php echo date("l, F j, Y \a\\t g:i:s A"); ?></td></tr> <?php if(!empty($_SERVER['REQUEST_URI'])) echo '<tr><td align="right">Script:</td><td><a href="'.$_SERVER['REQUEST_URI'].'">'.$_SERVER['REQUEST_URI'].'</a></td></tr>'; ?> <?php if(!empty($_SERVER['HTTP_REFERER'])) echo '<tr><td align="right">Referer:</td><td><a href="'.$_SERVER['HTTP_REFERER'].'">'.$_SERVER['HTTP_REFERER'].'</a></td></tr>'; ?> </table> <?php }#-#oops() }//CLASS Database ################################################################################################### ?> here's what im trying to do. Code: [Select] $sql="SELECT * FROM rpg_announcements ORDER BY id desc"; $result = $db->query($sql); $row = $db->fetch_array($result); echo $row[1]; here's my error: Database Error Message: MySQL Query fail: Resource id #7 Notice: Undefined offset: 1 What am i doing wrong? Hey guys I keep getting the error "Database not selected" with this script <?php session_start(); if ($_SESSION['adminlogin'] == 1){ //Run } else { header('Location: Log-In.php'); exit; } ?> <!DOCTYPE HTML> <html lang="en-GB"> <head> <meta charset="utf-8"> <!--Search Engine Meta Tags--> <meta name="author" content="Worldwide Lighthouses"> <meta name="keywords" content="Lighthouses,Lightships,Trinity House,Fog Signals,Fog Horns,Fresnel"> <meta name="description" content="Worldwide Lighthouses is the number 1 source of information, pictures and videos on the Subject of Lighthouses and Lightships"> <!--Stylesheets/Javascript--> <link rel="stylesheet" href="../../Page-Layout.css" media="screen and (min-width: 481px)"> <link rel="stylesheet" href="../../Mobile-Page-Layout.css" media="only screen and (max-width:480px)"> <!--Mobile Browser Support--> <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"> <!--IE Support--> <!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <link rel="stylesheet" href="../Page-Layout.css"><![endif]--> <meta name="application-name" content="Worldwide Lighthouses"> <meta name="msapplication-starturl" content="http://worldwidelighthouses.com/"> <meta name="msapplication-tooltip" content="Worldwide Lighthouses: Your number one source of Lighthouse Information, Videos and Pictures"> <meta name="msapplication-task" content="name=Lighthouses;action-uri=http://worldwidelighthouses.com/Lighthouses.php;icon-uri=http://worldwidelighthouses.com/IE9/Lighthouses.ico"> <meta name="msapplication-task" content="name=Lightships;action-uri=http://worldwidelighthouses.com/Lightships.php;icon-uri=http://worldwidelighthouses.com/IE9/Lightships.ico"> <meta name="msapplication-task" content="name=Fog Signals;action-uri=http://worldwidelighthouses.com/Fog-Signals.php;icon-uri=http://worldwidelighthouses.com/IE9/Fog-Signals.ico"> <meta name="msapplication-task" content="name=Glossary;action-uri=http://worldwidelighthouses.com/Glossary.php;icon-uri=http://worldwidelighthouses.com/IE9/Glossary.ico"> <title>Mailing List Administration | Worldwide Lighthouses</title> </head> <body> <header> <h1 id="WWLH">Worldwide Lighthouses</h1> <form method="get" action="http://www.worldwidelighthouses.com/Search/search.php" id="Search-Box"> <input type="search" placeholder="Search Worldwide Lighthouses" name="query" id="query" size="30" value="" autocomplete="off"> <input type="submit" value="Search"> <input type="hidden" name="search" value="1"> </form> </header> <nav> <ul id="Nav"> <li class="MenuButton" id="Index"><a href="../Index.php"><p class="Nav">Home</p></a></li> <li class="MenuButton" id="Lighthouses"><a href="../Lighthouses.php"><p class="Nav">Lighthouses</p></a></li> <li class="MenuButton" id="Lightships"><a href="../Lightships.php"><p class="Nav">Lightships</p></a></li> <li class="MenuButton" id="FogSignals"><a href="../Fog-Signals.php"><p class="Nav">Fog Signals</p></a></li> <li class="MenuButton" id="Daymarks"><a href="../Daymarks.php"><p class="Nav">Daymarks</p></a></li> <li class="MenuButton" id="Buoys"><a href="../Buoys.php"><p class="Nav">Buoys</p></a></li> <li id="MenuButtonLast"><a href="../Glossary.php"><p class="Nav">Glossary</p></a></li> </ul> </nav> <?php if ($_SESSION['adminlogin']==1) { echo '<div id="logout"> <div style="float:left; width:30%; text-align:left;!important"> <a href="Log-In-Accept-Deny.php">Back to Admin Home</a> </div> <div style="float:right; width:70%;"> <a href="Logout.php">Log Out of Admin</a> <p style="font-size:10px;">Always Sign Out when Finished!</p> </div></div>';} ?> <article> <h1 class="Title">Update Contact Record</h1> <div class="Textbox"> <? $id=$_GET['id']; $username="worldw44_php"; $password="c@rtmeldrive41"; $database="worldw44_newsemail"; mysql_connect(localhost,$username,$password); $query="SELECT * FROM contacts WHERE id='$id'"; $result=mysql_query($query) or die( 'Error: ' . mysql_error() ); $num = mysql_num_rows($result); $i=0; while ($i < $num) { $name=mysql_result($result,$i,"name"); $email=mysql_result($result,$i,"email"); ?> <form action="updated.php" method="post"> <input type="hidden" name="ud_id" value="<? echo $id; ?>"> Name: <input type="text" name="ud_first" value="<? echo $name; ?>"><br> E-mail: <input type="text" name="ud_email" value="<? echo $email; ?>"><br> <input type="Submit" value="Update"> </form> <? ++$i; } mysql_close(); ?> <?php if ($_SESSION['adminlogin'] == 1){ echo "Logged in on server side."; }?> </div> </article> <footer> <ul> <li><a href="http://www.worldwidelighthouses.com/About.php">About</a></li> <li><a href="http://www.worldwidelighthouses.com/Contact-us.php">Contact</a></li> <li><a href="http://www.worldwidelighthouses.com/Use-Our-Media.php">Use our media</a></li> <li><a href="http://www.worldwidelighthouses.com/Search/search.php">Search</a></li> <li><a href="http://www.worldwidelighthouses.com/Social-Networking.php">Social</a></li> <li><a href="#Top">Back to top</a></li> </ul> <br> <br> &#169; Worldwide Lighthouses <?php echo date("Y"); ?> </footer> </body> I have no idea why? Any help? AS far as my understanding i have selected it as "Contactinfo"? Thanks Danny Hi guys When I retrieve information from database into text field and update the fields, each time I press on update button, an space gets added before the text so in screenshots I have added you can see in image1 everything is fine but once I click on update, a space will be added before the text inside the text field. Here is my code <?php session_start(); include ("global.php"); //username session $_SESSION['username']=='$username'; $username=$_SESSION['username']; //welcome messaage echo "Welcome, " .$_SESSION['username']."!<p>"; if ($_POST['register']) { //get form data $name = addslashes(strip_tags($_POST['name'])); $telephonenumber = addslashes(strip_tags($_POST['telephonenumber'])); $buildingnumber = addslashes(strip_tags($_POST['buildingnumber'])); $streetname = addslashes(strip_tags($_POST['streetname'])); $town = addslashes(strip_tags($_POST['town'])); $county = addslashes(strip_tags($_POST['county'])); $country = addslashes(strip_tags($_POST['country'])); $postcode = addslashes(strip_tags($_POST['postcode'])); $email = addslashes(strip_tags($_POST['email'])); //update statements $query = "UPDATE userss SET name =' $name' WHERE username='$username'"; $result = mysql_query($query); $query = "UPDATE userss SET telephonenumber = ' $telephonenumber' WHERE username='$username'"; $result = mysql_query($query); $query = "UPDATE userss SET buildingnumber = ' $buildingnumber' WHERE username='$username'"; $result = mysql_query($query); $query = "UPDATE userss SET streetname = ' $streetname' WHERE username='$username'"; $result = mysql_query($query); $query = "UPDATE userss SET county = ' $county' WHERE username='$username'"; $result = mysql_query($query); $query = "UPDATE userss SET town = ' $town' WHERE username='$username'"; $result = mysql_query($query); $query = "UPDATE userss SET country = ' $country' WHERE username='$username'"; $result = mysql_query($query); $query = "UPDATE userss SET postcode = ' $postcode' WHERE username='$username'"; $result = mysql_query($query); $query = "UPDATE userss SET email = ' $email' WHERE username='$username'"; $result = mysql_query($query); } //update from database to txt field $update = "SELECT name, telephonenumber, buildingnumber, streetname, country, town, postcode, county, email FROM userss WHERE username='$username'"; $result = mysql_query($update); $row = mysql_fetch_assoc($result); ?> <form action='updateprofile.php' method='POST'> Name:<br /> <input type='text' name='name' value='<?php echo $row['name'];?>'><p /> Telephone Number:<br /> <input type='text' name='telephonenumber' value='<?php echo $row['telephonenumber'];?>'><p /> Building Number:<br /> <input type='text' name='buildingnumber' value='<?php echo $row['buildingnumber'];?>'><p /> Street Name:<br /> <input type='text' name='streetname' value='<?php echo $row['streetname'];?>'><p /> County:<br /> <input type='text' name='county' value='<?php echo $row['county'];?>'><p /> Town:<br /> <input type='text' name='town' value='<?php echo $row['town'];?>'><p /> Country:<br /> <input type='text' name='country' value='<?php echo $row['country'];?>'><p /> Postcode:<br /> <input type='text' name='postcode' value='<?php echo $row['postcode'];?>'><p /> Email:<br /> <input type='text' name='email' value='<?php echo $row['email'];?>'><p /> <input type='submit' name='register' value='Update'> </form> <iframe width="750" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.co.uk/maps?f=q&source=s_q&hl=en&geocode=&q=<?php echo "$buildingnumber,+$streetname,+$town,+ $postcode,+$county,+$country";?>&sll=&sspn=0.007597,0.025921&ie=UTF8&hq=&hnear=<?php echo "$buildingnumber,+$streetname,+$town,+ $postcode,+$county,+$country";?>&ll=&spn=0.011236,0.025921&z=14&output=embed"></iframe> could someone kindly advice me on this please? Hi guys, I need help in my code, it states 'Error querying database' when I set $result = mysql_query($query, $dbc). And strange thing happens when I switched $query and $dbc place, and I got a different error msg $result = mysql_query($dbc, $query). 'Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in D:\inetpub\vhosts\championtutor.com\httpdocs\report.php on line 31 Error querying database' Any idea what is happening? Below is my code Lastly, do you guys have any debug tool software to recommend, so that it can assist me in debugging my code. Thanks <?php $first_name = $_POST['firstname']; $last_name = $_POST['lastname']; $when_it_happened = $_POST['whenithappened']; $how_long = $_POST['howlong']; $how_many = $_POST['howmany']; $alien_description = $_POST['aliendescription']; $what_they_did = $_POST['whattheydid']; $fang_spotted = $_POST['fangspotted']; $email = $_POST['email']; $other = $_POST['other']; $dbc = mysql_connect('*******', '*******', '*******', '*******') or die('Error connecting to MySQL server.'); $query = "INSERT INTO aliens_abduction (first_name, last_name, when_it_happened, how_long, " . "how_many, alien_description, what_they_did, fang_spotted, other, email) " . "VALUES ('$first_name', '$last_name', '$when_it_happened', '$how_long', '$how_many', " . "'$alien_description', '$what_they_did', '$fang_spotted', '$other', '$email')"; $result = mysql_query($query, $dbc) or die('Error querying database.'); mysql_close($dbc); echo 'Thanks for submitting the form.<br />'; echo 'You were abducted ' . $when_it_happened; echo ' and were gone for ' . $how_long . '<br />'; echo 'Number of aliens: ' . $how_many . '<br />'; echo 'Describe them: ' . $alien_description . '<br />'; echo 'The aliens did this: ' . $what_they_did . '<br />'; echo 'Was Fang there? ' . $fang_spotted . '<br />'; echo 'Other comments: ' . $other . '<br />'; echo 'Your email address is ' . $email; ?> Hey guys, i'm trying to help my buddy out with a contact database and we ran into a problem I was hoping you guys could help me out with. Everything is working except his update contact page. The error is the following, where do you think we should start in fixing this problem?? Error: Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 3 in /home/stofikj2/public_html/hw5/updcontact.php on line 55 Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 3 in /home/stofikj2/public_html/hw5/updcontact.php on line 56 Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 3 in /home/stofikj2/public_html/hw5/updcontact.php on line 57 Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 3 in /home/stofikj2/public_html/hw5/updcontact.php on line 58 Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 3 in /home/stofikj2/public_html/hw5/updcontact.php on line 59 Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 3 in /home/stofikj2/public_html/hw5/updcontact.php on line 60 Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 3 in /home/stofikj2/public_html/hw5/updcontact.php on line 61 Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 3 in /home/stofikj2/public_html/hw5/updcontact.php on line 62 Hi I am struggling to connect to my database and was wondering if someone could please help me. I am not sure what I need to put on line 10 in this code
<?php define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASS', ''); define('DB_NAME', 'tonyruttle'); define("PERPAGE", 10); $mydb = (DB_HOST, DB_USER, DB_PASS, DB_NAME); /*********************************************** ** SEARCH FOR MATCHING PRODUCTS ************************************************/ $showResults = 0; $search = ''; if (isset($_GET['srch'])) { $search = $_GET['srch']; $showResults = 1; $srch = array_filter(array_unique(explode(' ', trim($_GET['srch'])))); array_walk($srch, function(&$v, $k) { // add the +'s to the search tags $v = '+'.$v; }); $tagparam = join(' ', $srch); // // FINDTOTAL RECORDS IN SEARCH RESULTS // $params[] = $tagparam; $res = $db->prepare("SELECT COUNT(*) as tot FROM television p WHERE MATCH(title,keywords) AGAINST(? IN BOOLEAN MODE) "); $res->execute( $params ); $total = $res->fetchColumn(); $page = $_GET['page'] ?? 1; $params[] = ($page-1)*PERPAGE; // append parameters offset $params[] = PERPAGE; // and number of records for limit clause // // GET A PAGEFUL OF RECORDS // $sql = "SELECT id , title , active FROM television p WHERE MATCH(title,keywords) AGAINST(? IN BOOLEAN MODE) ORDER BY TITLE LIMIT ?,? "; $stmt = $db->prepare($sql); $stmt->execute($params); if ($stmt->rowCount()==0) { $results = "<h3>No matching records</h3>"; } else { $results = "<tr><th>Product Id</th><th>Title</th><th>Active</th><th colspan='2'>Action</th></tr>\n"; foreach ($stmt as $rec) { $cls = $rec['active']==0 ? "class='inactive'" : ''; $results .= "<tr $cls><td>{$rec['id']}</td><td>{$rec['title']}</td><td class='ca'>{$rec['active']}</td> <td class='ca'><a href='?action=edit&id={$rec['id']}'><img src='images/edit-icon.png' alt='edit'></a></td> </tr>\n"; } } } ?> <div id='title'>Product List</div> <form id='form1' "> <fieldset> <legend>Search titles and tags</legend> <input type='text' name='srch' id='srch' size='50' value='<?=$search?>' placeholder='Search for...' > <input type="hidden" name="page" id="page" value="1"> <input type="hidden" name="action" value="search"> <input type="submit" name="btnSub" value="Search"> </fieldset> <div id='formfoot'></div> </form> <?php if ($showResults) { ?> <div class="paginate_panel"> <?=page_selector($total, $page, PERPAGE)?> </div> <table border='1'> <?=$results?> </table> <?php } ?>
|