PHP - Simple:passing Null Value To Function
Code: [Select]
function display_details($name, $department="sales", $sex="male") { return "You are {$name} from {$department} and you are {$sex}"; } I need to use the default value for $department, but none of the below work. How do I do it? echo $display_details("Sally", NULL, "female"); // sets $department as empty/blank echo $display_details("Sally", "", "female"); // sets $department as empty/blank echo $display_details("Sally", , "female"); // PHP error Similar TutorialsHi guys, I am trying to install a script and I am getting this error when loading for the first time kindly assist anyone.
Hi guys, I am trying to implement a Pagination class for a website displaying movies. I need to have the total number of posts, but on accessing the function row_count() from class Connection I get the error: "Fatal error: Uncaught Error: Call to a member function query() on null in ..\connection.php:30 Stack trace: #0 from ...\index.php(20): Connection->row_count() #1 ..." I only found two posts concerning this issue, and they led me to think this might be a scope issue with $db variable; $db is defined in the constructor function of the same Connection class so I thought the scope would be ok; but apparently, not. Can anybody help? This is a real show-stopper just now. Please let me know if you need any further information. Thanks in advance. Sept connection.txt index.txt Hello, my global variable is getting whacked (defined null or being undefined) after a function call. I'm not sure if it's happening when leaving the function that assigns it or when the form is "posted", or something else. Code: [Select] <? //global variables $globalVarString = ""; //function definitions function displayResults() { global $globalVarString; if ($globalVarString == "") {displayForm("please enter your search string again");} else {displayForm("you typed: $globalVarString");} } function getResults($searchInput) { global $globalVarString; $globalVarString = $searchInput; //give status ?> <html><head><title>Search</title></head><body> <form action="<?=$_SERVER['PHP_SELF']?>" method="post"> Thanks for entering your data (<? echo "$globalVarString" ?>).<br><br>Please press the submit button to process your data    <input type="Submit" value="Submit" name="processQuery"> </form></body></html> <? } function displayForm($message) { //prompt for input ?> <html><head><title>Search</title></head><body> <form action=" <? $_SERVER['PHP_SELF'] ?>" method="post"> <h3>Please enter your search <input type="text" name="searchString">    <script type="text/javascript">document.forms[0].searchString.focus();</script> <input type="Submit" value="Submit Query" name="searchQuery"></h3> </form> <? if (!$message == ""){echo "<br>    <h4>" . $message . "</h4><br>";} ?> </body></html> <? } //main() if(array_key_exists('searchQuery', $_POST)) {getResults($_POST['searchString']);} elseif (array_key_exists('processQuery', $_POST)) {displayResults();} else {displayForm("");} ?> Been scratching my head about this all day. Cannot figure it out. Any help would be appreciated. Code: [Select] <?php $selectClause = 'SELECT * FROM idInfo WHERE'; $whereClause = ''; function addWhere($fxnName, $fxnValue) { if (!$whereClause) { return $fxnName . '=\'' . $fxnValue . '\''; } else { return ' AND ' . $fxnName . '=\'' . $fxnValue . '\''; } } $whereClause.=addWhere("firstName", $firstName); $whereClause.=addWhere("lastName", $lastName); $whereClause.=addWhere("idNum", $idNum); echo 'mysql_query("' . $selectClause . ' ' . $whereClause . '"); <br /><br />'; ?> This is meant to generate a query of the type: Code: [Select] SELECT * FROM idInfo WHERE firstName='firstNameINPUT' AND lastName='lastNameINPUT' AND idNum='idNumINPUT' For some reason, though, the if statement always reads false. No matter how I try to work the syntax Code: [Select] if (!$whereClause) if ($whereClause) if ($whereClause == NULL) if ($whereClause != NULL) if (empty($whereClause) etc. I've tried all of those and more, experimenting with and without quotes. They always return a FALSE for the existence of the variable, so that the string never contains the word "AND" as it should by the end. I've tried these same if statements outside the function and they work fine. Inside the function, it doesn't matter what the value of the variable is, the function runs as though it has no value. Comments? Suggestions? Excerpts of code: function addUser() { $username = $_POST['username']; $password = password_hash($_POST['password'], PASSWORD_DEFAULT); $bio = $_POST['bio']; $email = $_POST['email']; $c_status = 0; //$avatar = //$username_query = $pdo->prepare("SELECT * from profiles001 WHERE username=':username'"); //$username_query->bindValue(':username', $username); //$username_query->execute(); $query = $pdo->prepare("INSERT into profiles001 (username, password, email, c_status, bio) VALUES (:username, :password, :email, :cstat, :bio)"); $query->bindValue(':username', $username); $query->bindValue(':password', $password); $query->bindValue(':email', $email); $query->bindValue(':cstat', $c_status); $query->bindValue(':bio', $bio); $query->execute(); setAvatar(); } function setAvatar() { // check if avatar is set, if not give default avatar if (isset($file) && $fileError === UPLOAD_ERR_OK) { $file = $_FILES['userfile']; $fileName = $file['name']; $fileTmpName = $file['tmp_name']; $fileSize = $file['size']; $fileError = $file['error']; $fileType = $file['type']; $fileExt = explode('.', $fileName); $fileActualExt = strtolower(end($fileExt)); $allowedExtensions = array('jpg', 'jpeg', 'png'); } // if user has not assigned avatar, assign the default. if (empty($file)) { $avatar = "assets/soap.jpg"; $query = $pdo->prepare("INSERT INTO profiles001 (avatar) VALUES (:avatar)"); $query->bindValue(':avatar', $avatar); $query->execute(); } } addUser(); } From the database file: <?php $host = "localhost"; $database = "soapbox"; $username = "drb"; $password = "m1n3craft"; // Create connection $pdo = new PDO('mysql:host=localhost;dbname=soapbox;', $username, $password); /* Print error message and or code to the screen if there is an error. */ ?> NOTE: I also require dbcon.php at the top of the confirmation.php file which is NOT included in the excerpt at the top. Making pdo a global variable would probably fix it, but from what I heard globals are frowned upon. i've tried whit a lot of solutions from other posts but nothing seems to be working
this part is where im having trouble but i dont know how to get it to work
namespace App\Controllers;
class Home extends BaseController
//Set form validation
//Run form validation
//Get the form data
//Web master email
//Mail settings $this->email->initialize($config);
//Send mail with data
redirect('contact');
}
<div class="header">
<a href="javascript:void(0);" class="mobi-toggler"><i class="fa fa-bars"></i></a>
<!-- BEGIN NAVIGATION --> Hi All, I have the following code which works fine: $mysqli = new mysqli("server", "user", "pass", "database"); if($mysqli->connect_error) { exit('Could not connect'); } $sql = "SELECT customer_contactname, customer_companyname, customer_phonenumber, customer_emailaddress, customer_address1, customer_address2, customer_city, customer_postcode FROM ssm_customer WHERE customer_id = ?"; $stmt = $mysqli->prepare($sql); $stmt->bind_param("s", $_GET['q']); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($ccontname, $ccompname, $cphoneno, $cemail, $cad1, $cad2, $ccity, $cpost); $stmt->fetch(); $stmt->close(); however, when i use my dbconn.php as an include rather than the top section of this code, i get the following error: function prepare() on null The error references the following $stmt = $mysqli->prepare($sql); In my database connection file, i am using the following: $conn = mysqli_connect($db_servername, $db_username, $db_password, $db_name); This seems to be the issue and i believe i am mixing procedural and object based but not sure why there should be a difference here? when i used my database connection file, i do change $mysqli->prepare to $conn->prepare Kind Regards Edited February 4, 2019 by Adamhumbugthe ultimate goal is to let the user select to date range (begin date in DD-MM and enddate in DD-MM), pass this through php file with ajax and query it against the registered date (stored as a datetime), however i'm already running problems catching the values of minDate and maxDate. Can sombody tell me what's wrong please? Code: [Select] if (document.getElementById('brdat_dag').value != ''){ var minDag = document.getElementById('brdat_dag').value;} if (document.getElementById('brdat_maand').value != ''){ var minMaand = document.getElementById('brdat_maand').value; } var minDate = date ('Y-m-d H:i:s', mktime (0,0,0,minMaand,minDag.value,date('Y', time()))); var queryString = "?postcode=" + postcode + "&provincie=" + provincie + "&aland=" + aland + "&gland=" +gland +"&minAge=" + minAge +"&maxAge=" + maxAge + "&sex=" + sex; + [color=red]"&minDatum=" + minDatum;[/color] This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=355809.0 Hi there, I've just started learning php and mysql today. I'm putting things together in dreamweaver and everything is running smoothly (ish). I've got a form written in php that sends data to a database. All fine. I need to send the time of submission to the database. I've put in a hidden field, what code should I use to set the field value to a mysql field of type DATETIME? Cheers. Mon Aug 24, 2020 2:41 pm I'm using php_serial.class.php, called once require_once("php_serial.class.php"); and call it $serial: $serial = new phpSerial;
The above are in a global.php file that sets up the serial com parameters. Function checkInput($serial){ And one in the Function: $read = $serial->readPort();
This throws an error: "PHP Fatal error: Uncaught Error: Call to a member function readPort() on string" I have a odd one here, two classes and one which calls another class. I want to pass all of the parameters from the array as seperate variables into the next function. Hope my example explains a little better class master{ public function __call($name, $args) { second->$name($args); }}class second{ public function example($param1, $param2) { }}master->example($param1, $param2);() ( i know its not accurate php, but should get the idea of what im trying to do) I need to do something with the following line second->$name($args); Where param1 and param2 will be seperated out Is there a php function which you can tell it the class, method name and pass it an array of parameters? Thanks Help I am trying to pass a php variable into a javasript function. Here is my code.
<a href="<?php echo $row['track']; ?>" download="<?php echo $row['track']; ?>" onclick="myhit(<?php echo $row['track']; ?>)">Download</a> <script> function myhit(top){ alert(top); } </script>the javascript function is never called function chk_error($site_mode, $obj) { if( $site_mode == 'dev' ) { echo'Error : ('. $obj->errno .') '. $obj->error; } } chk_error($site_mode, $stmt);the above is not working for me. it echos out the text but no values for errno and error. what am i doing wrong? http://pastebin.com/DbHQSYd7 Been stumbling my way through OOP and seem to be understanding it for the most part (I think..) But I've got a couple questions / kinks that I can't seem to work out. a) How do I return a variable from a class so that a different class has access to it (meta_data) b) I'm getting a "$this" cannot be redefined error (which I know why, but I don't know how to fix)) c) How do I call a function from within one class, where the function resides in another class, AND pass it variables? Any help would be greatly appreciated I've tried to Google warrior A and I think I can figure that one out, but B and C are proving to be the real stumbling blocks. Ok, starting around line 137 with the functions..... Commented well. Just not sure If im doing it right. Any help greatly appreciated. Basic stuff and still learning. Just trying to figure out if Im passing by reference correctly or if not how to do it. Thanks. php File is attached but heres a snippet. Thanks in advance. Peace, Adam // The grand total and the item total need to be passed BY REFERENCE. function show_table_contents($cart_items, $table, &$grand_total, &$item_total) Firstly i am new to php.Iv currently got this while loop iterating through a database drawing polygons from the info in the datatable.each polygon has its own id stored in the datatable and with the on click event i am trying to just output to the screen the specific id of the polygon clicked on.It looks ok to me but it doesnt work for some reason. Below is the loop and the function it is trying to call. /////////////////////////////////////////////////////////////////////// <?php while($info = mysql_fetch_array( $data )){ echo "<polygon fill=".$info['fill_colour']." stroke=\"black\" id=".$info['id']." onclick=\"buildingClick(id)\" points=".$info['coordinates']." />"; } ?> ///////////THIS IS THE FUNCTION/////////////////////////// <?php function buildingClick($id) { echo "building id : {$id}"; } ?> /////////////////////////////////////////////////////////////////// If anyone could help it would be hugely appreciated. Eoin Hello everyone, Pretty much what I am trying to do is run a query and based of the queries result, return a string - as of now it is turning up blank and cant seem to pass any strings through the function. Current function: function addNewBookmark($hash,$url,$title,$username){ Code: [Select] $query = "INSERT INTO bookmarks (hash,url,title,username) VALUES '".md5($hash)."', '".$url."', '".$title."', '".$username."')"; $result = mysql_query(query, $this->connection); $message = ''; if(mysql_affected_rows($this->connection)!=1) { $message = 'This URL already exists in the database!'; return $message; } else $message = 'The URL was shared!'; return $message; } The above code seems to run fine, just cant seem to pass a string...read that you can possibly use a __toString function? but that keeps throwing errors when I try to work with it. Thanks all! I am trying to update the database with isset to set the value of the variable to either null or the value entered by the user. Currently, if no value has been entered null is being set as a string causing the date field to populate with zeros. How do I code it so that it populates or sets the value as null and not as string null?
Here's my code: (yes I know sql injections it's still in development )
<?php Hey guys, I want to pass the unique id of a node to a function when that image is clicked. Actually i am a newbee in php so don't know what to search about or where to look for it,but find this place and you all guys so helpful so i am asking for a guide here |