PHP - Pdo/mysqli - Escape Characters From Object
Hello
I am still fairly new to the PDO / mysqli thing and I would really appreciate some help with escaping special characters from the below code.
$sth = ("SELECT * from table WHERE field1 = '$bob' and field2 != ''"); foreach ($dbh->query($sth) as $row) { $who = $row['field2']; $why = $row['field1']; $dbh1->query("UPDATE table SET who = '$who', date = '$row[DATE]', time = '$row[TIME]' WHERE field1 = '$why'")or die(mysqli_error($db)); }I have tried using the prepared statement as well as the mysqli_real_escape_string but sees the code results as an object. Any help or comments would be greatly appreciated. Similar TutorialsI am having problems understanding how to sanitize my form data so it is safe to INSERT. If I use this code... Quote $trimmed = array_map('trim', $_POST); $body = mysqli_real_escape_string($dbc, $trimmed['body']); And I enter into my form... Quote O'Reilly's book Then I see this in phpMyAdmin... Quote O\'Reilly\'s book --------- If I use this code... Quote $trimmed = array_map('trim', $_POST); $body = $trimmed['body']; And I enter into my form... Quote O'Reilly's book Then I see this in phpMyAdmin... Quote O'Reilly's book Why the strange behavior?? Debbie I've got a basic text input area within a form for users to add a brief bio about themselves. I made sure to use mysql_real_escape_string to avoid problems with special characters. However, when I want to display the content within the text area when a user chooses to update or change their bio, the text displays the escape characters. How do I display data from my db without the user having to deal with the escape characters? Hello. My client and I are trying to figure out a strange issue with exporting blobs. We are trying to sync a WAMP based databse and local MySQL database. The problem is with blob columns.
The issue: When exporting a blob, the local MySQL dump command inserts an escape character "\" before characters such as NUL, TAB and LF, and I am assuming a lot more. My PHP export function (opens a file, SELECT * FROM tbl, writes to the file) does not do this. The main issue is that my client cannot import my PHP dump files when there are blobs, which I suppose is because they are missing these escape characters. He can however re-import his own MySQL dumps. I know I could remedy by using PHP string replace functions to find each character and insert a '\' before it, but I don't know which characters will need to be escaped. I also feel like there is a more simple solution. For example this is what I have and it worked for a tiny 1 pixel image, but not for something complex: $val = str_replace(chr('NUL'), '\0', $val); $val = str_replace(chr(0x9), chr(0x5c).chr(0x9), $val); $val = str_replace(chr(0xa), chr(0x5c).chr(0xa), $val);Thanks Ever since I started using OOP this past week, I have not been able to go back to the old "procedural" methods. HOwever, I seem to be stuck on creating a mysql connection that I can reuse in all of my classes. After I set up a connection to mysql using the mysqli object, I am unable to use the mysqli in other objects. Code: [Select] $mysqli = new mysqli(.....); class new_class { function quickQuery () { $mysqli->query('some query') } } Obviously, this doesn't work, because $mysqli is not defined within that functions scope. One way, is to use global keyword. Code: [Select] global $mysqli However, globals "are the root of all evil" and simply go against the idea of encapsulation in OOP. What's a way around this? HOWEVER: 1) I still want to use the mysqli object 2) I don't want to reference the $link of the db each time I instantiate a new class .... Maybe I'm asking too much? And I've google for the past hour or so. Singleton seems interesting but it requires the creation of a new db connection class. I want to use the mysqli object. I've been starting to play around the mysqli class and I've been having trouble using it due to various error it gives me from simple queries like this one. I'm not sure what the error is really, I've been following the php manual. Any help would be greatly appreciated. Code: [Select] <?php $mysqli = new MySQLi('localhost', 'root', 'root', 'jaipai'); if ($mysqli->connect_errno) { echo "There was a connection error: ". $mysqli->connecterrno; } class testClass { private $db; function __construct($mysqli) { $this->db = $mysqli; } public function pageInfo() { $query = "SELECT * FROM users WHERE username = jaipai"; $results = $this->db->query($query); $result = $this->db->fetch_assoc($results); return $result['username']; } } $testClass = new testClass($mysqli); echo $testClass->pageInfo(); ?> This gives me this error: Code: [Select] Fatal error: Call to undefined method mysqli::fetch_assoc() in /Users/JPFoster/Sites/Research & Development/Programs/Object Sandbox/DatabaseConnection.php on line 30 Just to be a little more informative I've also tried this method Code: [Select] $results = $this->db->query($query); $result = $results->fetch_assoc(); return $result['username']; This gives me an error: Code: [Select] Fatal error: Call to a member function fetch_assoc() on a non-object in Sites/Research & Development/Programs/Object Sandbox/DatabaseConnection.php on line 30 I'm not sure which is on the best path to go. Any help would be greatly appreciated. I am trying to build an object-oriented interface for a website. My classes include a "Database" class with a constructor method that connects to a database and a destructor method that disconnects from the database, a child class called "Content" that will display content stored in the database, another child class called "User" that handles registration, updating user info, logging in, and logging out, etc., and a "Validator" class that will validate all forms. So far I have the database class, the content class, and the index.php page started. My problem is that I cannot get the data returned from the function (using mysqli prepared statements) to display on the main page. I have read tutorials using MySQL, but I am using MySQLi with prepared statements. Any help is appreciated. Code: [Select] Database.php /* The Database class handles connecting to and disconnecting from the database. All interaction with the database is then extended from this class. The constructor will be run automatically each time a new instance of the Database class (or one of its child classes) is made. */ abstract class Database { // assign variables to use in the constructor private $host = 'localhost'; private $user = ''; private $password = ''; private $database = ''; // define constructor method to connect to database public function __construct() { $this->connect = new mysqli($this->host, $this->user, $this->password, $this->database); // if the connection failed kill the script and display an error if($this->connect->connect_errno) { die('Critical database error: ' . $this->database->error . '. Please contact a site administrator.'); } } // define destructor method to disconnect from the database public function __destruct() { $this->connect->close(); } } Content.php require_once('Database.php'); /* This class will display all website content that is held in the database. Anything that is stored in the database that needs to be shown on the front end of the website will go through this class. */ class Content extends Database { public function pageInfo($page) { $query = $this->connect->prepare('SELECT pageTitle, pageHeading, pageContent FROM pageInfo WHERE pageName = ?'); $query->bind_param('s', $page); $query->execute(); $query->bind_result($title, $heading, $content); return $query->fetch(); // procedurally this returns the values of the bound variables which then I can use just by typing echo $variableName // if i echo the variables out inside this method, they display at the top of index.php // how do i call them into my variables to display where i want // return $query->fetch(); should return that object to main script but then how do i call those values } public function displayUsers() { } public function searchUsers() { } } index.php <?php $page = 'index.php'; require_once('modules/Content.php'); $page = new Content(); list($title, $heading, $content) = $page->pageInfo('index.php'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title><?php echo $title; ?></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link href="includes/style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="scripts/cufon-yui.js"></script> <script type="text/javascript" src="scripts/arial.js"></script> <script type="text/javascript" src="scripts/cuf_run.js"></script> </head> <body> <!--begin main--> <div class="main"> <?php include('header.php'); ?> <?php include('menu.php'); ?> <!--begin content--> <div class="content"> <!--begin content_resize--> <div class="content_resize"> <!--begin mainbar--> <div class="mainbar"> <!--begin article--> <div class="article"> <h2><span><?php echo $heading; ?></span></h2> <div class="clr"></div> <p><?php echo $content; ?></p> </div> <!--end article--> </div> <!--end mainbar--> <?php include('sidebar.php'); ?> <div class="clr"></div> </div> <!--end content_resize--> </div> <!--end content--> <?php include('footer.php'); ?> </div> <!--end main--> </body> </html> I am getting an error when the clear banned ip over 15mins script runs if there is a row to remove from the database, what am I doing wrong here and the error is Quote PHP Fatal error: Call to a member function fetch_object() on a non-object in /path/to/file/index.php on line 14 Code: [Select] <?php // clear banned ip over 15mins $timeBAN = time(); $sql = $link->query("SELECT unban, id FROM attempts WHERE unban <= '$timeBAN'"); if ($sql->num_rows > 0) { while ($result = $sql->fetch_object()) { //<----THIS IS LINE 14 CAUSING ERROR if there is data $remove=$result->id; $sql = $link->query("DELETE FROM attempts WHERE id='$remove'"); } $sql->close(); } // check if user banned $sql = $link->query("SELECT ip, unban FROM attempts WHERE ip='$ip'"); if ($sql->num_rows > 0) { $result = $sql->fetch_object(); $unban = $result->unban; $timeCHECK = $unban-$timeBAN; if ($timeCHECK > 0 ) { $remain = round($timeCHECK/60); } $sql->close(); } // reset the auto_increment of attempts $sql = $link->query("SELECT id FROM attempts"); if ($sql->num_rows == 0) { $sql = $link->query("ALTER TABLE attempts AUTO_INCREMENT = 1"); } ?> Hey I wasn't able to add/edit some text to the mysql database because of some character how can i bypass them should i use the mysql_real_escape_string() ? if yes how do i make it work with the code i got? thaks <?php include "../configdb.php"; $id = $_GET['id']; if(isset($_POST['submit'])) { //global variables $name = $_POST['name']; $footer = $_POST['footer']; //run the query which adds the data gathered from the form into the database $result = mysql_query("UPDATE pages SET name='$name', footer='$footer' WHERE id='$id' ",$connect); echo "<b>Your Page have been edited successfully"; // echo "<meta http-equiv=Refresh content=2;url=index.php>"; } elseif($id) { $result = mysql_query("SELECT * FROM pages WHERE id='$id' ",$connect); while($row = mysql_fetch_assoc($result)) { ?> <h3>::Edit Page</h3> <form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>?id=<?php echo $row['id']?>"> <input type="hidden" name="id" value="<?php echo $row['id']?>"> <textarea name="name"><?php echo $row['name']?></textarea> <input name="footer" size="40" maxlength="255" value="<?php echo $row['footer']?>"> <input type="submit" name="submit" value="Submit"> <?php } } ?> I don't know why it won't work.. as the topic titles says that I am trying to pass a mysqli object to a property in another class but it keeps me getting an error.
here's the code for the mysqli object that i want to pass to another class
class ConnectMe2Db { public $dbname = 'somedatabase'; public $dbuname = 'root'; public $dbpass = ''; public $dbhost = 'localhost'; function __construct() { $mysqli = new mysqli($this->dbhost,$this->dbuname,$this->dbpass,$this->dbname) or die ('ERROR: '.$mysqli->connect_errno); return $mysqli; } # OTHER CODES... }and here is the class that i want the Mysqli object to pass to: class DatabaseUsers { private $dbconnection; function __construct() { $this->dbconnection = new ConnectMe2Db();#mysqli object will be passed to this attribute '$dbconnection' } public function session($username, $password) { $UserName = mysqli_real_escape_string($this->dbconnection,$username); $Password = mysqli_real_escape_string($this->dbconnection,md5($password)); $querry = "SELECT * FROM trakingsystem.login WHERE username='$username' and password='$password'"; $result = mysqli_query($this->dbconnection,$querry) or die (mysqli_error($this->dbconnection)); $count = mysqli_num_rows($result); $row = mysqli_fetch_array($result); if ($count > 0) { #some code here } } #some other code here }and this outputs 4 errors: #outputs 2 of these: Warning: mysqli_real_escape_string() expects parameter 1 to be mysqliand some mysqli_query() expects parameter 1 to be mysqli mysqli_error() expects parameter 1 to be mysqliis there something wrong with the logic that I've made? please help thanks Hi guys, I think escaping is the correct term, apologies if its not. Could anyone show me how I can escape this so it works? Thanks Code: [Select] echo "[ - <a href="/$dir/game_play.php">Play</a> - ]"; Hey! Code: [Select] echo "<ol type=\"a"\>";This gives an error, how am I supposed to escape the " " correctly? I haven't coded HTML or PHP in several years and am trying to get back into it. Seems to me that there were some nifty tricks so that when you were conctenating HTML and PHP you didn't get a birds nest. Maybe it was using something like { } but I don;t recall. I also seem to recall that wisely choosing where to use single (') and double (") quote was key! For example, how could this code be cleaner?
echo '<table id="membershipPlans"> <!-- Column Groups --> <colgroup> <col id="feature">'."\r"; foreach ($plan_names as $p_id => $p_name): echo '<col id="option0'.$p_id.'">'."\r"; endforeach; echo '</colgroup>";
Hello, I was wondering if I need to escape all get values. I often use a $_GET variable as in mypage.php?id=variable to selecting records to view etc. I usually convert this to a variable to be used in a WHERE statement. Code: [Select] IF ($_GET['id']){ $id=$_GET['id']; } But what if someone tried to view all records Quote http://www.mypage.com/page.php?id=0';SELECT%20*%20FROM%20CONTENT;'SELECT%20*%20FROM%20CONTENT%20WHERE%20ID='0 resulted in all content page data being displayed somehow. Or better yet, if visiting Quote http://www.mypage.com/page.php?id=0';DELETE%20*%20FROM%20CONTENT;'SELECT%20*%20FROM%20CONTENT%20WHERE%20ID='0 resulted in all content being deleted. Is that even possible in the in the context of a MySQL WHERE statement? Seems like the MySQL statement wouldn't be structured correctly and wouldn't work. I use mysqli_real_escape_string" on posted content but should I also escape all GET input? Hi Chaps, this is really getting my back up as its never happened before...im doing a site on a server im not familiar with and its causing me problems Code: [Select] <? if(isset($_POST['upload'])) { include 'dbconnection.php'; $ttitle = mysql_real_escape_string($_POST['ttitle']); $ttitle2 = mysql_real_escape_string($_POST['ttitle2']); $query = "INSERT INTO test ( ttitle, ttitle2) ". "VALUES ('$ttitle', '$ttitle2' )"; mysql_query($query) or die('Error, query failed : ' . mysql_error()); echo "<br>File uploaded<br>"; } ?> The database table is showing that it includes the backslash in the record, whereas i understood mysql_real_escape_string was oinly used to carry the data, and the backslash wouldn't be uncluded. From the server: PHP.ini file: (ver 5.2.17) magic_quotes_gpc Off Off magic_quotes_runtime Off Off magic_quotes_sybase Off Off Is there something i can do to get this sorted, as i dont want to add stripslashes() throught the site. As with the above, i have some forms with loads of fields, so if there is someway of adding a function that would be great.... thanks in advance I have front page and page for news, and i wonna to set, on front page to show news but only 100 characters, and on news page to be all text, i done that with substr($news, 0, 100); but i have proble, when i have in $news text like this: Code: [Select] Hi everyone. <b>Bold</b>now, subsrt count <b> and </b> like characters, how can i escape that <b> </b>, <u> </u> and other? Hello I am having a problem trying to write to a database using mysql real escape so there wont be any injection attacks. I trying using myrealescape and it returns errors: Code: [Select] Notice: Use of undefined constant messageTo - assumed 'messageTo' in D:\wamp\www\Legit Gaming Upload\LGU\includes\mailCompose.php on line 17 Notice: Use of undefined constant messageSubject - assumed 'messageSubject' in D:\wamp\www\Legit Gaming Upload\LGU\includes\mailCompose.php on line 17 Notice: Use of undefined constant messageBody - assumed 'messageBody' in D:\wamp\www\Legit Gaming Upload\LGU\includes\mailCompose.php on line 17 I add in the single quotes and it doesn't write either. Dreamweaver says that either single quotes or not there is no syntax errors. What going on? I have used it like this befo ('$ID','" . mysql_real_escape_string($_POST[post_content]) . "') and no problems.. ~AJ <?php require_once('connect.php'); if(isset($_COOKIE['user'])){}else{ header( 'Location: members.php'); } if (isset($_POST['sendBtn'])){ $messageFrom = $_COOKIE['user']; $messageTo = $_POST['messageTo']; $hash = $messageTo.$messageFrom.time(); $hash = md5($hash); mysql_select_db("majik"); $sql="INSERT INTO messagesystem(ID, hash, messageTo, messageFrom, messageSubject, messageBody, messageDate, messageRead, messageDelete) VALUES ('','$hash','" . mysql_real_escape_string($_POST['messageTo']) . "','$messageFrom','" . mysql_real_escape_string($_POST['messageSubject']) . "','" . mysql_real_escape_string($_POST['messageBody']) . "','0','0')"; echo '<center>Your message was sent to: '.$messageTo.'</center>'; } ?> Hi, I have a site where users can register etc. I was wondering should I use mysql_real_escape_string() for the elements on my registration form example email, name and so on or is it no necessary? One more question could some one tell is this the proper way to use it before inserting into the database. $name=$_POST['name']; mysql_real_escape_string($name) ? My hosts version of php just seems to automatically add the backslashes. Adding the escape string just seems to add like 3 of them rather than 1 Is this command out-of-date? |