PHP - Problem With Function
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. Similar TutorialsI 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. 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? 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 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. 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 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 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! 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 Hello all I've been using implode function of php and suddenly i encounter a problem regarding it.. Code: [Select] <?php $insertValues[] = "(default,'{$y}', '{$p}', '{$o}', '{$i}', '{$u}','AMM-40','test')"; $query_status = "INSERT INTO `mobile1_mn1`.`logs_inbound` (`log_id`, `originator`, `sender`, `date`, `time`, `message`, `company_id`, `keyword`) VALUES". implode(',',$insertValues); ?> When the information on $y,$p,$o,$i and $u does not have any single 'quotations' and commas it can save my information on database but when i have a string say for example the string is "he's good" and "Im, good" having a comma and quote it can't save my information anymore... can someone tell me why i have this problem? thanks in advance 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 creating my own lottery feature for my online game, which uses in-game money. I decided to create my own function to compare the numbers of each ticket. Before I started creating the mod, I did some testing to see if my pseudocode function would work. When I go onto my test page, I get this error: Error 324 (net::ERR_EMPTY_RESPONSE): Unknown error. I've Googled it, and it says that it's a Google Chrome error and that I should restart my browser and so on, which I did. Nothing worked. I've yet to try it in another browser yet..... My code is below: <?php include_once(DIRNAME(__FILE__) ."/globals.php"); ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); function checkResult($numbers, $winNums, $key, $wins) { if($key >= 7 && $wins >= 7) { print "Break out <br />"; return $correct; break; } else { $nums = unserialize($numbers); $winning = unserialize($winNums); $p = $nums[$key]; $n = $winning[$wins]; if($n != $p && $n > $p) { print "Increment \$key <br />"; $key++; checkResult($numbers, $winNums, $key, $wins); } elseif($n != $p && $n < $p) { print "Increment \$wins <br />"; $wins++; checkResult($numbers, $winNums, $key, $wins); } elseif($n === $p) { print "Matching! <br />"; $correct++; $key++; $wins++; checkResult($numbers, $winNums, $key, $wins); } } } $yourNumbers = array(15,20,42,37,4,8); $winNumbers = array(17,28,20,4,15,39); $sortYourNumbers = sort($yourNumbers); $sortWinNumbers = sort($winNumbers); print_r($yourNumbers); print "<br />"; print_r($sortYourNumbers); print "<hr />"; print_r($winNumbers); print "<br />"; print_r($sortWinNumbers); $yrs = serialize($yourNumbers); $wns = serialize($winNumbers); $correct = 0; print "<br />"; print $yrs ."<br />"; print $wns; checkResult($yrs, $wns, 0, 0); $h->endpage(); ?> Could someone please point out to me why this is causing the unknown error? I've tried other pages on my website, they all work perfectly. Any help will be appreciated. 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 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. 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 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 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); Hey! I have a small code where I want to check if one variable matches the other when the other is sent through a function. The function, for practical reasons, is included with a separate PHP-file. And I cant seem to apply a variable to the function which processes the other variable. Its really wierd to me. Here is the code for the main PHP-file: Code: [Select] <?php include 'function.php'; $unformatted = "FORMATTING AY ..."; $formatted1 = "formattingay..."; $formatted2 = test_format($unformatted); if ($formatted1 == $formatted2) { echo "Success, formatted!"; } else { echo "Fail, unformatted."; } ?> And here is the code for "function.php": Code: [Select] <?php function test_format($var) { strtolower(str_replace(array(" "), array(""), $var)); } ?> Does anybody have a clue to why this simply wont work? Any answers and help is highly appreciated! Hi All,
I am having an issue with my image rotating PHP function code which I have attached below.
1% of the time it can rotate through 3 of the 10 pics before stopping. 99% of the time it doesn't work at all.
The issue that is popping up in the Developer console of Firefox is "[12:25:28.802] Image corrupt or truncated: http://www.mywebsite...s/79/7979_5.jpg @ http://www.mywebsite...79/7979_5.jpg".
It is not specific to Firefox.
Any assistance would be appreciated.
function script_thumb($prefix,$title){ $saved_thmb = get_post_meta( get_the_ID(),'saved_thmb',true); $subPath = tubeace_sub_dir_path(get_the_ID()); $upload_dir = wp_upload_dir(); $thumb_url = $upload_dir[baseurl]."/script-thumbs/".$subPath."/"; if($saved_thmb==1){ $thumb = $thumb_url."/".get_the_ID()."_1.jpg"; } elseif($saved_thmb>1) { $def_thmb = get_post_meta( get_the_ID(),'def_thmb',true); $thumb = $thumb_url."/".get_the_ID()."_".$def_thmb.".jpg"; $rotate_thumbs = "onmouseover=\"thumbStart('$prefix-".get_the_ID()."', $saved_thmb, '$thumb_url');\" onmouseout=\"thumbStop('$prefix-".get_the_ID()."', '$thumb_url', '$def_thmb');\""; } else { return; } $thumb = "<img class=\"img-responsive\" src=\"$thumb\" $rotate_thumbs id=\"$prefix-".get_the_ID()."\" alt=\"".esc_attr($title)."\">"; return $thumb; }Cheers, Shaun |