PHP - Why Should Using $_post[] In A Class Create An Error ?
I'm new to OOP and straight out the gate Dreamweaver keeps giving me an error which I do not understand. I get that $_POST creates an array, however, in the procedural world I have always been able to assign a $variable to a $_POST. In fact if I remove the Class declaration the error goes away. What am am I missing ? - Many Thanks VJ :
Code: [Select] <?php class LookUp { $first_name = $_POST["f_name"]; $last_name = $_POST ["l_name"]; $company = $_POST["company"]; } ?> Similar TutorialsI 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 Hello all
i have this code
<?php $sql = "SELECT DISTINCT phonemodel FROM iphone ORDER BY phonemodel DESC LIMIT 4"; $rows = $conn->sqlExec($sql); $nr_row = $conn->num_rows; if($nr_row>=0) { $div_cls = (($nr_row % 2) == 0) ? 'linksmen' : 'linksmen_s'; foreach($rows as $row) { echo '<div class="'.$div_cls.'" title="'.$row['phonemodel'].'"><a href="iphone.php?phonemodel='.$row['phonemodel'].'"><img src="images/mark.png" alt="" /> '.$row['phonemodel'].'</a></div>'; } } ?>And looks like,the code take only firs class (linksmen) ,the condition else not working.did someone what is wrong. Thx 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 My error happens on line #81 I closed everything down last night and it was all fine, website was working as normal etc, but I've turned on the Xxamp server today and I am getting this error. Seems very random as nothing has changed since it was last on? Does anyone know how to sort this out and why I'm now getting this error? Thanks! Well I have a user profile page with codes written like this: Code: [Select] <?php $filename = "profile"; include("functions/functions.php"); include("functions/functions_users.php"); include("functions/functions_adopts.php"); include("functions/functions_friends.php"); include("inc/lang.php"); include("inc/bbcode.php"); //***************// // START SCRIPT // //***************// // This page handles user profiles and shows the site members... $user = $_GET["user"]; $page = $_GET["page"]; if($user != ""){ // We have specified a specific user who we are showing a profile for... // See if the user exists... $article_title = "{$user}'s Profile"; $query = "SELECT * FROM {$prefix}users, {$prefix}users_contacts, {$prefix}users_options, {$prefix}users_profile, {$prefix}users_status WHERE {$prefix}users.username = '{$user}' AND {$prefix}users_contacts.uid = {$prefix}users.uid AND {$prefix}users_options.uid = {$prefix}users.uid AND {$prefix}users_profile.uid = {$prefix}users.uid AND {$prefix}users_status.uid = {$prefix}users.uid AND {$prefix}users_contacts.username = {$prefix}users.username AND {$prefix}users_options.username = {$prefix}users.username AND {$prefix}users_profile.username = {$prefix}users.username AND {$prefix}users_status.username = {$prefix}users.username"; $result = runquery($query); $row = mysql_fetch_array($result); if($row['username'] == $user){ // First let's initiate tab system! include("inc/tabs.php"); include("css/tabs.css"); $article_content = "<div id='page-wrap'><div id='profile'> <ul class='nav'> <li class='nav0'><a href='#visitormessage'>Visitor Message</a></li> <li class='nav1'><a href='#aboutme' class='current'>About Me</a></li> <li class='nav2'><a href='#adopts'>Adoptables</a></li> <li class='nav3'><a href='#friends'>Friends</a></li> <li class='nav4 last'><a href='#contactinfo' class='last'>Contact Info</a></li> </ul><div class='list-wrap'>"; // Format user profile information... $id = $row['uid']; $ccstat = cancp($row['usergroup']); $website = (empty($row['website']))?"No Website Information Given":"<a href='{$row['website']}' target='_blank'>{$row['website']}</a>"; $facebook = (empty($row['facebook']))?"No Facebook Information Given":"<a href='{$row['facebook']}' target='_blank'>{$row['facebook']}</a>"; $twitter = (empty($row['twitter']))?"No Twitter Information Given":"<a href='{$row['twitter']}' target='_blank'>{$row['twitter']}</a>"; $msn = (empty($row['msn']))?"No MSN Information Given":$row['msn']; $aim = (empty($row['aim']))?"No AIM Information Given":$row['aim']; $yahoo = (empty($row['yahoo']))?"No YIM Information Given":$row['yahoo']; $skype = (empty($row['skype']))?"No YIM Information Given":$row['skype']; $row['username'] = ($ccstat == "yes")?"<img src='templates/icons/star.gif' /> {$row['username']}":$row['username']; $row['favpet'] = ($row['favpet'] == 0)?"None Selected":"<a href='http://www.{$domain}{$scriptpath}/levelup.php?id={$row['favpet']}' target='_blank'><img src='http://www.{$domain}{$scriptpath}/siggy.php?id={$row['favpet']}' border=0></a>"; // Here we go with the first tab content: Visitor Message $article_content .= "<ul id='visitormessage' class='hide'><strong><u>{$user}'s Profile Comments:</u></strong><br /><br /><table>"; $result = runquery("SELECT * FROM {$prefix}visitor_messages WHERE touser = '{$user}' ORDER BY vid DESC LIMIT 0, 10"); while($vmessage = mysql_fetch_array($result)){ $date = substr_replace($vmessage['datesent']," at ",10,1); $query2 = "SELECT * FROM {$prefix}users, {$prefix}users_profile WHERE {$prefix}users.username = '{$vmessage['fromuser']}' AND {$prefix}users_profile.uid = {$prefix}users.uid AND {$prefix}users_profile.username = {$prefix}users.username"; $result2 = runquery($query2); $sender = mysql_fetch_array($result2); $article_content .= "<tr> <td><img src='{$sender['avatar']}' width='40' height='40'></br></td> <td><a href='profile.php?user={$sender['username']}'>{$vmessage['fromuser']}</a> ({$date}) <a href='vmessage.php?act=view&user1={$user}&user2={$vmessage['fromuser']}'> <img src='templates/icons/status.gif'> </a> </br>{$vmessage['vmtext']} </br></td> <td><a href='vmessage.php?act=edit&vid={$vmessage['vid']}'> <img src='templates/icons/cog.gif'> </a> <a href='vmessage.php?act=delete&vid={$vmessage['vid']}'> <img src='templates/icons/delete.gif'> </a></br></td></tr>"; } if($isloggedin == "yes"){ if(isbanned($loggedinname) == 1){ $article_content .= "</table>It seems that you have been banned from this site and thus cannot send profile comment."; } else{ $article_content .= "</table> To Post a profile comment, please write your message in the text area below: <form action='profile.php?user={$user}' method='post'> <textarea rows='10' cols='50' name='vmtext' wrap='physical' ></textarea><br> <input type='submit' name='Submit' value='Submit'></form>"; $vmcontent = $_POST["vmtext"]; // Now check if the two users are friends... if($vmcontent != ""){ $datesent = date("Y-m-d H:i:s"); // $date = "2010-23-03 21:02:35"; $fromuser = $loggedinname; $touser = $user; runquery("INSERT INTO {$prefix}visitor_messages (vid, fromuser, touser, datesent, vmtext) VALUES ('', '$fromuser', '$touser' , '$datesent', '$vmcontent')"); $article_content .= "<p>Your comment for user has been posted. You may now view your conversation with {$user} from <a href='vmessage.php?act=view&user1={$fromuser}&user2={$touser}'>here</a>.</p>"; } } } else{ $article_content .= "</table>Guests cannot post profile comment, sorry..."; } // Now the second tab: About me... $article_content .= "</ul><ul id='aboutme'><li><strong><u>{$lang_basic_info} {$user}</u></strong><br /><br /> <img src='{$row['avatar']}' border=0 width='100' height=100 /><br /> <strong>Member Since:</strong> {$row['membersince']}<br /><br /> Gender: {$row['gender']}<br /> Favorite Color: {$row['color']}<br /> Nickname: {$row['nickname']}<br /> Bio: <br /> {$row['bio']}<br /></li>"; // The third tab: Adopts... $article_content .= "</ul><ul id='adopts' class='hide'><h2>.:AdoptSpotlight:.</h2><br /> {$row['favpet']}<br />{$row['about']}<br /><br /> <strong><u>{$user}'s Pets:</u></strong><br /><br />"; $query = "SELECT COUNT(*) AS pets FROM {$prefix}owned_adoptables WHERE owner = '{$user}'"; $result = runquery($query); $total = mysql_fetch_array($result); if($total['pets'] > 0){ $rowsperpage = 15; $totalpages = ceil($total['pets'] / $rowsperpage); if(is_numeric($page)) $currentpage = $page; else $currentpage = 1; if($currentpage > $totalpages) $currentpage = $totalpages; if($currentpage < 1) $currentpage = 1; $offset = ($currentpage - 1) * $rowsperpage; $query = "SELECT * FROM {$prefix}owned_adoptables WHERE owner = '{$user}' LIMIT {$offset}, {$rowsperpage}"; $result = runquery($query); while($row = mysql_fetch_array($result)){ $image = getcurrentimage($row['aid']); $article_content .= "<a href='levelup.php?id={$row['aid']}'><img src='{$image}' border='0' /></a>"; } $article_content .= "<br />"; if($currentpage > 1){ $newpage = $currentpage - 1; $article_content .= "<strong><a href='profile.php?user={$user}&page={$newpage}'><img src='templates/icons/prev.gif' border=0> Previous Page</a></strong> "; } else $article_content .= "<strong><img src='templates/icons/prev.gif' border=0> Previous Page</strong> "; if($currentpage < $totalpages){ $newpage = $currentpage + 1; $article_content .= " :: <strong><a href='profile.php?user={$user}&page={$newpage}'>Next Page <img src='templates/icons/next.gif' border=0></a></strong> "; } else $article_content .= " :: <strong>Next Page <img src='templates/icons/next.gif' border=0></strong>"; } else{ $article_content .= "This user currently does not have any pets."; } // The fourth tab: Friends... $friendlist = getfriendid($user); $friendnum = getfriendnum($user); $article_content .= "</ul><ul id='friends' class='hide'>{$user} currently have {$friendnum} friends.<br /><table>"; if($friendnum != 0){ foreach($friendlist as $friendid){ $query = "SELECT * FROM {$prefix}users, {$prefix}users_profile WHERE {$prefix}users.uid = '{$friendid}' AND {$prefix}users_profile.uid = {$prefix}users.uid AND {$prefix}users_profile.username = {$prefix}users.username"; $result = runquery($query) ; $friendinfo = mysql_fetch_array($result); $uid = $friendinfo['uid']; $username = $friendinfo['username']; $friendgender = getfriendgender($username); $onlinestatus = getonlinestatus($username); $article_content .= "<tr><td style='text-align: left'><img src='{$friendinfo['avatar']}' border=0 width='60' height =60></td> <td><strong><a href='profile.php?user={$username}'>{$username}</a></strong> {$friendgender}<br />{$friendinfo['nickname']}<br />{$onlinestatus} <a href='{$friendinfo['website']}' target='_blank'><img src='templates/icons/web.gif'></a> <a href='messages.php?act=newpm&user={$username}'><img src='templates/icons/title.gif'></a></td>"; $article_content .= ($user == $loggedinname)?"<td style='text-align: right'><br /><br /><br /><a href='friends.php?act=delete&uid={$uid}'>Break Friendship </td></tr>":"</tr>"; } } $article_content .= "</table>"; // The last tab: Contact Info! $article_content .= "</ul><ul id='contactinfo' class='hide'><img src='templates/icons/web.gif' /> {$website}<br /> <img src='templates/icons/facebook.gif' /> {$facebook}<br /> <img src='templates/icons/twitter.gif' /> {$twitter}<br /> <img src='templates/icons/aim.gif' /> {$aim}<br /> <img src='templates/icons/msn.gif' /> {$msn}<br /> <img src='templates/icons/yahoo.gif' /> {$yahoo}<br /> <img src='templates/icons/skype.gif' /> {$skype}<br /> <img src='templates/icons/title.gif' /> <a href='messages.php?act=newpm&user={$user}'>Send {$user} a Private Message</a><br /> <img src='templates/icons/fr.gif' /><a href='friends.php?act=request&uid={$id}'>Send {$user} a Friend Request</a><br /> <br /></div></div>"; } else{ $article_content .= "Sorry, but we could not find a user in the system with the name {$user}. Please make sure you have the username right. The user's account may also have been deleted by the system admin."; } } else{ // We did not specify a user, so show the memberlist $article_title = "Memberlist"; $article_content = "Here are all of the members of this site, sorted by registration date.<br /><br />"; include("classes/class_pagination.php"); include("css/pagination.css"); $query = "SELECT * FROM {$prefix}users ORDER BY uid ASC"; $result = runquery($query); $rowsperpage = 15; $pagination = new Pagination($query, $rowsperpage, "http://www.{$domain}{$scriptpath}/profile.php"); $pagination->setPage($_GET[page]); $query = "SELECT * FROM {$prefix}users ORDER BY uid ASC LIMIT {$pagination->getLimit()},{$rowsperpage}"; $result = runquery($query); while ($row = mysql_fetch_array($result)){ $status = cancp($row['usergroup']); $star = ($status == "yes")?"<img src='templates/icons/star.gif' border=0' /> ":""; $article_content .= "<strong><a href='profile.php?user={$row['username']}'>{$star}{$row['username']}</a></strong><br />"; } $article_content .= "<br />{$pagination->showPage()}"; } //***************// // OUTPUT PAGE // //***************// echo showpage($article_title, $article_content, $date); ?> In order to improve re-usability of the tabs, I attempted to create a file called class_tabs.php to make it object oriented. It did not work however, as the css is seriously messed up, and I have absolutely no idea why it did not. Here is the class file: Code: [Select] <?php class Tab{ private $t_num; private $t_name = array(); private $t_alias = array(); private $t_content; private $t_default; private $t_hide; private $t_index = array(); private $t_last = array(); public function __construct($num, $tabs, $default=1){ $this->t_num = $num; $this->t_default = $default; $i = 0; foreach ($tabs as $key => $val){ $this->t_name[$i] = $key; $this->t_alias[$i] = $val; $this->t_index[$i] = ($i == $default-1)?" class='current":""; $this->t_index[$i] = ($i == $num-1)?" class='last":$this->t_index[$i]; $this->t_last[$i] = ($i == $num-1)?" last":""; $i++; } } public function createtab(){ if($this->t_num < 2 or $this->t_num > 5) throw new Exception("The number of tabs must be restricted between 2 to 5!",272); $this->t_content = "<div id='page-wrap'><div id='tab'><ul class='nav'>"; for($i=0; $i<$this->t_num; $i++){ $this->t_content .= " <li class='nav{$i}{$this->t_last[$i]}'><a href='#{$this->t_alias[$i]}{$this->t_index[$i]}'>{$this->t_name[$i]}</a></li>"; } $this->t_content .= "</ul><div class='list-wrap'>"; return $this->t_content; } public function starttab($index){ $this->t_hide = ($index == $this->t_default)?"":" class='hide'"; $this->t_content .= "<ul id='{$this->t_alias}'{$this->t_hide}>"; return $this->t_content; } public function endtab($index){ $this->t_content .= "</ul>"; if($index == $this->t_num) $this->t_content .= "</div></div>"; return $this->t_content; } } ?> And this is the modified profile codes with OOP: Code: [Select] <?php $filename = "profile"; include("functions/functions.php"); include("functions/functions_users.php"); include("functions/functions_adopts.php"); include("functions/functions_friends.php"); include("inc/lang.php"); include("inc/bbcode.php"); //***************// // START SCRIPT // //***************// // This page handles user profiles and shows the site members... $user = $_GET["user"]; $page = $_GET["page"]; if($user != ""){ // We have specified a specific user who we are showing a profile for... // See if the user exists... $article_title = "{$user}'s Profile"; $query = "SELECT * FROM {$prefix}users, {$prefix}users_contacts, {$prefix}users_options, {$prefix}users_profile, {$prefix}users_status WHERE {$prefix}users.username = '{$user}' AND {$prefix}users_contacts.uid = {$prefix}users.uid AND {$prefix}users_options.uid = {$prefix}users.uid AND {$prefix}users_profile.uid = {$prefix}users.uid AND {$prefix}users_status.uid = {$prefix}users.uid AND {$prefix}users_contacts.username = {$prefix}users.username AND {$prefix}users_options.username = {$prefix}users.username AND {$prefix}users_profile.username = {$prefix}users.username AND {$prefix}users_status.username = {$prefix}users.username"; $result = runquery($query); $row = mysql_fetch_array($result); if($row['username'] == $user){ // First let's initiate tab system! include("inc/tabs.php"); include("css/tabs.css"); include("classes/class_tabs.css"); $profile_tabs = new Tabs(5, array("Visitor Message" => "visitormessage", "About Me" => "aboutme", "Adoptables" => "adopts", "Friends" => "friends", "Contact Info" => "contactinfo"), 2); $article_content = $profile_tabs -> createtab(); // Format user profile information... $id = $row['uid']; $ccstat = cancp($row['usergroup']); $website = (empty($row['website']))?"No Website Information Given":"<a href='{$row['website']}' target='_blank'>{$row['website']}</a>"; $facebook = (empty($row['facebook']))?"No Facebook Information Given":"<a href='{$row['facebook']}' target='_blank'>{$row['facebook']}</a>"; $twitter = (empty($row['twitter']))?"No Twitter Information Given":"<a href='{$row['twitter']}' target='_blank'>{$row['twitter']}</a>"; $msn = (empty($row['msn']))?"No MSN Information Given":$row['msn']; $aim = (empty($row['aim']))?"No AIM Information Given":$row['aim']; $yahoo = (empty($row['yahoo']))?"No YIM Information Given":$row['yahoo']; $skype = (empty($row['skype']))?"No YIM Information Given":$row['skype']; $row['username'] = ($ccstat == "yes")?"<img src='templates/icons/star.gif' /> {$row['username']}":$row['username']; $row['favpet'] = ($row['favpet'] == 0)?"None Selected":"<a href='http://www.{$domain}{$scriptpath}/levelup.php?id={$row['favpet']}' target='_blank'><img src='http://www.{$domain}{$scriptpath}/siggy.php?id={$row['favpet']}' border=0></a>"; // Here we go with the first tab content: Visitor Message $article_content .= "{$profile_tabs -> starttab(0)}<strong><u>{$user}'s Profile Comments:</u></strong><br /><br /><table>"; $result = runquery("SELECT * FROM {$prefix}visitor_messages WHERE touser = '{$user}' ORDER BY vid DESC LIMIT 0, 10"); while($vmessage = mysql_fetch_array($result)){ $date = substr_replace($vmessage['datesent']," at ",10,1); $query2 = "SELECT * FROM {$prefix}users, {$prefix}users_profile WHERE {$prefix}users.username = '{$vmessage['fromuser']}' AND {$prefix}users_profile.uid = {$prefix}users.uid AND {$prefix}users_profile.username = {$prefix}users.username"; $result2 = runquery($query2); $sender = mysql_fetch_array($result2); $article_content .= "<tr> <td><img src='{$sender['avatar']}' width='40' height='40'></br></td> <td><a href='profile.php?user={$sender['username']}'>{$vmessage['fromuser']}</a> ({$date}) <a href='vmessage.php?act=view&user1={$user}&user2={$vmessage['fromuser']}'> <img src='templates/icons/status.gif'> </a> </br>{$vmessage['vmtext']} </br></td> <td><a href='vmessage.php?act=edit&vid={$vmessage['vid']}'> <img src='templates/icons/cog.gif'> </a> <a href='vmessage.php?act=delete&vid={$vmessage['vid']}'> <img src='templates/icons/delete.gif'> </a></br></td></tr>"; } if($isloggedin == "yes"){ if(isbanned($loggedinname) == 1){ $article_content .= "</table>It seems that you have been banned from this site and thus cannot send profile comment."; } else{ $article_content .= "</table> To Post a profile comment, please write your message in the text area below: <form action='profile.php?user={$user}' method='post'> <textarea rows='10' cols='50' name='vmtext' wrap='physical' ></textarea><br> <input type='submit' name='Submit' value='Submit'></form>"; $vmcontent = $_POST["vmtext"]; // Now check if the two users are friends... if($vmcontent != ""){ $datesent = date("Y-m-d H:i:s"); // $date = "2010-23-03 21:02:35"; $fromuser = $loggedinname; $touser = $user; runquery("INSERT INTO {$prefix}visitor_messages (vid, fromuser, touser, datesent, vmtext) VALUES ('', '$fromuser', '$touser' , '$datesent', '$vmcontent')"); $article_content .= "<p>Your comment for user has been posted. You may now view your conversation with {$user} from <a href='vmessage.php?act=view&user1={$fromuser}&user2={$touser}'>here</a>.</p>"; } } } else{ $article_content .= "</table>Guests cannot post profile comment, sorry..."; } // Now the second tab: About me... $article_content .= "{$profile_tabs -> endtab(0)}{$profile_tabs -> starttab(1)} <li><strong><u>{$lang_basic_info} {$user}</u></strong><br /><br /> <img src='{$row['avatar']}' border=0 width='100' height=100 /><br /> <strong>Member Since:</strong> {$row['membersince']}<br /><br /> Gender: {$row['gender']}<br /> Favorite Color: {$row['color']}<br /> Nickname: {$row['nickname']}<br /> Bio: <br /> {$row['bio']}<br /></li>"; // The third tab: Adopts... $article_content .= {$profile_tabs -> endtab(1)}{$profile_tabs -> starttab(2)}<h2>.:AdoptSpotlight:.</h2><br /> {$row['favpet']}<br />{$row['about']}<br /><br /> <strong><u>{$user}'s Pets:</u></strong><br /><br />"; $query = "SELECT COUNT(*) AS pets FROM {$prefix}owned_adoptables WHERE owner = '{$user}'"; $result = runquery($query); $total = mysql_fetch_array($result); if($total['pets'] > 0){ $rowsperpage = 15; $totalpages = ceil($total['pets'] / $rowsperpage); if(is_numeric($page)) $currentpage = $page; else $currentpage = 1; if($currentpage > $totalpages) $currentpage = $totalpages; if($currentpage < 1) $currentpage = 1; $offset = ($currentpage - 1) * $rowsperpage; $query = "SELECT * FROM {$prefix}owned_adoptables WHERE owner = '{$user}' LIMIT {$offset}, {$rowsperpage}"; $result = runquery($query); while($row = mysql_fetch_array($result)){ $image = getcurrentimage($row['aid']); $article_content .= "<a href='levelup.php?id={$row['aid']}'><img src='{$image}' border='0' /></a>"; } $article_content .= "<br />"; if($currentpage > 1){ $newpage = $currentpage - 1; $article_content .= "<strong><a href='profile.php?user={$user}&page={$newpage}'><img src='templates/icons/prev.gif' border=0> Previous Page</a></strong> "; } else $article_content .= "<strong><img src='templates/icons/prev.gif' border=0> Previous Page</strong> "; if($currentpage < $totalpages){ $newpage = $currentpage + 1; $article_content .= " :: <strong><a href='profile.php?user={$user}&page={$newpage}'>Next Page <img src='templates/icons/next.gif' border=0></a></strong> "; } else $article_content .= " :: <strong>Next Page <img src='templates/icons/next.gif' border=0></strong>"; } else{ $article_content .= "This user currently does not have any pets."; } // The fourth tab: Friends... $friendlist = getfriendid($user); $friendnum = getfriendnum($user); $article_content .= "{$profile_tabs -> endtab(2)}{$profile_tabs -> starttab(3)}{$user} currently have {$friendnum} friends.<br /><table>"; if($friendnum != 0){ foreach($friendlist as $friendid){ $query = "SELECT * FROM {$prefix}users, {$prefix}users_profile WHERE {$prefix}users.uid = '{$friendid}' AND {$prefix}users_profile.uid = {$prefix}users.uid AND {$prefix}users_profile.username = {$prefix}users.username"; $result = runquery($query) ; $friendinfo = mysql_fetch_array($result); $uid = $friendinfo['uid']; $username = $friendinfo['username']; $friendgender = getfriendgender($username); $onlinestatus = getonlinestatus($username); $article_content .= "<tr><td style='text-align: left'><img src='{$friendinfo['avatar']}' border=0 width='60' height =60></td> <td><strong><a href='profile.php?user={$username}'>{$username}</a></strong> {$friendgender}<br />{$friendinfo['nickname']}<br />{$onlinestatus} <a href='{$friendinfo['website']}' target='_blank'><img src='templates/icons/web.gif'></a> <a href='messages.php?act=newpm&user={$username}'><img src='templates/icons/title.gif'></a></td>"; $article_content .= ($user == $loggedinname)?"<td style='text-align: right'><br /><br /><br /><a href='friends.php?act=delete&uid={$uid}'>Break Friendship </td></tr>":"</tr>"; } } $article_content .= "</table>"; // The last tab: Contact Info! $article_content .= "{$profile_tabs -> endtab(3)}{$profile_tabs -> starttab(4)}<img src='templates/icons/web.gif' /> {$website}<br /> <img src='templates/icons/facebook.gif' /> {$facebook}<br /> <img src='templates/icons/twitter.gif' /> {$twitter}<br /> <img src='templates/icons/aim.gif' /> {$aim}<br /> <img src='templates/icons/msn.gif' /> {$msn}<br /> <img src='templates/icons/yahoo.gif' /> {$yahoo}<br /> <img src='templates/icons/skype.gif' /> {$skype}<br /> <img src='templates/icons/title.gif' /> <a href='messages.php?act=newpm&user={$user}'>Send {$user} a Private Message</a><br /> <img src='templates/icons/fr.gif' /><a href='friends.php?act=request&uid={$id}'>Send {$user} a Friend Request</a><br /> <br />{$profile_tabs -> endtab(4)}"; } else{ $article_content .= "Sorry, but we could not find a user in the system with the name {$user}. Please make sure you have the username right. The user's account may also have been deleted by the system admin."; } } else{ // We did not specify a user, so show the memberlist $article_title = "Memberlist"; $article_content = "Here are all of the members of this site, sorted by registration date.<br /><br />"; include("classes/class_pagination.php"); include("css/pagination.css"); $query = "SELECT * FROM {$prefix}users ORDER BY uid ASC"; $result = runquery($query); $rowsperpage = 15; $pagination = new Pagination($query, $rowsperpage, "http://www.{$domain}{$scriptpath}/profile.php"); $pagination->setPage($_GET[page]); $query = "SELECT * FROM {$prefix}users ORDER BY uid ASC LIMIT {$pagination->getLimit()},{$rowsperpage}"; $result = runquery($query); while ($row = mysql_fetch_array($result)){ $status = cancp($row['usergroup']); $star = ($status == "yes")?"<img src='templates/icons/star.gif' border=0' /> ":""; $article_content .= "<strong><a href='profile.php?user={$row['username']}'>{$star}{$row['username']}</a></strong><br />"; } $article_content .= "<br />{$pagination->showPage()}"; } //***************// // OUTPUT PAGE // //***************// echo showpage($article_title, $article_content, $date); ?> Incase you find it necessary, the css/tabs.css and inc/tabs.php files are provided below. They should be irrelevant to this problem though, but just incase.. css/tabs.css Code: [Select] <style type="text/css"> * body { font: 12px Georgia, serif; } html { overflow-y: scroll; } a { text-decoration: none; } a:focus { outline: 0; } p { font-size: 15px; margin: 0 0 20px 0; } #page-wrap { width: 640px; margin: 30px;} h1 { font: bold 40px Sans-Serif; margin: 0 0 20px 0; } /* Generic Utility */ .hide { position: absolute; top: -9999px; left: -9999px; } /* Specific to example one */ #profile { background: #eee; padding: 10px; margin: 0 0 20px 0; -moz-box-shadow: 0 0 5px #666; -webkit-box-shadow: 0 0 5px #666; } #profile .nav { overflow: hidden; margin: 0 0 10px 0; } #profile .nav li { width: 97px; float: left; margin: 0 10px 0 0; } #profile .nav li.last { margin-right: 0; } #profile .nav li a { display: block; padding: 5px; background: #959290; color: white; font-size: 10px; text-align: center; border: 0; } #profile .nav li a:hover { background-color: #111; } #profile ul { list-style: none; } #profile ul li a { display: block; border-bottom: 1px solid #666; padding: 4px; color: #666; } #profile ul li a:hover { background: #fe4902; color: white; } #profile ul li:last-child a { border: none; } #profile ul li.nav0 a.current, #profile ul.visitormessage li a:hover { background-color: #0575f4; color: white; } #profile ul li.nav1 a.current, #profile ul.aboutme li a:hover { background-color: #d30000; color: white; } #profile ul li.nav2 a.current, #profile ul.adopts li a:hover { background-color: #8d01b0; color: white; } #profile ul li.nav3 a.current, #profile ul.friends li a:hover { background-color: #FE4902; color: white; } #profile ul li.nav4 a.current, #profile ul.contactinfo li a:hover { background-color: #Eac117; color: white; } </style> Code: [Select] <?php if($filename == "profile"){ ?> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script> <script src="js/tabs.js"></script> <script> $(function() { $("#profile").organicTabs(); }); </script> <? } ?> Please help... Hi, I've always used PHP code in my websites in a procedural manner as I come from a html/css background. Now that I want to do projects with more complexity I'm thinking I need to approach development in a more Object Oriented fashion. My question is more a theoretical one. I'm creating a User class and I'm not sure on what is the best practise for putting my functions etc. and where to call them. My project will have 2 different users (Admin & End User) so is it correct to say that the User class should encapsulate all the functions of both of these users ? By that I mean create/delete/modify user, login & change password/forgotten password functionality rather than having a seperate Login class Should I only call the database functions within these methods of the user class as opposed to calling them on the php page where the form data is posted ? For example, if a user logins in and when the form data is posted I currently open a connection, validate data, run the query. In an OO approach would I have just one User class method thats relevant to a particular page functionality ? Say, in pseudo code, for handling a login request loginRequest.php Code: [Select] include User class try { create new user User(); User::login(); } catch Exception() and should my User class look something like this class.User.php Code: [Select] include DBase class class User { var name, var email, var password, function validateInput (email, password) { if (!valid input) throw Exception else return true } function login (email, password){ try { database connection validateInput(); sql to see if user exists and login } catch Exception } } Apologies for this being a bit long winded! thanks tmfl Hey, i'd like to extract filenames from my database and present them as a downloadable zip-file to my users. I found a usefull function on http://davidwalsh.name/create-zip-php and thought i could work that out to my needs, but on this function itself (before using it), i get an error.. on the following line: if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) { i get: Parse error: syntax error, unexpected ')', expecting '(' i dont get it, dont think there is actually an error in the function.. does it mean that the php installed on the server i use, cant handle this function or anything? my phpinfo: http://dwarsfluit.davidvandiepen.nl/test.php the function is: Code: [Select] <?php /* creates a compressed zip file */ function create_zip($files = array(),$destination = '',$overwrite = false) { //if the zip file already exists and overwrite is false, return false if(file_exists($destination) && !$overwrite) { return false; } //vars $valid_files = array(); //if files were passed in... if(is_array($files)) { //cycle through each file foreach($files as $file) { //make sure the file exists if(file_exists($file)) { $valid_files[] = $file; } } } //if we have good files... if(count($valid_files)) { //create the archive $zip = new ZipArchive(); if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) { return false; } //add the files foreach($valid_files as $file) { $zip->addFile($file,$file); } //debug //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status; //close the zip -- done! $zip->close(); //check to make sure the file exists return file_exists($destination); } else { return false; } }?> thanks for helping! Hi All I am building a website and I basically want to be able to log my own Error Logging. This could be anything from a usual PHP Notice, An SQL Query failing, a 404 page or a user reaching an activity they should not have (For example, hitting a default: on a switch when they shouldn't have) I have 3 options that I can think off 1) MySQL 2) Email 3) File Write All have pros and cons MySQL - Pro - I can build an admin script to read the errors and display them for me to handle and mark when completed. MySQL - CON - What is the Queries fail for what ever reason (too many connections), then the query to log the error would also fail, thus I would never know Email: PRO - Should always work, I will know straight away Email: CON - Getting the data from an email to a user friendly screen, instead of clogging up my email box File Write - PRO - I can put the data into MySQL at any point, Should near enough always work File Write - CON - Other people could possibly see the the errors, which could give away directories or weaknesses in the web project. Does anyone have any suggestions? Hi, After a long time I start php again to do some stuff and using OOP concept for the first time and getting this below error Code: [Select] PHP Fatal error: Class 'SystemConfig' not found in /home/tanveer/Workspace/EmailTest/webapp/classes/MailParser.class.php on line 12, referer: http://localhost/EmailTest/public_html/index.php My project directory structure is as follows: Code: [Select] \webapp: |- classes |- MailParser.class.php |-DatabaseConnect.class.php |-SystemConfig.class.php \public_html: |-header.php |-footer.php |-gencsv.php |-stat.php \css |-style.css \images index.php And the php code file that I am trying to make work is as follows: class MailParser extends SystemConfig { /* Reads the files passed line-by-line * @param $fileName */ public function readFiles($fileName){ $fileHandler = fopen($fileName,'r'); while ($line = fgets($fileHandler)) { echo $line."<br />"; } fclose($fileHandler); } /* Traverse the user specified directory * @param $dirPath */ public function traverseDirectory($dirPath) { echo $dirPath; $sentFolderPath = new SystemConfig(); $sentFolderPath->getSentMailFolder(); $totalDirPath = $dirPath."/".$sentFolderPath; echo $totalDirPath; $io=0; if ($handle = @opendir($dirPath)) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $newdir = ""; $filetext = ""; if (!is_file($dirPath."/".$file) or is_dir($dirPath) ) { $io++; $newdir.= $dirPath."/".$file."/"; print $newdir."<br />"; $this->traverseDirectory($newdir); if(is_file($dirPath.$file)) { $text = str_replace('//','/',"".$dirPath.$file."\n"); } } } } closedir($handle); } } } $rmf = new MailParser(); $rmf->traverseDirectory($_POST["dirpath"]); ?> All, I'm getting the following error when I work with a class: Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /webspace/httpdocs/offers/form_key.php on line 5 The complete code for this is class is: <?php class Form_Key { protected $oldKey; public function __construct() { // Ensure we have an available session if ( NULL == session_id() ) { session_start(); } // Grab our former key for validation if ( isset( $_SESSION['form_key'] ) ) { $this->oldKey = $_SESSION['form_key']; } // Assign the new key $_SESSION['form_key'] = md5( uniqid( mt_rand(), TRUE ) ); } public function isValid() { return 'POST' == $_SERVER['REQUEST_METHOD'] && isset( $_POST['form_key'] ) && '' != trim( $_POST['form_key'] ) && '' != trim( $this->oldKey ) && $_POST['form_key'] === $this->oldKey; } public function getKey() { return $_SESSION['form_key']; } public function getOldKey() { return $this->oldKey; } public function render() { return '<input type="hidden" name="form_key" value="' . $_SESSION['form_key'] . '" />'; } public function __toString() { return $this->render(); } } ?> The line that is giving the issue is this line: protected $oldKey; Is it ok just to remove this line?? If I comment it out it gives me the same message but for line 7, which is this one: public function __construct() Anyone have any ideas? Thanks in advance. hey guys im having an error whilst trying to return an object registered in my registry class. Quote Notice: Trying to get property of non-object in C:\www\private\application\models\league_model.class.php on line 10 the object in trying to get is a config document reader which should return things such as database details and setting of the website. if someone could help me please that would be excellent...i hope you understand Index - where the resigtry is made Code: [Select] $config_root = 'config' . DS . 'config.ini'; $document = new Document; $config = $document->read($config_root); $registry = new Registry(); $registry->config = $config; Model - where the config is called but returns an error Code: [Select] $config = Registry::get_instance()->config; echo $config->db_username; Registry class Code: [Select] <?php class Registry { static protected $_instance = null; protected $_objects = array(); static public function get_instance() { if (self::$_instance == null) { self::$_instance = new self(); } return self::$_instance; } public function __set($key, $object) { $this->_objects[$key] = $object; } public function __get($key) { if (isset($this->_objects[$key])) { return $this->_objects[$key]; } return NULL; } } ?> return of the instant $this->_objects within the Registry class Code: [Select] Array ( [config] => Document Object ( [_values:protected] => Array ( [developement_enviroment] => true [db_type] => mysql [db_host] => localhost [db_username] => root [db_password] => password [db_database_name] => test [default_controller] => news [default_action] => articles [autoloader_ignore_directories] => Array ( [0] => .buildpath [1] => .project [2] => .settings [3] => . [4] => .. [5] => tmp [6] => views [7] => public [8] => scripts [9] => .htaccess ) ) ) } ) here's the class im using Code: [Select] <?php # Name: Database.singleton.php # File Description: MySQL Singleton Class to allow easy and clean access to common mysql commands # Author: ricocheting # Web: http://www.ricocheting.com/ # Update: 2010-07-19 # Version: 3.1.4 # Copyright 2003 ricocheting.com /* This program is free softwa you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ //require("config.inc.php"); //$db = Database::obtain(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); //$db = Database::obtain(); ################################################################################################### ################################################################################################### ################################################################################################### class Database{ // debug flag for showing error messages public $debug = true; // Store the single instance of Database private static $instance; private $server = ""; //database server private $user = ""; //database login name private $pass = ""; //database login password private $database = ""; //database name private $error = ""; ####################### //number of rows affected by SQL query public $affected_rows = 0; private $link_id = 0; private $query_id = 0; #-############################################# # desc: constructor private function __construct($server=null, $user=null, $pass=null, $database=null){ // error catching if not passed in if($server==null || $user==null || $database==null){ $this->oops("Database information must be passed in when the object is first created."); } $this->server=$server; $this->user=$user; $this->pass=$pass; $this->database=$database; }#-#constructor() #-############################################# # desc: singleton declaration public static function obtain($server=null, $user=null, $pass=null, $database=null){ if (!self::$instance){ self::$instance = new Database($server, $user, $pass, $database); } return self::$instance; }#-#obtain() #-############################################# # desc: connect and select database using vars above # Param: $new_link can force connect() to open a new link, even if mysql_connect() was called before with the same parameters public function connect($new_link=false){ $this->link_id=@mysql_connect($this->server,$this->user,$this->pass,$new_link); if (!$this->link_id){//open failed $this->oops("Could not connect to server: <b>$this->server</b>."); } if(!@mysql_select_db($this->database, $this->link_id)){//no database $this->oops("Could not open database: <b>$this->database</b>."); } // unset the data so it can't be dumped $this->server=''; $this->user=''; $this->pass=''; $this->database=''; }#-#connect() #-############################################# # desc: close the connection public function close(){ if(!@mysql_close($this->link_id)){ $this->oops("Connection close failed."); } }#-#close() #-############################################# # Desc: escapes characters to be mysql ready # Param: string # returns: string public function escape($string){ if(get_magic_quotes_runtime()) $string = stripslashes($string); return @mysql_real_escape_string($string,$this->link_id); }#-#escape() #-############################################# # Desc: executes SQL query to an open connection # Param: (MySQL query) to execute # returns: (query_id) for fetching results etc public function query($sql){ // do query $this->query_id = @mysql_query($sql, $this->link_id); if (!$this->query_id){ $this->oops("<b>MySQL Query fail:</b> $sql"); return 0; } $this->affected_rows = @mysql_affected_rows($this->link_id); return $this->query_id; }#-#query() #-############################################# # desc: does a query, fetches the first row only, frees resultset # param: (MySQL query) the query to run on server # returns: array of fetched results public function query_first($query_string){ $query_id = $this->query($query_string); $out = $this->fetch($query_id); $this->free_result($query_id); return $out; }#-#query_first() #-############################################# # desc: fetches and returns results one line at a time # param: query_id for mysql run. if none specified, last used # return: (array) fetched record(s) public function fetch($query_id=-1){ // retrieve row if ($query_id!=-1){ $this->query_id=$query_id; } if (isset($this->query_id)){ $record = @mysql_fetch_assoc($this->query_id); }else{ $this->oops("Invalid query_id: <b>$this->query_id</b>. Records could not be fetched."); } return $record; }#-#fetch() #-############################################# # desc: returns all the results (not one row) # param: (MySQL query) the query to run on server # returns: assoc array of ALL fetched results public function fetch_array($sql){ $query_id = $this->query($sql); $out = array(); while ($row = $this->fetch($query_id)){ $out[] = $row; } $this->free_result($query_id); return $out; }#-#fetch_array() #-############################################# # desc: does an update query with an array # param: table, assoc array with data (not escaped), where condition (optional. if none given, all records updated) # returns: (query_id) for fetching results etc public function update($table, $data, $where='1'){ $q="UPDATE `$table` SET "; foreach($data as $key=>$val){ if(strtolower($val)=='null') $q.= "`$key` = NULL, "; elseif(strtolower($val)=='now()') $q.= "`$key` = NOW(), "; elseif(preg_match("/^increment\((\-?\d+)\)$/i",$val,$m)) $q.= "`$key` = `$key` + $m[1], "; else $q.= "`$key`='".$this->escape($val)."', "; } $q = rtrim($q, ', ') . ' WHERE '.$where.';'; return $this->query($q); }#-#update() #-############################################# # desc: does an insert query with an array # param: table, assoc array with data (not escaped) # returns: id of inserted record, false if error public function insert($table, $data){ $q="INSERT INTO `$table` "; $v=''; $n=''; foreach($data as $key=>$val){ $n.="`$key`, "; if(strtolower($val)=='null') $v.="NULL, "; elseif(strtolower($val)=='now()') $v.="NOW(), "; else $v.= "'".$this->escape($val)."', "; } $q .= "(". rtrim($n, ', ') .") VALUES (". rtrim($v, ', ') .");"; if($this->query($q)){ return mysql_insert_id($this->link_id); } else return false; }#-#insert() #-############################################# # desc: frees the resultset # param: query_id for mysql run. if none specified, last used private function free_result($query_id=-1){ if ($query_id!=-1){ $this->query_id=$query_id; } if($this->query_id!=0 && !@mysql_free_result($this->query_id)){ $this->oops("Result ID: <b>$this->query_id</b> could not be freed."); } }#-#free_result() #-############################################# # desc: throw an error message # param: [optional] any custom error to display private function oops($msg=''){ if(!empty($this->link_id)){ $this->error = mysql_error($this->link_id); } else{ $this->error = mysql_error(); $msg="<b>WARNING:</b> No link_id found. Likely not be connected to database.<br />$msg"; } // if no debug, done here if(!$this->debug) return; ?> <table align="center" border="1" cellspacing="0" style="background:white;color:black;width:80%;"> <tr><th colspan=2>Database Error</th></tr> <tr><td align="right" valign="top">Message:</td><td><?php echo $msg; ?></td></tr> <?php if(!empty($this->error)) echo '<tr><td align="right" valign="top" nowrap>MySQL Error:</td><td>'.$this->error.'</td></tr>'; ?> <tr><td align="right">Date:</td><td><?php echo date("l, F j, Y \a\\t g:i:s A"); ?></td></tr> <?php if(!empty($_SERVER['REQUEST_URI'])) echo '<tr><td align="right">Script:</td><td><a href="'.$_SERVER['REQUEST_URI'].'">'.$_SERVER['REQUEST_URI'].'</a></td></tr>'; ?> <?php if(!empty($_SERVER['HTTP_REFERER'])) echo '<tr><td align="right">Referer:</td><td><a href="'.$_SERVER['HTTP_REFERER'].'">'.$_SERVER['HTTP_REFERER'].'</a></td></tr>'; ?> </table> <?php }#-#oops() }//CLASS Database ################################################################################################### ?> here's what im trying to do. Code: [Select] $sql="SELECT * FROM rpg_announcements ORDER BY id desc"; $result = $db->query($sql); $row = $db->fetch_array($result); echo $row[1]; here's my error: Database Error Message: MySQL Query fail: Resource id #7 Notice: Undefined offset: 1 What am i doing wrong? Hi all.
Just seeing this error now.
funny enough the site have been live for about a week only to bring this error now!
Fatal error: Class 'PDO' not found in /home/mysite/public_html/includes/file.php on line 21
and this is the file.php
$database='mydb'; $user='username'; $password='password'; $dsn="mysql:host=localhost;dbname=$database"; try { $pdo = new PDO($dsn,$user,$password); // mysql } catch(PDOException $e) { die ('Failed to connect'); // Exit, displaying an error message }i just saw this today and it's on godaddy thanks Alright guys got a but of a issue here, i keep geting a 'Call to class error undefined $obj' and i cant seem to see the problem. my class Code: [Select] <?php class DatabaseInsert { function ArticleInsert($table,$fields,$values) { $values_imploded = implode("','",$values); $fields_imploded = implode(",",$fields); $i = "INSERT INTO $table ($fields_imploded) VALUES ($values_imploded)"; mysql_query($i) or die( "<br>Query string: <br>Produced error: " . mysql_error() );; //$table,$fields,$values } } ?> The call Code: [Select] if(isset($_POST['sub'])) { include("../scrips/php/cms/database.insert.class.php"); $table = "blog_posts"; $title = "'".$_POST['ArticleTitle']."'"; $img = "'2'"; $post = "'".$_POST['ArticleBody']."'"; $aurthor_id = "'1'"; $category_id = "'4'"; $date_posted = "NOW()"; $values = array("$title","$img","$post","$aurthor_id","$category_id","$date_posted"); $fields = array('title','img','post','aurthor_id','category_id','date_posted'); //echo $values['0']."<br/>".$fields['0']; echo $values['0']."<br/>".$values['1']."<br/>".$values['2']."<br/>".$values['3']."<br/>".$values['4']."<br/>".$values['5']; $obj->ArticleInsert($table,$fields,$values); I wanted to inherit child classes from parent class. But it gives error like this: Fatal error: Cannot redeclare class Ch2_Product in C:\wamp\www\OOPhpSolutions\Ch_02\Product.php on line 3 I have file like this: Product.php Quote <?php class Ch2_Product { protected $_title; protected $_type; public function __construct($title, $type) { $this->_title = $title; $this->_type = $type; } public function getTitle() { return $this->_title; } public function getType() { return $this->_type; } } ?> Next I've inherited like this: Book.php Quote <?php require 'Product.php'; class Ch2_Book extends Ch2_Product { //defining functions } ?> And DVD.php Quote <?php require 'Product.php'; class Ch2_DVD extends Ch2_Product { // } ?> Finally I tried to catch the child class values like this in Ch_Book.php Quote <?php require_once 'Book.php'; require_once 'DVD.php'; $product1 = new Ch2_Book('Old Man and the Sea', 'Novel'); $product2 = new Ch2_DVD('Gone With the Wind', 'Movie'); echo $product1->getTitle(); echo $product1->getType(); echo $product2->getTitle(); echo $product2->getType(); ?> But it gave that error. Can anyone solve this? This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=357348.0 hello, i am hoping someone can help, been working on my own mvc with help from tutorials, but i am stuck with this error: Fatal error: Class 'services' not found in C:\xampp\htdocs\Workspace\Cyberglide\libs\Bootstrap.php on line 27 were it says services that changes when i type a different item in the url, loads the error page but says that at the bottom of the page. hoping someone can help me where i gone wrong: Code: [Select] <?php class Bootstrap { function __construct() { $url = isset($_GET['url']) ? $_GET['url'] : null; $url = rtrim($url, '/'); $url = explode('/', $url); //print_r($url); if (empty($url[0])) { require 'controllers/index.php'; $controller = new Index(); $controller->index(); return false; } $file = 'controllers/' . $url[0] . '.php'; if (file_exists($file)) { require $file; } else { $this->error(); } $controller = new $url[0]; $controller->loadModel($url[0]); // calling methods if (isset($url[2])) { if (method_exists($controller, $url[1])) { $controller->{$url[1]}($url[2]); } else { $this->error(); } } else { if (isset($url[1])) { if (method_exists($controller, $url[1])) { $controller->{$url[1]}(); } else { $this->error(); } } else { $controller->index(); } } } function error() { require 'controllers/error.php'; $controller = new Error(); $controller->index(); return false; } hope someone can help, many thanks guys. 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. This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=315284.0 |