PHP - Mysql In Functions
Hi I was trying to run an mysql statement in a function and it wasn't working. I'm sure it has something to do with global variables but when I tried running the statement with the connect in the function it still did not work.
I am running MySQL server version --5.1.58-1ubuntu1 basically my code looks like this Code: [Select] <?php include(" database connect "); include(" proc "); if(!empty($_POST[''])) run_function(); ?> proc Code: [Select] funcion run_function() { mysql_query("") or die(mysql_error()); } The error prints nothing but if I take it out of the function the code works. If I require the database connect in the function, still nothing.. Do I need to pass my connect variables or something? or will this simply not work. [/code] Similar TutorialsHi, So as you might (or might not) have guessed I need to open/close new connections inside my functions. Here's my current code: Code: [Select] <?PHP /** * This function checks the ban status of the account. * @return 1 if banned */ function checkBan() { mysql_close($con); require("./includes/wow.php"); $result = mysql_query("SELECT * FROM wow_logon.accounts WHERE forum_acc= '.$user->data['user_id'].'"); $row = mysql_fetch_array($result); if($row["banned"] == "1") { return 1; $ban_reason = $row["banreason"]; } //$user->data['user_id'] mysql_close($connect); require("./includes/config.php"); } ?> When trying to use the function: checkBan(); if(checkban() == "1") { echo'function works, and returns 1. Ban reason: '.$ban_reason.' '; } This gives a pretty good idea of what I try to accomplish I hope, if not, an explanation is below. This code unfortunately returns: Code: [Select] [phpBB Debug] PHP Warning: in file /home/fusion/public_html/includes/functions_user.php on line 9: mysql_close() expects parameter 1 to be resource, null given [phpBB Debug] PHP Warning: in file /home/fusion/public_html/includes/functions_user.php on line 12: mysql_fetch_array() expects parameter 1 to be resource, boolean given [phpBB Debug] PHP Warning: in file /home/fusion/public_html/includes/functions_user.php on line 9: mysql_close() expects parameter 1 to be resource, null given [phpBB Debug] PHP Warning: in file /home/fusion/public_html/includes/functions_user.php on line 12: mysql_fetch_array() expects parameter 1 to be resource, boolean given Line 9 & 12: mysql_close($con); $row = mysql_fetch_array($result); Explanation: What I want to do is that I have a user account panel. When the user log in, I want to call a function to check if the user is banned. If the user is banned then we have returned 1, and display some banned message, followed by the ban reason. P.S. is it possible to use stored variables inside a function? When I do this, I connect to another sql server, by first closing the existing connection (if any) and open a new one to execute my statements. Then close that connection and resume the old one. Hello guys, I have purchased a new book for PHP called Professional PHP 6. But the bad news is that the whole book was written for PostgreSQL NOT for MYSQL which I'm familiar with! I have this code, I have tried to do so many things to get it working! but nothing seems to have it working! Long story short, I have failed to convert the code to work with MySQL! Here is my code, in case some one will offer a help, or a reference to go to if some similar case comes up on my way. <?php class Widget { private $id; private $name; private $description; private $hDB; private $needsUpdating = false; public function __construct($widgetID) { //The widgetID parameter is the primary key of a //record in the database containing the information //for this object //Create a connection handle and store it in a private member variable //This code assumes the DB is called "parts" $this->hDB = pg_connect('dbname=parts user=postgres'); if(! is_resource($this->hDB)) { throw new Exception("Unable to connect to the database."); } $sql = "SELECT name, description FROM widget WHERE widgetid = $widgetID"; $rs = pg_query($this->hDB, $sql); if(! is_resource($rs)) { throw new Exception("An error occurred selecting from the database."); } if(! pg_num_rows($rs)) { throw new Exception("The specified widget does not exist!"); } $data = pg_fetch_array($rs); $this->id = $widgetID; } public function getName() { return $this->name; } public function getDescription() { return $this->description; } public function setName($name) { $this->name = $name; $this->needsUpdating = true; } public function setDescription($description) { $this->description = $description; $this->needsUpdating = true; } public function __destruct() { if($this->needsUpdating) { $sql = "UPDATE widget SET "; $sql .= "name = " . pg_escape_string($this->name) . ", "; $sql .= "description = " . pg_escape_string($this->description) . ""; $sql .= "WHERE widgetID = " . $this->id; $rs = pg_query($this->hDB, $sql); } pg_close($this->hDB); } } ?> FYI: I have tried mysql_pconnect ! results => failure! I have tried replacing the prefix "pg" to "mysql" or "mysqli"! results => failure! I have tried switching parameters, say in pg_query($resource, $query) TO mysql_query($query, $resource) results => failure too! Thank you in advance! I have a script I am putting together that simulate a cricket game. The only issue is, that there are a huge number of functions because there doesn't seem to be any other way to do this properly. As well as this, there a while() loop and all this seems to be leading to the page reaching a max 30 second timeout when generating the result. My code is attached below, it is quite messy at the moment because i've just be working on it, but I was wondering if anyone has any solutions of how I can speed this up or change to prevent a timeout: <?php // Error reporting error_reporting(E_ALL); // Connect DB mysql_connect("wickettowicket.adminfuel.com", "rockinaway", "preetha6488") or die(mysql_error()); // Select DB mysql_select_db("wickettowicket") or die(mysql_error()); // MySQL queries to find batsmen and bowlers $array_batsmen = mysql_query('SELECT id, name, ability, strength FROM wtw_players WHERE team_id = 1 ORDER BY id ASC'); $array_bowlers = mysql_query('SELECT id, name, ability, strength FROM wtw_players WHERE team_id = 2'); // Start table for data $data = '<table width="600px">'; // Create blank scorecard while ($array_bat = mysql_fetch_array($array_batsmen)) { $data .= '<tr><td>'.$array_bat['name'].'</td><td></td><td></td><td>0</td></tr>'; } // Set up arrays for players $current_batsman = $current_bowler = array(); // Reset query mysql_data_seek($array_batsmen,0); $in_one = $in_two = $it = ''; function currentBatsman($id, $name, $ability, $strength, $out, $in, $runs) { global $current_batsman; $current_batsman = array ( 'id' => $id, 'name' => $name, 'ability' => $ability, 'strength' => $strength, 'out' => $out, 'in' => $in, 'runs' => $runs ); echo 'set current'; } // Set up arrays of batsmen while ($array = mysql_fetch_array($array_batsmen)) { if ($it < 3 && $in_one == '') { currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0); $batsmen[$array['id']] = array ( 'id' => $array['id'], 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'], 'out' => 0, 'in' => 1, 'runs' => 0 ); $in_one = $array['id']; $current = $array['id']; $it++; } else if ($it < 3 && $in_two == '') { $batsmen[$array['id']] = array ( 'id' => $array['id'], 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'], 'out' => 0, 'in' => 1, 'runs' => 0 ); $in_two = $array['id']; $it++; } else { $batsmen[$array['id']] = array ( 'id' => $array['id'], 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'], 'out' => 0, 'in' => 0, 'runs' => 0 ); } } // Bowler Array while ($array = mysql_fetch_array($array_bowlers)) { $bowlers[] = array ( 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'] ); } // Reset both queries mysql_data_seek($array_bowlers,0); mysql_data_seek($array_batsmen,0); function changeBatsman($just_out) { global $array_batsmen, $batsmen; //Update array $batsmen[$just_out] = array ( 'in' => 1, 'out' => 1 ); while ($array = mysql_fetch_array($array_batsmen)) { if ($just_out != $array['id'] && $batsmen[$array['id']]['out'] != 0) currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0); } // Reset query mysql_data_seek($array_batsmen,0); echo 'change batsman'; } function swapBatsman($other_batsman) { global $array_batsmen, $batsman; while ($array = mysql_fetch_array($array_batsmen)) { if ($other_batsman != $array['id'] && $batsman[$array['id']]['out'] != 0 && $batsman[$array['id']]['in'] == 1) currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0); } // Reset query mysql_data_seek($array_batsmen,0); echo 'swap batsman'; } $runs = $outs = $balls = $overs = 0; $played = array(); function selectBowler() { global $bowlers, $current_bowler; // Select random bowler $choose_bowler = array_rand($bowlers, 1); $current_bowler = array ( 'name' => $bowlers[$choose_bowler]['name'], 'ability' => $bowlers[$choose_bowler]['ability'], 'strength' => $bowlers[$choose_bowler]['strength'] ); } /* function selectBatsman(); { global $array_batsmen; while ($array_batsmen[]['out'] != 1) { }*/ function bowl() { global $batsmen, $bowlers, $current_bowler, $current_batsman, $data, $balls, $outs, $runs; if ($current_batsman['out'] == 0) { echo 'bowling'; // Set the initial number $number = rand(0, 190); // Ability of batsman if ($current_batsman['ability'] > 90) $number += 30; else if ($current_batsman['ability'] > 70) $number += 15; else if ($current_batsman['ability'] > 50) $number += 2; else $number = $number; // Strength of batsman if ($current_batsman['strength'] > 90) $number += 15; else if ($current_batsman['strength'] > 70) $number += 10; else if ($current_batsman['strength'] > 50) $number += 5; else $number = $number; // Depending on overs if ($balls > 270) $number += 30; else if ($balls > 120) $number -= 10; // Ability if ($current_bowler['ability'] > 90) $number -= 30; else if ($current_bowler['ability'] > 70) $number -= 15; else if ($current_bowler['ability'] > 50) $number -= 2; else $number = $number; // If batsman has made a huge total of runs, we need to knock some numbers off - more likely to get out if ($current_batsman['runs'] > 200) $number -= 70; else if ($current_batsman['runs'] > 100) $number -= 30; // Finally sort out runs if ($number > 190) $run = 6; else if ($number > 170) $run = 4; else if ($number > 160) $run = 3; else if ($number > 100) $run = 2; else if ($number > 50) $run = 1; else if ($number > 10) $run = 0; else if ($balls > 120 && $number > 0) $run = 0; else $run = -1; // Increase number of balls $balls += 1; // Are they out? if ($run == -1) { $current_batsman['out'] = 1; $played[] = $current_batsman['id']; $find = '<tr><td>'.$current_batsman['name'].'</td><td></td><td></td><td>0</td></tr>'; $replace = '<tr><td>'.$current_batsman['name'].'</td><td></td><td>'.$current_bowler['name'].'</td><td>'.$current_batsman['runs'].'</td></tr>'; $data = str_replace($find, $replace, $data); changeBatsman($current_batsman['id']); echo 'out'; } else { $current_batsman['runs'] += $run; $runs += $run; if ($run == 1 || $run == 3) { swapBatsman($current_batsman['id']); echo 'time to swap'; } echo $run; } // Count outs if ($current_batsman['out'] == 1) $outs += 1; } } function game() { global $main, $batsmen, $bowlers, $data, $batted, $balls, $outs, $current_batsman; // Check if possible while ($balls <= 295 && $outs < 10) { selectBowler(); // Actually bowl now bowl(); } } game(); echo $data; I teaching myself php, but I am coming from java and other compiled languages, so the process has been a little bumpy. I am trying to do something like this: Code: [Select] class my_class { function one () { $two = two (); $three = three (); $five = $two + $three; return $five; } function two () { $two = 2; return $two; } function three () { $three = 3; return $three; } } Unfortunately, I keep getting an error message saying that my call to two () is an undefined function. I am gathering from this that the scope of one () is not aware of the existence of two (). Is there a way to get around this so I can call two () and three () from one ()? i am wondering what the '@' is used for when used in front of a function like Function(@$VAR); What is the benefit of the @? Hi. I am trying to write a function but they are new to me and confusing me. On multiple pages I am requesting users details. I thought instead of writing out the query every time I want to do this I would include a functions page with the query in it. The only variable I carry from the user is the user name as a session when they log in. The user name is the email address of the person signed in. so here is my first function. As im sure you can see it doesn't work but I don't understand why or how to call it properly. Can someone please explain.... function GetUser($user = "") { $qFindUser = "SELECT * FROM members WHERE email = '$user'"; $rFindUser = mysql_query($qFindUser) or die (mysql_error()); $UserInfo = mysql_fetch_array($rFindUser); } calling the function to return all details of a member as an array. <?php $Name = $_SESSION['MM_Username']; $UserInfo = GetUser($Name); echo $UserInfo['forename']; ?> As painfully simple as this may be, I seem to be doing something wrong as always. New to php and decided to start using functions. I'm trying to add functions from an external functions.php file to my other pages and then call the functions where necessary. How should I go about it? I tried something like this: Functions.php: Code: [Select] <?php function field() { echo 'text heherh'; } ?> and then when calling it to when needed for example: include 'includes/functions.php'; // at the top of the page Code: [Select] <?php // and when trying to call the function on a specific line if (!$sname) $errorstring = $errorstring . "<b>Surname:" . field() ; //field being the function name ?> I know this is very simple but I have never used functions before.. tried google, didn't help much and I'm pressed for time so decided to ask here. Thanks in advance OK, so if I've got this in my one of my class files: public function userr($user) { $thisquery = mysql_query("SELECT * FROM users WHERE username='". $user ."'"); if(mysql_num_rows($thisquery) == 1) { return true; } return false; } Could I use something like this: if($class->userr($user)) { // Something } If not, how would I go about doing something like it? And is there any way I could use a mysql_fetch_assoc in a function? Hi, I've got 3 different upload forms in one form. I'm making a function so it just one piece of code. I'm having a bit of a problem changing some of the code so it works for all 3. Here is the function function loadImages ($action, $position) { $link = mysql_connect("","",""); if (!$link) { die('Error: could not connect: ' . mysql_error()); } $db_select = mysql_select_db("",$link); if (!$db_select) { die ("Error: database selection failed: " . mysql_error()); } $page = ($_POST["pageName"]); if ((($_FILES["bfile"]["type"] == "image/gif") || ($_FILES["bfile"]["type"] == "image/jpeg") || ($_FILES["bfile"]["type"] == "image/pjpeg")) && ($_FILES["bfile"]["size"] < 9000000)) { if ($_FILES["bfile"]["error"] > 0) { echo "Return Code: " . $_FILES["bfile"]["error"] . "<br />"; } else { $success = '<p style="font-weight: bold; color: #C00">Upload successful<br />'; // move uploaded temporary file to final destination move_uploaded_file($_FILES["bfile"]["tmp_name"], "uploads/" . $_FILES["bfile"]["name"]); // update database with new filename $filename = $_FILES["bfile"]["name"]; $sql = "UPDATE images SET filename= '$filename' where page = '$page' and position = '$position'"; if (!mysql_query($sql,$link)) { die('Error: ' . mysql_error()); } } } else { $fail = '<p style="font-weight: bold; color: #C00">Invalid file'; } mysql_close($link); } Now the $action is the bit that will determine whether it's updateTop updateMiddle or updateBottom. $position finds out if it's top middle or bottom if (isset($_POST['updateTop'])) { loadImages ($_POST['updateTop'], "top"); } Here is a sample of the html, it's in a switch case "Products": echo "<p>Image Top</p> <input type=\"file\" name=\"file\" id=\"file\" /> <input type=\"submit\" name=\"updateTop\" value=\"Update $page Top\" /> <p>Image Middle</p> <input type=\"file\" name=\"mfile\" id=\"mfile\" /> <input type=\"submit\" name=\"updateMiddle\" value=\"Update $page Middle\" /> <p>Image Bottom</p> <input type=\"file\" name=\"bfile\" id=\"bfile\" /> <input type=\"submit\" name=\"updateBottom\" value=\"Update $page Bottom\" /> "; break; What I need to do is get $_FILES["bfile" into a variable to see whether it's "bfile" "mfile" or "file" but not sure how to write it. Thanks for the help. Can someone tell me by looking at the following code why function pcust() does not work, I am new to programming? Code: [Select] $firstname = "chris"; $surname = "reynolds"; $address1 = "12 birch end"; $town = "Wallington"; $county = "surrey"; $postcode = "wh20 3bg"; $telephone = "01372 854785"; $cust_details = fix_cust($firstname, $surname, $address1,$town, $county, $postcode, $telephone ); function fix_cust($n1, $n2, $n3, $n4, $n5, $n6, $n7) { $n1 = ucfirst(strtolower($n1)); $n2 = ucfirst(strtolower($n2)); $n3 = ucwords(strtolower($n3)); $n4 = ucfirst(strtolower($n4)); $n5 = ucfirst(strtolower($n5)); $n6 = ucfirst(strtoupper($n6)); $n7 = ucfirst(strtolower($n7)); return array($n1, $n2, $n3, $n4, $n5, $n6, $n7); } echo $cust_details[0] . " " . $cust_details[1]; echo "<br />"; echo $cust_details[2]; echo "<br />"; echo $cust_details[3]; echo "<br />"; echo $cust_details[4]; echo "<br />"; echo $cust_details[5]; echo "<br />"; echo $cust_details[6]; echo "<br />"; function pcust(){ $length = count($cust_details ); for ($i = 0; $i < $length; $i++) { echo $cust_details[$i]; echo "<br />"; } } pcust(); Hey guys. Can anyone tell me what this means? function foo { } It is basic php but I don't get it. Should it be called for execution, or does it work automatically, or both? The php manual at w3schools and php.net are too tough for me. That's why I posted here. Thanks! I have a function to get some data from the database. However it always comes back with: Code: [Select] Notice: Undefined variable: db in C:\wamp\www\ASF A Simple Forum\functions\functions.php on line 233 Fatal error: Call to a member function query() on a non-object in C:\wamp\www\ASF A Simple Forum\functions\functions.php on line 233 here is the code: require_once(ASF_ROOT."includes/init.php"); // this is where the db connection is function get_db_info($type, $select, $table, $where="", $order="DESC", $limit="") { if (empty($type) || empty($select) || empty($table)) { try { throw new emptyArgs(); } catch (emptyArgs $invalid) { echo "<div style=\"border:1px solid #f00; padding:5px; width:350px; line-height:10px;\">"; echo "<b>$invalid</b>"; echo "<p>get_info() needs atleast 3 arguments (Type, Select and Table) - none supplied</p>"; echo "</div>"; } } else { if ($type == "num") { $query = $db->query(" SELECT $select FROM ".TBL_PREFIX."$table $where $order $limit ") or die($db->error()); $result = $db->num_rows(MYSQLI_NUM); return $result; } else { $query = $db->query(" SELECT $select FROM ".TBL_PREFIX."$table $where $order $limit "); $result = $query->fetch_array(MYSQL_ASSOC); return $result; } } } I have a function for mysqli_real_escape_string above this function and it works with no errors. Have i done something wrong? as you can see i am including the file which holds the connection but it doesnt seem to use it. every other file that uses the connection works fine. Hi, I could use a little guidance here. 1) is a function with values to be sent to 2). 1) <!-- use ajax - OnCalc function to send data to your database. --> function OnCalc(value1,op,value2,total) { 2) php file using above function values <?php header( "refresh:5;url='http://localhost/hom...lcprint.php'"); echo 'You\'ll be redirected in about 5 secs. If not, click <a href="http://localhost/hom...hp">here</a>.'; echo '<script type="text/javascript">' , 'OnCalc();' , '</script>'; No error but code not working? When in OOP I have been watching tutorials and some have functions just written like Code: [Select] class user { public $user; public function __construct($u) { $this->user = $u; } } do I need to type public before the function or is it better practice to just put Code: [Select] class user { public $user; function __construct($u) { $this->user = $u; } } Thanks! Hey , I'm looking for functions names from the GD directory. 1.function that open image. 2.function that getting pixel color. 3.function that changing pixel color. thanks. Hey, So i have an admin.php page that lists all of the users in the database and im wondering how i can add functions so the administrator can delete / ban the user from the webpage i'm not sure on how you would select the user?
Ok so I have these 2 functions set up to secure some things make_safe() is used before putting anything in the database. the make_viewable() function is used to display the data that was made safe. function make_safe($string) { // used before adding to db return addslashes($string); } function make_viewable($string) { // used before displaying anywhere return stripslashes($string); } is this enough or is there anything else to make this secure. Thanks Shane I'm using php's DOM functions to strip some information out of a block of HTML: Code: [Select] for ($i = 0; $i <= $tot_tblocks-1; $i++) { // Load the HTML blocks... $dom = new DOMDocument(); $dom->loadHTML($tblock[$i]); $xpath = new DOMXPath($dom); $tags = $xpath->query('//div[@class="desc"]/h2[@class="name"]'); // Get the part I want... foreach ($tags as $tag) { $tname[$i] = trim($tag->nodeValue); echo $tname[$i]."<br>"; } } Two questions: 1 - There is actually ever only one item ("name"), can I access it without the foreach loop? $tname[$i] = trim($tags->nodeValue); doesn't work. 2 - This code extracts content between tags of certain class names. But I would also like to extract the values of certain attributes of some of those tags, such as - perhaps - the value of the href in a <a> tag. The tag may not have unique class name, but I could still get an array from all the <a> tags in the source block? But I don't know how, and haven't been successful in deciphering the documentation... Any ideas? Hi everyone. Good day for coding? I created this tiny script just for self-learning purposes but I'd like to improve it. Here is the script: Code: [Select] <?php include_once 'dbinfo.php'; if(isset($_POST['submit'])) { $label = $_POST['label']; $stm = $connect->prepare("INSERT INTO words(word) VALUES (?)");//$stm = $connect->prepare("INSERT INTO words VALUES (?,?)"); $stm->bind_param('s', $label);//$stm->bind_param('ss', $label, $user);http://php.net/manual/en/mysqli-stmt.bind-param.php $stm->execute(); printf("%d Label inserted.\n", $stmt->affected_rows); $stm->close(); $connect->close(); } ?> <form action="" name="submit_label" method="POST"> <p>Submit a Label:<input type="text" name="label" value=""></p> <input name="submit" type="submit" value="Submit label"> <p></p> <a href="wordlist.php" >The List of labels</a> </form> <?php if ($stm = $connect->prepare("SELECT word, label_id FROM words ORDER BY label_id")){ $stm->execute(); $stm->bind_result($labelcol, $labelcol2); while($stm->fetch()){ printf("%s %s</br>", $labelcol, $labelcol2); } $stm->close(); } $connect->close(); ?>It submits words and insert them in a table called words. It also outputs the table content, the submitted words. An image of a database structure is attached to this post. What I'd like to do is to count the how many times the same words are repeatedly submitted and output the the repeated word next to the number of times it is repeated. For example: user 1 submitted 'awesome' 3 times so it shows awesome (3) user2 submitted 'bad' 45 times so it shows bad (45).... and so on I'm guessing that I should use arrays and and built in functions and things like that but my question which functions should I use to get started or just give me some hint how to use arrays in this case. Thank you very much in advance. [attachment deleted by admin] |