PHP - Object Of Class Mysqli_result Could Not Be Converted To String
The following is an extract of PHP code I have interacting with a MySQL database and I keep getting the "object of class mysqli_result could not be converted to string" error on the line of code inside my loop. This is my code.
#This is just storing a single integer, a moduleID
$sqlmodID = mysqli_query($con,"select moduleID from module_details WHERE moduleName = '$moduleName' AND lecturerID = '$lecturerID'"); #This is a query to get relevant idNumbers $sqlstudent = "select idNum from user_info WHERE courseCode = '$courseCode'";
#Running the previous statement $result = mysqli_query($con, $sqlstudent);
#Storing the statements results in an array $row = mysqli_fetch_array($result);
#I'm not sure if this line is necessary but it converts the array values into a string (I'm storing the ID's as strings as they contain numbers and letters) $studentArray = array_map('strval', $row);
#The error flashes on my condition of this loop. I'm trying to take each element of my array, and enter it to my table, assigning each variable the same ModuleID.
for($i=0; $i < count($studentArray); $i++){
Any help would be much appreciated. I hope I've explained my code sufficiently. Similar TutorialsHi all
i am using the code below, but am getting the error
Object of class mysqli_result could not be converted to int
<?php $sql="SELECT lng,lng_prefix FROM tbl_languages where active = 1"; $result=mysqli_query($dbConn, $sql)or die(mysqli_error($dbConn)); //problem line if(mysqli_num_rows($result==1)){ ?>The code continues with what I want to happen based on the result. What does the error mean and how do I fix it? I'm receiving the error "Object of class player could not be converted to string" yet I cannot find why what I'm inputting is an object and not a string. As far as I can see it is a string and this error shouldn't be happening, yet it is... A form submits to a page which gets the data thus: Code: [Select] <?php case "updplayer": if(!isset($_GET['id']) || !isset($_POST['kit']) || !isset($_POST['level']) || !isset($_POST['group']) || !isset($_POST['state'])) { header("location:admin.php?mode=settings&error=info&sid=$user->sid"); exit; } $var = "player" . $_GET['id']; $$var->kit = mysql_real_escape_string($_POST['kit']); $$var->level = mysql_real_escape_string($_POST['level']); $$var->group = mysql_real_escape_string($_POST['group']); $$var->state = mysql_real_escape_string($_POST['state']); $$var->update(); header("location:admin.php?sid=$user->sid"); exit; break; The update function is: Code: [Select] <?php function update() { echo "Name: $this->name <br /> Kit: $this->kit <br /> Level: $this->level <br /> Group: $this->group <br /> State: $this->state <br />"; $sql = "UPDATE `players` SET `name` = '" . $this->name . "', `preferredKit` = '" . $this-kit . "', `gamingLevel` = '" . $this->level . "', `group` = '" . $this->group . "', `draftState` = " . $this->state; if(!mysql_query($sql)) { return mysql_error(); } return TRUE; } I added the echo's in for error checking. They output exactly what was expected. What is wrong with this? Error occurs on the "$sql = " line. why do i keep getting this error from line 7? Object of class stdClass could not be converted to string Code: [Select] <?php include_once"../includes/db_connect.php"; $item_number="2"; $custom="54298"; $query=mysql_query("SELECT `prodID`, `quanity` FROM `cart` WHERE `sessID`='$custom'") or mysql_error(); while($cart=mysql_fetch_object($query)){ mysql_query("INSERT INTO `orderItems` ( `id` , `orderInfoID` , `productID` , `quanity` ) VALUES ('', '$item_number', '$cart-> prodID', '$cart->quanity');"); } mysql_query("UPDATE `cart` SET `show`='1' WHERE `sessID`='$custom'"); ?> I have the following script: <?php $tijd[] = '2012-05-23T02:00:00'; $date = new DateTime($tijd[0]); echo $date; ?> However it is not working and resulting in: Quote Catchable fatal error: Object of class DateTime could not be converted to string in time3.php on line 7 I think to solve this issue, I have to convert $tijd[0] into a string. Right? If this is correct, how do I do that? Hi everyone, I get this error: Catchable fatal error: Object of class Category could not be converted to string The code: public static function list_all_cat_names() { $result_array = self::find_by_sql("SELECT name FROM ".self::$table_name); return !empty($result_array) ? array_shift($result_array) : false; } $categories = Category::find_all(); foreach ($categories as $cats): echo $cats; endforeach; Where could be the problem? Hello , I have a made a PHP website where users signup and send their Date of Birth and gets an OTP on their email after signup. The OTP is recieved but when we enter the OTP this problem occurs QuoteError! Something went wrong and I am facing this error in the error log QuotePHP Fatal error: Uncaught Error: Object of class DateTime could not be converted to string This is my config.php code <?php session_start(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Confirmation Page - Kanha Stories</title> <style> body { background-color: #330000; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100%25' height='100%25' viewBox='0 0 800 400'%3E%3Cdefs%3E%3CradialGradient id='a' cx='396' cy='281' r='514' gradientUnits='userSpaceOnUse'%3E%3Cstop offset='0' stop-color='%23D18'/%3E%3Cstop offset='1' stop-color='%23330000'/%3E%3C/radialGradient%3E%3ClinearGradient id='b' gradientUnits='userSpaceOnUse' x1='400' y1='148' x2='400' y2='333'%3E%3Cstop offset='0' stop-color='%23FA3' stop-opacity='0'/%3E%3Cstop offset='1' stop-color='%23FA3' stop-opacity='0.5'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect fill='url(%23a)' width='800' height='400'/%3E%3Cg fill-opacity='0.4'%3E%3Ccircle fill='url(%23b)' cx='267.5' cy='61' r='300'/%3E%3Ccircle fill='url(%23b)' cx='532.5' cy='61' r='300'/%3E%3Ccircle fill='url(%23b)' cx='400' cy='30' r='300'/%3E%3C/g%3E%3C/svg%3E"); background-attachment: fixed; background-size: cover; padding: 20px; width: 100vw; height: 100vh; display: flex; align-items: center; justify-content: center; color:#ffffff; overflow-x: hidden; } .cont { padding: 20px 40px; position: relative; border-right: 4px solid rgb(184, 182, 182); border-bottom: 4px solid rgb(184, 182, 182); border-radius: 15px; display: flex; flex-direction: column; align-items: center; } #left{ float: left; } #right{ float: right; } input{ margin: 10px 0px; } s{ padding: 5px; } .error{ padding: 5px; color: #ffffff; } .resend{ color: rgb(14, 14, 196); padding: 5px; } .s:hover{ cursor: pointer; background-color:gray; color: rgb(243, 237, 237); border-radius: 5px; } </style> </head> <body> <?php $code=""; $err=""; $error=""; if(($_SERVER["REQUEST_METHOD"]=="GET" && $_SESSION['xyz'] === 'xyz') || isset($_POST['verify']) || isset($_POST['resend'])) { unset($_SESSION["xyz"]); if($_SERVER["REQUEST_METHOD"] ==="POST") { if(isset($_POST['verify'])) { if(empty($_POST['code'])) { $err="Enter the code!"; } else { $code=$_POST['code']; if(password_verify($code,$_SESSION['code'])) { $name=$_SESSION['name']; $email=$_SESSION['email']; $tel=$_SESSION['tel']; $dob=$_SESSION['dob']; $password=$_SESSION['password']; $age_category=$_SESSION['age_category']; require_once('./all_utils/connection.php'); $sql="INSERT INTO identity_table(name,email,password,tel,dob,age_category) VALUES ('$name','$email','".$password."','$tel','$dob','$age_category')"; if(mysqli_query($conn,$sql) === TRUE) { unset($_SESSION["name"]); unset($_SESSION["password"]); unset($_SESSION["dob"]); unset($_SESSION["tel"]); unset($_SESSION["age_category"]); header("location:welcome/welcome.php"); } else { $err="Error! Something went wrong"; } } else { $err="Incorrect code!"; } } } elseif(isset($_POST['resend'])) { require_once('./all_utils/mail.php'); $error="OTP has been sent again!"; } } } else{ header("location:signup.php"); } ?> <div class="cont"> <h2> Email Verification</h2> <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="POST"> <label for="verification">Enter the 5 digit code</label> <br/> <p> Didn't got the mail? Please check your spam folder </p> <input type="text" name="code" placeholder="Eg. 12345" value="<?php echo $code; ?>"> <br/> <div class="error"><?php echo $err; ?></div> <div class="resend"><?php echo $error;?></div> <input type="submit" name="resend" class="s" id="left" value="Resend OTP"> <input type="submit" name="verify" class="s" id="right" value="Verify"> </form> </div> </body> </html>
This is my signup.php code <?php session_start(); if(!empty($_SESSION['email'])) { require_once('./all_utils/connection.php'); $query="SELECT * FROM identity_table WHERE email='".$_SESSION['email']."'"; $result=mysqli_query($conn,$query); if(mysqli_fetch_assoc($result)) { header("location:welcome/welcome.php"); } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>SignUp - Kanha Stories</title> <style> * { margin: 0; padding: 0; } body { width: 100vw; height: 100vh; display: flex; align-items: center; background-color: #ff9d00; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100%25' height='100%25' viewBox='0 0 1600 800'%3E%3Cg stroke='%23000' stroke-width='66.7' stroke-opacity='0' %3E%3Ccircle fill='%23ff9d00' cx='0' cy='0' r='1800'/%3E%3Ccircle fill='%23f27d00' cx='0' cy='0' r='1700'/%3E%3Ccircle fill='%23e55f00' cx='0' cy='0' r='1600'/%3E%3Ccircle fill='%23d84400' cx='0' cy='0' r='1500'/%3E%3Ccircle fill='%23cb2c00' cx='0' cy='0' r='1400'/%3E%3Ccircle fill='%23bf1600' cx='0' cy='0' r='1300'/%3E%3Ccircle fill='%23b20300' cx='0' cy='0' r='1200'/%3E%3Ccircle fill='%23a5000e' cx='0' cy='0' r='1100'/%3E%3Ccircle fill='%2398001c' cx='0' cy='0' r='1000'/%3E%3Ccircle fill='%238b0027' cx='0' cy='0' r='900'/%3E%3Ccircle fill='%237e0030' cx='0' cy='0' r='800'/%3E%3Ccircle fill='%23710037' cx='0' cy='0' r='700'/%3E%3Ccircle fill='%2364003b' cx='0' cy='0' r='600'/%3E%3Ccircle fill='%2358003c' cx='0' cy='0' r='500'/%3E%3Ccircle fill='%234b003a' cx='0' cy='0' r='400'/%3E%3Ccircle fill='%233e0037' cx='0' cy='0' r='300'/%3E%3Ccircle fill='%23310030' cx='0' cy='0' r='200'/%3E%3Ccircle fill='%23210024' cx='0' cy='0' r='100'/%3E%3C/g%3E%3C/svg%3E"); background-attachment: fixed; background-size: cover; overflow-x: hidden; } .cont { color: #ffffff; width: 500px; margin: auto; } h2 { color: #ffffff; text-align: center; padding: 1.5px; } .error { text-align: center; padding: 20px; font-size: 1rem; color: rgb(233, 76, 76); } form { font-size: 1.2rem; /* width: 40%; */ /* margin: auto; */ } .in{ margin: 5px 0; } input { border: 2px solid white; padding: 10px; margin: 5px 0; font-size: 1rem; width: 100%; } input:hover { border: 2px solid rgb(228, 81, 81); cursor: text; } p,a{ text-align: center; font-size: 1rem; } a{ color: deepskyblue; font-size:20px; } #s{ text-decoration:none; border-radius: 12px; } #s:hover { cursor: pointer; } a { text-decoration: none; } @media only screen and (max-width: 600px){ .cont{ width: 300px; } .error,input{ font-size: 0.8rem; } } @media only screen and (max-width: 400px){ .cont{ width: 70%; } h2{ font-size: 1.3rem; } a,p{ font-size: 0.7rem; } label{ font-size: 1.0rem; } input{ padding: 4px; } } </style> </head> <body> <?php $name=""; $email=""; $tel=""; $dob=""; $err=""; $name_err=""; $email_err=""; $tel_err=""; $dob_err=""; $password_err=""; if($_SERVER["REQUEST_METHOD"]=="POST") { if(isset($_POST['signup'])) { if(empty($_POST['name']) || empty($_POST['dob']) || empty($_POST['tel']) || empty($_POST['email']) || empty($_POST['password'])) { if(empty($_POST['name'])) { $name_err="Name is required!"; } else{ $name=$_POST['name']; } if(empty($_POST['email'])) { $email_err="Email is required!"; } else{ $email=$_POST['email']; } if(empty($_POST['tel'])) { $tel_err="Contact Number is required!"; } else{ $tel=$_POST['tel']; } if(empty($_POST['dob'])) { $dob_err="D.O.B is required!"; } else{ $dob=$_POST['dob']; } if(empty($_POST['password'])) { $password_err="Password is required!"; } } else { $today = new DateTime(date('m.d.y')); $dob = new DateTime($_POST['dob']); $diff1 = $today->diff($dob); $age = $diff1->y; if($age > 15 || $age <3) { $dob = $_POST['dob']; $dob_err = "Age criteria not satisfied , child's age must be between 3-15 years"; } else { require_once("./all_utils/connection.php"); $email=$_POST['email']; $query="SELECT * FROM identity_table WHERE email='".$email."'"; $result=mysqli_query($conn,$query); if(mysqli_fetch_assoc($result)) { $err="Email alredy registered!"; $name=$_POST['name']; $email=$_POST['email']; } else { if($age < 7) { $_SESSION['age_category'] = '1'; } else { $_SESSION['age_category'] = '2'; } $_SESSION['name']=$_POST['name']; $_SESSION['email']=$_POST['email']; $_SESSION['password'] = password_hash($_POST['password'],PASSWORD_DEFAULT); $_SESSION['tel']=$_POST['tel']; $_SESSION['dob']=$_POST['dob']; $_SESSION['xyz']='xyz'; require_once("all_utils/mail.php"); header("location:conf.php"); } } } } } ?> <div class="cont"> <h2>SignUp - Kanha Stories</h2> <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])?>" method="POST"> <span class="error"><?php echo $err; ?></span> <br/> <label for="name">Name</label><br /> <input type="text" name="name" placeholder="Enter your name" value="<?php echo $name; ?>"> <span class="error"><?php echo $name_err; ?></span> <br/> <label for="email">Email</label><br /> <input type="email" name="email" placeholder="Enter your Email ID" value="<?php echo $email; ?>"> <span class="error"><?php echo $email_err;?></span> <br/> <label for="tel">Mobile Number</label><br /> <input type="tel" name="tel" placeholder="Enter Mobile Number" value="<?php echo $tel; ?>"> <span class="error"><?php echo $tel_err;?></span> <br/> <label for="date">D.O.B. of Child (Click on Calander icon)</label><br /> <input type="date" name="dob" placeholder="Enter date of birth " value="<?php echo $dob;?>"> <span class="error"><?php echo $dob_err;?></span> <br/> <label for="password">Password</label><br /> <input type="password" name="password" placeholder="Enter your Password"> <span class="error"><?php echo $password_err; ?></span> <br/> <div class="sub"> <input type="submit" name="signup" id="s" placeholder="Submit"><br /> </div> </form> <p>Already registered? <a href="./login.php">log in here</a></p> </div> </body> </html>
I don't know what I can do now , Please try to give me the solutions as soon as possible. Thanks Hi guys, I have below values in array Code: [Select] stdClass Object ( [Category] => stdClass Object ( [ChildCategoryDescription] => 50s / 60s ERA [ChildCategoryID] => 87 [GrandchildCategoryDescription] => - [GrandchildCategoryID] => 25 [ParentCategoryDescription] => CONCERTS [ParentCategoryID] => 2 ) [Description] => Tony Bennett [ID] => 1073 [HomeVenueID] => 0 ) When am calling Desciption object by $resultsObj->Description then i got the result " Tony Bennett" but i do not know to get the value GrandchildCategoryID . Just i tried this Code: [Select] echo $resultsObj->$resultsObj->ParentCategoryID and i got below error. Catchable fatal error: Object of class stdClass could not be converted to string in D:\Program Files\xampp\htdocs\t1\genericLib.php on line 255. How i can get this value... PLEASEEE no matter what i do... datepicker always post the dates as string i do whatever ways know convert string to date but no way!! how convert string to date so i can sarch in a mysql table... tnx in advanced <!--HTML-->
<div class="control-group"> <!--PHP-->
$yfromx=$_POST['from'] ;
$t1=gettype ( $yfromx ) ;
I am preparing $begin and $end for DatePeriod() but I can't get passed this error "getting the error Recoverable fatal error: Object of class DateTime could not be converted to string". $today = date("Y-m-d"); $datestop=$_POST['datestop']; //echo "$today<br /><br />$datestop<br /><br />"; $begin = new DateTime("$today"); $end = new DateTime("$datestop");
I have mysqli object in Database class base: [color=]database class:[/color] class Database { private $dbLink = null; public function __construct() { if (is_null($this->dbLink)) { // load db information to connect $init_array = parse_ini_file("../init.ini.inc", true); $this->dbLink = new mysqli($init_array['database']['host'], $init_array['database']['usr'], $init_array['database']['pwd'], $init_array['database']['db']); if (mysqli_connect_errno()) { $this->dbLink = null; } } } public function __destruct() { $this->dbLink->close(); } } Class derived is Articles where I use object dBLink in base (or parent) class and I can't access to mysqli methods (dbLink member of base class): Articles class: require_once ('./includes/db.inc'); class Articles extends Database{ private $id, .... .... $visible = null; public function __construct() { // Set date as 2009-07-08 07:35:00 $this->lastUpdDate = date('Y-m-d H:i:s'); $this->creationDate = date('Y-m-d H:i:s'); } // Setter .... .... // Getter .... .... public function getArticlesByPosition($numArticles) { if ($result = $this->dbLink->query('SELECT * FROM articles ORDER BY position LIMIT '.$numArticles)) { $i = 0; while ($ret = $result->fetch_array(MYSQLI_ASSOC)) { $arts[$i] = $ret; } $result->close(); return $arts; } } } In my front page php I use article class: include_once('./includes/articles.inc'); $articlesObj = new articles(); $articles = $articlesObj->getArticlesByPosition(1); var_dump($articles); [color=]Error that go out is follow[/color] Notice: Undefined property: Articles::$dbLink in articles.inc on line 89 Fatal error: Call to a member function query() on a non-object in articles.inc on line 89 If I remove constructor on derived class Articles result don't change Please help me I am calling an object from another class in the constructor of first class but when I call it in another function it does not access it's object. Here is the code. Code: [Select] <?php /* This is controller.php used to control the flow of data between view.php and model.php. This file cotains all the controlling mechanism of the data It was created on 11th Feb 2011 By Narjis Fatima for an Open Source Project and contains all the includes to the database etc. */ include ("view.php"); include ("functions.php"); $name = stripslashes($_GET['username']); $email = stripslashes($_GET['email']); //echo "in controller.php"; check_validate_input($name, $email); $newUser = new controller($name, $email); $action=$_GET['t']; $newUser->display_view($action); class controller { public $my_model; //is an object of model class public $user_info;//=array('id' , 'username' ,'role','email','interests','location', 'homepage'); function __construct($name,$email) { $my_model = new model(); $user_info = $my_model->check_members($name,$email); echo "<pre>"; print_r ($user_info); } function __destruct() { } function display_view($token) { echo "In display function"; echo "<pre>"; print_r ($user_info); if ($this->user_info == NULL) { if (($token=="register")) { show_registration_form(); } else{ show_mailing_form(); } } if ($this->user_info['role'] == "admin") { $myView = new view(); $myView->view_admin_menu(); } if ($this->user_info['role'] == "user") { $myView = new view(); $myView->view_user_menu() ; } }//close of function display_view() } /* name and email cominfg from index.php would be checked by the controoler class to be checked if it a vaild name and email. The database would be connected n the model.php*/ ?> The code for model.php is as follows Code: [Select] <?php //This is model.php created on 10th Feb 2011 .It deals with daytabase connection // //By NArjis Fatima //For the project of EDUForge an Open Source Software //include ("register.php"); class model{ public $dbh; public $user_arr=array('username','password','email','location','interest','homepage'); //cunstructor of model class //function to connect to database function __construct(){ try{ $this->dbh = new PDO("mysql:host=localhost;dbname=phpfaqproject",'root',''); //echo "connected"; } catch(PDOException $e){ echo $e-> getMessage(); } } public function check_members($username,$email) { //get_connected(); $sql = "SELECT * FROM account WHERE (username='" .$username ."' AND email='" .$email."')"; $sth = $this->dbh->prepare($sql); $sth->execute(); $result = $sth->fetch(); /* echo('<pre>'); print_r($result);*/ return ($result); } public function insert_data($user_info) { //$user_info = $user_in; //$dbh; try{ $dbh = new PDO("mysql:host=localhost;dbname=phpfaqproject",'root',''); //echo "connected"; } catch(PDOException $e){ echo $e-> getMessage(); } $dbh->exec("INSERT INTO account (username, userpassword, email, role, location, interest, homepage) VALUES ('" .$user_info['username']."','".$user_info['password'] ."','".$user_info['email']."', 'user','".$user_info['location']."','".$user_info['interests'] ."','".$user_info['homepage']."')"); } } ?> Please somebody help me. I am really stuck. I am also sending my attachment. Folks, I need to Extract the Content of "[content] => " Class from the output of the below Script: <?php $keywords = file_get_contents('http://ajax.googleapis.com/ajax/services/search/web?rsz=large&v=1.0&q="paintball"'); $keywords = json_decode($keywords); print_r($keywords); ?> Output is like: Quote stdClass Object ( [responseData] => stdClass Object ( [results] => Array ( => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.paintball.com/ [url] => http://www.paintball.com/ [visibleUrl] => www.paintball.com [cacheUrl] => http://www.google.com/search?q=cache:Zcnr-K8jU4YJ:www.paintball.com [title] => PaintBall.com [titleNoFormatting] => PaintBall.com [content] => Information and meeting place for new and experienced players. Features industry news, equipment reviews, information for new players, links to online ... ) [1] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.zephyrpaintball.com/ [url] => http://www.zephyrpaintball.com/ [visibleUrl] => www.zephyrpaintball.com [cacheUrl] => http://www.google.com/search?q=cache:EkBfV3VsT9UJ:www.zephyrpaintball.com [title] => Cheap Paintball Guns - Cheap Paintball Gear - Cheap Paintball Supplies [titleNoFormatting] => Cheap Paintball Guns - Cheap Paintball Gear - Cheap Paintball Supplies [content] => Cheap Paintball Gear - Zephyr Paintball offers a wide variety of cheap paintball guns as well as cheap paintball supplies that can get you into the painball ... ) [2] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.addictinggames.com/paintballthegame.html [url] => http://www.addictinggames.com/paintballthegame.html [visibleUrl] => www.addictinggames.com [cacheUrl] => http://www.google.com/search?q=cache:TM1GFy3lDIQJ:www.addictinggames.com [title] => Paintball - The Game - Free Puzzle and Board Game from AddictingGames! [titleNoFormatting] => Paintball - The Game - Free Puzzle and Board Game from AddictingGames! [content] => Paintball - The Game, a Free Puzzle and Board Game from AddictingGames: Use your skills to paint a path for the ball to get to the magical square. ) [3] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.paintball-online.com/ [url] => http://www.paintball-online.com/ [visibleUrl] => www.paintball-online.com [cacheUrl] => http://www.google.com/search?q=cache:rm9AvRxLLX4J:www.paintball-online.com [title] => Paintball Guns & Markers at Paintball-Online.com [titleNoFormatting] => Paintball Guns & Markers at Paintball-Online.com [content] => The Internet's largest paintball store featuring over 4000 paintball guns, markers and other gear. Free shipping and 10% off for all VIP members. ) [4] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://en.wikipedia.org/wiki/Paintball [url] => http://en.wikipedia.org/wiki/Paintball [visibleUrl] => en.wikipedia.org [cacheUrl] => http://www.google.com/search?q=cache:h3rpb57aWfcJ:en.wikipedia.org [title] => Paintball - Wikipedia, the free encyclopedia [titleNoFormatting] => Paintball - Wikipedia, the free encyclopedia [content] => Paintball is a sport in which players compete, in teams or individually, to eliminate opponents by hitting them with capsules containing food coloring and ... ) [5] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.ansgear.com/ [url] => http://www.ansgear.com/ [visibleUrl] => www.ansgear.com [cacheUrl] => http://www.google.com/search?q=cache:uiYno-g6MOkJ:www.ansgear.com [title] => Paintball - Cheap Paintball Guns, Gear and Paintball Equipment [titleNoFormatting] => Paintball - Cheap Paintball Guns, Gear and Paintball Equipment [content] => Ansgear has Paintball guns and Paintball equipment for everyone. Get your Paintball equipment for cheap. All Paintball gear on sale! ) [6] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.pbreview.com/ [url] => http://www.pbreview.com/ [visibleUrl] => www.pbreview.com [cacheUrl] => http://www.google.com/search?q=cache:OzXP0G1QzFMJ:www.pbreview.com [title] => Paintball Reviews of Guns, Equipment, Games & More | pbreview.com [titleNoFormatting] => Paintball Reviews of Guns, Equipment, Games & More | pbreview.com [content] => All things paintball on pbreview.com. Paintball gun & equipment reviews, paintball videos, a paintball field locator for paintball games & tournaments. ) [7] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => Desired Output: Quote [content] => Cheap Paintball Gear - Zephyr Paintball offers a wide variety of cheap paintball guns as well as cheap paintball supplies that can get you into the painball ... [content] => Paintball - The Game, a Free Puzzle and Board Game from AddictingGames: Use your skills to paint a path for the ball to get to the magical square. ) .......................... Till the End of the Page... How can it be achieved? Cheers Natasha T why is this not working? <?php class registration{ public $email = $_POST["email"]; public $username = $_POST["username"]; public $password = $_POST["password"]; //var $username = $_POST["confirmPassword"]; function validateFields(){ echo $this->$email; echo $this->$username; echo $this->$password; //echo $this->$confirmPassword; } } registration->validateFields(); ?> Im getting error: Parse error: syntax error, unexpected T_VARIABLE on the first property declaration $email. Long story short, I have a class that does some data verification and session management. In order to do some of this verification, it needs a database connection. I am using the MDB2 class; here is a sample of the constructor's code: this is a snippet of code from My Class. // FUNCTIONS function __construct() { /* other code here */ // set up our datbase connection global $dsn; // must use global as to include the one *from* the settings.php include $mdb2 =& MDB2::singleton($dsn); if (PEAR::isError($mdb2)) { die("<H1> THERE WAS AN ERROR </H1>" . $mdb2->getMessage()); } echo("SESSION CLASS: if you see this, then we're goood!"); // some very crude debugging, please ignore this! } Now, i have another function within this same class: public static function data_validateUserName($safeUserName){ // build the query $q = "SELECT uName FROM Users WHERE username = '$safeUserName'"; $result = $this->$mdb2->query($q); if($result->numRows() >= 1){ // there is 1 or more hits for a username, it is not available! return false; } else if ($result->numRows() < 1){ // there is less than 1 row with that username, we're golden! return ture; } } Inside the constructor, i have correctly set up a MDB2 object. I was able to run some queries and other things on it *inside* the constructor. Because of this, i know that it's settings are correct and it is fully working. However, when i try to use that $mdb2 object inside this other method, i get all sorts of errors about that being a bad reference to an object that essentially does not exist. Now, i tried searching here, and didn't get much help, so apologies. If you've got a link to a similar question, then please post that with a brief explanation of what you searched for to get it... Also, the php.net manual is not very helpful about the scope of objects in this particular setup... so please know that i did pour over that before posting here. Thanks for your time, all. ***** EDIT ****** I've thought about doing it another way: Each function is passed in a reference to the MDB2 object as an argument instead of relying on the one that is *suposed to be* built in to the actual class it's self. Would this be better / more secure / more efficient?! Hey, I'm trying to create an object oriented webpage, with just some basic features, like creating a user, logging in, admin restricted pages. However I'm stuck at this point. This is my code: class_user.php Code: [Select] <?php include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/class_database.php"; ?> <?php class User { private $database; public function __construct(MySqlDatabase $database) { //Type Hinting $this->database = $database; } public function find_all() { $result = $this->database->db_query("SELECT * FROM users"); return $result; } public function find_by_id($id=1) { $result = $this->database->db_query("SELECT * FROM users WHERE id={$id}"); $final = mysqli_fetch_array($result); return $final; } } ?>class_database.php Code: [Select] <?php include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/values.php"; include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/class_user.php"; ?> <?php class MySqlDatabase extends MySQLi { function __construct() { //Check if constants are missing if (defined(!DB_USERNAME) || defined(!DB_SERVER) || defined(!DB_PASSWORD) || defined(!DB_NAME)) { die("One or more of the database constants are missing: " . mysqli_errno); } //Establish connection if constants are present using the parent class parent::__construct(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME); //Echo error message if connection has failed if ($this->connect_errno) { die("Database connection has failed: " . $this->connect_errno); } } public function db_query($sql) { $result = mysqli_query($this->connection, $sql); if (!$result) { die("Database query failed: " . $this->errno); } return $result; } public function query_prep($value) { $result = mysqli_real_escape_string($this->connection, $value); if (!$result) { die("Preparing query failed: " . $this->errno); } return $result; } } ?>Calling externally: Code: [Select] <?php $database = new MySqlDatabase(); $user = new User($database); $found = $user->find_all(); ?>This is the error I'm getting: Quote Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\includes\class_database.php on line 28 Database query failed: 0 I've tried everything I can come up with, but still I'm stuck at this error. 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 I can not understand why this isn't working, basically it works in one place but not the other I have this in my main class: class phpLive{ public function loadCore(){ foreach(glob($this->location."/core/*/*.core.php") as $coreFile){ $info = (object)pathinfo($coreFile); require_once $coreFile; $pos = strrpos($info->dirname, "/"); $coreMedia = substr($info->dirname, $pos + 1); $className = str_replace(".core", "", $info->filename); $instance = strtolower($className); $this->$coreMedia->$instance = new $className(); } } } On the page that I run (index.php), I use this: $_live->example->loadurl(); which is in a class that looks like this: <?php class ExampleClass extends phpLive{ public function __construct(){ $this->loadCore(); } public function loadurl(){ $this->net->http->getHttp('http://google.com'); } } ?> and I get the following error: Quote Notice: Undefined property: ExampleClass::$net in C:\wamp\www\phpLive\phpLive\plugins\Example\ExampleClass.inc.php on line 7 Notice: Trying to get property of non-object in C:\wamp\www\phpLive\phpLive\plugins\Example\ExampleClass.inc.php on line 7 Fatal error: Call to a member function getHttp() on a non-object in C:\wamp\www\phpLive\phpLive\plugins\Example\ExampleClass.inc.php on line 7 but, when I run this on the main page: $_live->net->http->getHttp("http://google.com"); The code works just fine. Why doesn't the first one work (the above is the actual code, copy and pasted from my editor)? I want to create an application for sending mails using PHPMailer by placing it on my website server (using SMTP), but I can not get object of class phpmailer to change its properties of: to_name to_email ContentType from default (i.e. null). Why are the properties keeping default values from the PHPMailer class, and not accepting my once, though I check values i get from DB and they are good. ContentType is set in a config file. Here is part of var_dump ($mailer); object of my extended class: object(MyMailer)#2 (56) { ["priority"]=> int(3) ["to_name"]=> NULL ["to_email"]=> NULL ... ["ContentType"]=> string(10) "text/plain"... also I get value of ["Port"]=> int(26) but ["SMTP_PORT"]=> int(25). I need to use smtp port 26. And here is the extended class of phpmailer require_once './PHPMailer/class.phpmailer.php'; require_once 'mailer-config.php'; class MyMailer extends PHPMailer { var $priority = 3; var $to_name = null; var $to_email = null; var $From = null; var $FromName = null; var $Sender = null; var $ContentType = null; function MyMailer() { global $eSlanje; // Comes from mailer-config.php $eSlanje array if($eSlanje['smtp_mode'] == 'enabled') { $this->Host = $eSlanje['smtp_host']; $this->Port = $eSlanje['smtp_port']; if($eSlanje['smtp_username'] != '') { $this->SMTPAuth = true; $this->Username = $eSlanje['smtp_username']; $this->Password = $eSlanje['smtp_password']; } $this->Mailer = "smtp"; } if(!$this->From) { $this->From = $eSlanje['from_email']; } if(!$this->FromName) { $this->FromName = $eSlanje['from_name']; } if(!$this->Sender) { $this->Sender = $eSlanje['from_email']; } $this->Priority = $this->priority; //echo "<br>eSlanje[content_type]"; //var_dump ($eSlanje['content_type']); $this->ContentType = $eSlanje['content_type']; } } and here is the cofig file: mailer-config.php <?php $eSlanje['from_email'] = "hi@mysite.com"; $eSlanje['from_name'] = "Joe Blog"; $eSlanje['title'] = "hi there"; $eSlanje['content_type'] ="text/html"; $eSlanje['smtp_username'] = null; $eSlanje['smtp_mode'] = "enabled"; $eSlanje['smtp_port'] = 26; $eSlanje['smtp_host'] = "mail.mysite.com"; Here is where I insert values of email and name into the object: <?php session_start(); include ("password.php"); require_once 'class_lib/MyMailer.php'; require "class_lib/MySQL_Database.php"; require "get_email_template.php"; $db = new MySQL_Database (); $id = isset($_GET['id']) ? $_GET['id'] : false; $sql = "select email,ime from ".TABLE." where id = $id"; $query = mysql_query ($sql); $toClient = mysql_fetch_array($query); $to = isset($toClient['email']) ? $toClient['email'] : false; var_dump($to); // here I get a valid email address $to_name = isset($toClient['ime']) ? $toClient['ime'] : false; //var_dump($to_name); // here I get a valid preson's name $mailer = new MyMailer(); $mailer->AddAddress($to, $to_name); $mailer->Body = get_htmlBody(); $mailer->AltBody = get_txtBody(); if(!$mailer->Send()) { echo "<br> Mailer Error: " . $mailer->ErrorInfo." "; } else { echo "<br>message not sent  "; } $mailer->ClearAddresses(); var_dump($mailer); // this is where the object trace comes from ?> Hi there, I am just wondering which way is the correct one if you want to create object properties/attribute dynamically at run time using magic method __set(), __get(), for example: class Foo{ public $data = array(); public function __set($name,$value){ $this->data[$name] = $value; } public function __get($name){ if ( isset($this->data[$name]) ){ return $this->data[$name]; } } } Or using the below way class Foo{ public function assign(array $data){ foreach($data as $key => $value){ $this->$key = $value; } } } I just encountered the second way in many places and I am totally confused . Is the __set() method called implicitly by the PHP engine in the second way or what? how come this is considered as a valid code ? your usual help is appreciated |