PHP - Problem With Function Using Mysqli_real_escape_string()
Hi,
I need some insight on how to go about fixing some broken code due to host upgrading PHP from 5.3 to 5.4 - see error below:
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in...Yes, I aware, the two parameters that are required which would be as follow - with $db being the connection string: mysqli_real_escape_string($db, $value);Right now, the $db arguement is NOT in the 'mysqli_real_escape_string() function - read below to know why (that's what i need help to fix): My problem is this function - itself - is being called within a function which (with PHP 5.3 used MYSQL extensions but PHP5.4 deprecated those functions and MYSQLi requiring 2 parameters as stated.... See that entire piece of code to see the issue which involves the 'quote_smart' function which executes the mysqli_real_escape_string() function inside 'quote_smart' function: Here's the defined function, currently: function quote_smart($value){ // Stripslashes if magic quotes is on if(get_magic_quotes_gpc()) { $value = stripslashes($value); } // Quote if not a number or a numeric string if (!is_numeric($value)) { $value = mysqli_real_escape_string($value); } return $value; }and it's being called as such: ${$key} = quote_smart($value);Thus, my problem - I'm not sure how to pass the mysqli link (arguement) into the function - correctly - or if i should just make the $db var 'global' within the quote_smart function itself - now that PHP is 5.4. FYI: Yes, the objective is to rewrite all this code with PDO and prepared statements but need to get this up, quickly, with temp fix due to sudden issues due to host upgrade. Would really appreciate some guidance on this one - thx! Similar Tutorialswhich one is necessary while protecting form field Edited July 28, 2019 by mahendaI am updating all my code from mysql to mysqli. Currently using PHP 5.4 but will update to 5.5 once all this updating is done.
Anyway, I have this old function for making data safe for inserting into mysql database. I changed all instances of "mysql" to "mysqli"...
function mysqli_prep($value) { $magic_quotes_active = get_magic_quotes_gpc(); $new_enough_php = function_exists("mysqli_real_escape_string") ; //i.e. PHP >= v4.3.0 if($new_enough_php) { //PHP v4.3.0 or higher //undo any magic quote effects so mysqli_real_escape_string can do the work if($magic_quotes_active) { $value = stripslashes($value) ;} $value = mysqli_real_escape_string($connection, $value); } else { //before php v4.3.0 // if magic quotes aren;t already on then add slashes manually if(!magic_quotes_active) { $value = addslashes($value); } // if magic quotes are active, then the slashes already exist } return $value; }When I load that page that calls this function, I get... Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in (mypath)This is my $connection by the way, which works fine on other pages that need it... $connection = mysqli_connect('localhost', 'myusername', 'mypassword', 'mytable'); if (!$connection) { die("database connection failed: " . mysqli_error()); }Any ideas what I'm doing wrong? This works: $name = mysqli_real_escape_string(mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME), trim($_POST['name'])); This DOESN'T work: $name = mysqli_real_escape_string($dbc, trim($_POST['name'])); // Connect to the database $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); With the second version I get the error message "expects parameter 1 to be mysqli". But parameter 1 IS mysqli, as you can see under $dbc. So what's the deal? PDO-Prepared Statements using mysqli_real_escape_string
Is it a good Idea to use mysqli_real_escape_string for extra security In the Prepared Statements
<?php try { require_once '../includes/pdo_connect.php'; $make = mysqli_real_escape_string($_GET['make']); $sql = 'SELECT * FROM cars WHERE make LIKE :make AND yearmade >= :yearmade AND price <= :price ORDER BY price'; $stmt = $db->prepare($sql); $stmt->bindValue(':make', '%' . $make . '%'); $stmt->bindParam(':yearmade', $_GET['yearmade'], PDO::PARAM_INT); $stmt->bindParam(':price', $_GET['price'], PDO::PARAM_INT); $stmt->execute(); $errorInfo = $stmt->errorInfo(); if (isset($errorInfo[2])) { $error = $errorInfo[2]; } } catch (Exception $e) { $error = $e->getMessage(); } I am having trouble getting a function to work. The function I am having trouble with is in a database.php include file that I am using successfully already. In this particular case I have had it read a function in the same file immediately before, with no problem. Here is the code. $database->addlog($username, $processname, "Can access database", 0); $prodidisused = $database->prodisused($prodid); and the error I am getting is Fatal error: Call to undefined method MySQLDB::prodisused() in /home/paulsinc/public_html/testcrm/create_product.php on line 217 The function which is in database.php is function prodisused($prodid) { $q = "SELECT * FROM orderitems WHERE productid = '$prodid'"; $result = mysql_query($q, $this->connection); /* Error occurred, return given name by default */ if (!$result || (mysql_numrows($result) < 1)) { return false; } /* Return result array */ return true; } As you can see, the function addlog which is also in database.php is working. Thanks for all suggestions. I have a function that needs to return a value and it isn’t.I think it’s a scope issue but can’t solve it. The function is function is_connected() { $addr= 'www.google.com'; if (!$socket = @fsockopen($addr, 80, $num, $error, 5)){ $connection = 0; }else { $connection = 1; { return $connection; } is_connected() echo $connection; The function works, but I do get a warning $connection not defined and I don’t get a value. Any help appreciated. First of All hello to all I have done registration login script and when I starting to making the users profiles, I have problem in the $_GET function well this is the code <?php $getid = $_GET['id']; if (!$getid) $getid = "1"; require('scripts/connect.php'); $query = mysql_query("SELECT * FROM users WHERE id='$getid'"); mysql_real_escape_string; $numrows = mysql_num_rows($query); if ($numrows == 1){ $row = mysql_fetch_assoc($query); $id = $row['id']; $firstname = $row['first_name']; $lastname = $row['last_name']; $user = $row['username']; $avatar = $row['avatar']; $city = $row['city']; echo "<div id='profile'> <div id='leftside'> <a href='profile.php?$user'><img src='avatars/$avatar' width='100px' height='100px' border='0'</a></img><br /><a href='profile.php?$user'>$firstname $lastname <br />($user)<br /></a>$city <br /></div>"; } else echo " You have to contact administrator"; ?> When I login as user id 1 then it display all right but when I go and login as another user it display the first users piture, name, surname & city can someone tell me what the problem is ? I know is this if (!$getid) $getid = "1"; but why is this happen If someone tell me or point to the right direction I would be thank full I can not handle with this function, will allways return 0 mysql_num_rows and i`m not able to login. Code: [Select] <?php session_start(); mysql_connect("localhost", "root", ""); mysql_select_db("proiect"); include("inc/functii.php"); echo "<form method='post' name='login'> <table cellspacing='1' cellpadding='2' border='0' > <tr> <td colspan='2' align='center' height='55'> Admin Login </td> </tr> <tr> <td id='paddingbot' colspan='2'> Username </td> </tr> <tr> <td id='paddingtop' colspan='2'><input type='text' name='username' size='33'/></td> </tr> <tr> <td colspan='2'></td> </tr> <tr> <td id='paddingbot' colspan='2'> Password </td> </tr> <tr> <td id='paddingtop' colspan='2'><input type='password' name='password' size='33' /></td> </tr> <tr> <td id='rem_me'><input type='checkbox' name='remember_me' /></td> <td> Remember me </td> </tr> <tr> <td align='right' colspan='2'><input type='submit' name='login' value='Login >' /></td> </tr> <tr> <td colspan='2' align='center'>"; checkLogin(); echo "</tr> </table> </form>"; ?> Code: [Select] <?php function checkLogin () { if (isset($_POST['login'])) if (($_POST['username']) == '') { echo "Please, complete the field for username."; } elseif (($_POST['password']) == '') { echo "Please, complete the field for password."; } elseif (($_POST['username'] !== '') && ($_POST['password']) !== '') { $username = $_POST['username']; $password = md5($_POST['password']); $result = mysql_query("SELECT * FROM admin WHERE username='".$username."' AND password='".$password."'") or die ("Error:".mysql_error()); $nr = mysql_num_rows($result); if ($nr < 1) { echo $nr; } else { $_SESSION['username'] = $username; $_SESSION['password'] = $password; echo "Welcome".$username; } } } ?> Hi, I am trying to include my menu and header on my website. It seems to be picking up the pictures but not showing them. My code is: <?php include ("..\head.html"); ?> <table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr> <td valign="top" align="left" width="90"> <?php include ("..\menu.html"); ?> My file structure is like this: FILE menu.php FILE head.php FOLDER blog - FILE index.php(where the code came from) FOLDER Images The menu and head files all link to the images folder, it is showing me the name of the image but just a little red cross. I hope that explains it ok. I don't knwo if i'm just missing something simple. Can anyone help? Hey there, I guess, theres something wrong with this page, 'cause it isnt loading the page I'm trying to include, please take a look: <? require "/backend/functions.php"; $con = mysql_connect('localhost', 'mdown', 'e5r8htt9'); mysql_select_db("actual", $con); dbconn(true); ?> <html> <body BGCOLOR="#000000"> [...] </style> <div class="wrapper"> <div class="rec"> <img src=test/recs.png border=0> </div> <div class="hormenu"> <img src=test/hormenu.png border=0> </div> <div class="cpanel"> <img src=test/cpanel.png border=0> </div> <div class="menu"> <img src=test/menu.png border=0> </div> <div class="baresq"> <img src=test/baresq.png border=0> </div> <div class="table"> <? include 'home/newtable.php'; ?> </div> <div class="bardir"> <img src=http://mdown.org/tretas/teste.V4/bardir.png border=0> </div> </div> </body> </html> Now the page with this code isnt showing anything inside the TABLE div and I guess it should display the content of newtable.php. The newtable.php is working perfectly and the is just the data selected from a table. Any idea about where did I messed up? thanks when trying to decode a array of rows taken from my database I found that the json_encode function doesn't allow you to present you array as (with brackets [ ])
[{"name":"Destramic"}]but returns the array as (without brackets [ ]) {"name":"Destramic"}I looked into the documentation and it doesn't seem as if php offer such a way of having bracket which Is a bit of a problem with passing to jquery (which I've found using their autocomplete plugin) this has resulted in me having to add brackets myself $data = "[" . json_encode($rows2) . "]";does anyone know if you can encode it with the brackets or readable for jquery...thank you Hi, I am calling the sms gateway to send sms, Quote $sms_msg = "hi this is mubarak"; $url = $urlAccount_home."?username=".$userAccount."&password=".$passAccount."&number=".$O_Mobile."&sender=".$userSenderSMS."&msg=".$sms_msg; if (!($fp =fopen($url,"r"))) echo "<br><center>خطا في الاتصال </center><br>"; $result =fread($fp,10); fclose($fp); when i am sending like this am sending only the message "Hi" I am not getting the whole message... What might be the problem in sending the sms gateway.. Please help me if you guys came to know, Thanks and Regards, Mubarak OK, this is a strange one I am hoping someone can help with. I have a file with a heap of functions which work fine. This file is included in my other files, and the function to display the content is called. For example I include the master file in guestbook.php, which calls showGuestbook(). Same with contact.php, it calles showContact(); etc. The file is outside the web root of the website calling it. So I went to add another function called downloadFile(). When I try to call the function, it gives me the "call to undefined function" error. I have tried renaming it to a few diff things, same error. So I thought there could be a brace error somewehere in the file. This is the strange bit.... When I put that function at the top of the file, the page seems to fail to parse. None of the functions are available... The function so far is simply: function downloadFile() { echo "Download File"; } Can anyone shed some light on this strange behaviour, especially the errors that occur just because I move the code higher up the file. Hi, ppl, my problem is that whenever the DELETE link is clicked, a javascript confirm box pops up and it should only delete the record with the ID from the $_GET global array if the user clicks the OK button, otherwise it should just redirect to the table of entries WITHOUT DELETION, but somehow it IS DELETING even when CANCEL button of javascript confirm box clicked. Here's my code below: <html> <head><title> </title> </head> <body> <?php require "bellConnect.inc.php"; $ID=$_GET['ID']; $result=mysql_query("SELECT * FROM bellProducts WHERE ID=$ID"); $row=mysql_fetch_assoc($result); $name=$row['Name']; $manufacturer=$row['Manufacturer']; print "Value of ID is $ID"; ?> <script type='text/javascript'> var confirmDelete=confirm("Are you sure you want to delete <?php echo "$name $manufacturer"?> ?"); if(confirmDelete) { <?php $deletedResult=mysql_query("DELETE FROM bellProducts WHERE ID=$ID"); ?> alert("<?php echo "$name $manufacturer" ?> has been deleted successfully."); window.location="http://localhost/index.php"; } else if(!confirmDelete) { window.location="http://localhost/index.php"; } </script> </body> </html> **please help me someone!!! thanks I am an absolute beginner in php & am trying to validate a form using javascript. Problem is I am checking if the textbox is left empty before the user clicks on the submit button(using javascript). On the other hand i'm using isset function of php for the same submit button so that it does not run the code unless and until the button is clicked. Due to this, the default value of text box is being entered into database. How do i prevent this? Is there an alternate function to isset for such an event? Here is a sample code Code: [Select] <?php if(isset($_POST[sub])) $sql="insert into testing values('$_POST[txt1]')"; $exec = mysql_query($sql); ?> <script type="text/javascript"> function check() { var a = document.getElementById('add'); if (a.value = "") { return false; } } </script> <form action="add.php" method="post"> <input type="text" name="txt1" id="add"><br> <input type="submit" name="sub" value="Click to Add" onclick = "check();"> </form> I'm using ghost text technique on my page instead of labels so the text boxes have different values at different instances and hence I cant use !empty function either. How do i unset the submit button so that it does not run the script further? I'm not getting any errors but its also not INSERTing into the database. Without an error I can figure out whats wrong. Code: [Select] $db_server = 'localhost'; $db_user = 'user_db'; $db_pass = 'password'; $dbc = mysql_connect ($db_server, $db_user, $db_pass); if (!$dbc) { die(mysql_error()); header ('Location: /form'); exit; } if (is_array($_POST)) { foreach ($_POST as $key => $value) { $_POST[$key] = mysql_real_escape_string(stripslashes($value)); } } $xRequestType = $_POST["xRequestType"]; $xConsumerBusiness = $_POST["xConsumerBusiness"]; $xGlobalLocation = $_POST["xGlobalLocation"]; $xFirstName = strtolower(str_replace("'","''",$_POST["xFirstName"])); $xFirstName = strtoupper(substr($xFirstName,0,1)).substr($xFirstName,1); $xLastName = strtolower(str_replace("'","''",$_POST["xLastName"])); $xLastName = strtoupper(substr($xLastName,0,1)).substr($xLastName,1); $xEmail = strtolower(str_replace("'","''",$_POST["xEmail"])); $xTitle = strtolower(str_replace("'","''",$_POST["xTitle"])); function dbSet($fields, $source = array()) { $set=''; if (!source) $source = &$_POST; foreach ($fields as $field) { if (isset($source[$field])) { $set.="`$field`='".mysql_real_escape_string($source[$field])."', "; } } return substr($set, 0, -2); } // INSERT INTO DATABASE mysql_select_db("new_contact",$dbc) or die("Could not select new_contact"); $fields = explode(" ", "xRequestType xConsumerBusiness xGlobalLocation xFirstName xLastName xEmail xTitle xCompany xAddress xCity xState xZip xPhone xFax xProductDesc xComment"); $query = "INSERT INTO new_contact SET ".dbSet($fields, $_POST); mysql_query($query); I just want to compare this two functions <?php function myfunction($x) { if($_GET['x']==$x) { return "SELECTED"; } } echo "<option value='test'".myfunction('test').">TEST</option>"; ?> ======================================================= <?php function myfunction($x) { if($_GET['x']==$x) { echo "SELECTED"; } } ?> <option value="test" <?php myfunction("test");?>>TEST</option> * Assume that $_GET['x']=="test" My question: I try to use echo for the first case and option didnt SELECTED until i use return Same thing with the second one, where i have to use return instead of echo can anyone simply explain this thanks hello everyone i'm new to PHP and i need your help. I'm developing a code which implements shannon-fano encryption algorithm with php. But i have problems with my function. Basicly i try to do this: 1.Specofy a string to be coded. 2.Count the number of occurences of a character and write it in assoc array like this : "A"=>4,"B"=>2 etc. then i copy this array 3.After i have the array i sort it descending. 4.Divide the given array into two arrays where the sum of the values is almost equal.In the Copied array i set the value of the elements which fit into the fisrt divided array with 0 the rest with 1. 5.Each of the divided arrays i divide with recursion again until every symbol is into different array.and add to the value in the copied array 0 or 1; 6.I try to print the copied array. here is my function which doesnt work and gives a lot of errors function divide_array($array) { $sum=0; $mid=array_sum($array)/2; foreach($array as $k=>$v) { if($sum<$mid){ $sum=$sum+$array[$k]; $up[$k]=$array[$k]; $codeArr[$k]=0; } else { $down=array_slice($array,$k+1); $codeArr[$k]=1; } } divide_array($up); divide_array($down); echo "<pre>"; print_r($codeArr); echo "</pre>"; } i appreciate any help PS:I know this can be done easier with trees but i don't understand them. |