PHP - Json_decode Return Instance Of Person Class
json_decode returns a stdClass Object.
Is there any way where I can get instance of my class instead of the same? I mean If I json_decode the below string then it will provide me instance of stdClass and not instance of Person class {"name":"a"} How to achieve the same? Thanks in advance CSJakharia Similar TutorialsI've been looking everywhere for a solution of this but I can't find one...
Basically what I did was created a class named USER.
public class USER{ private static $USER = array(); public function __construct($U='') { // if $U is not entered (=='') then set $U to MY USER ID ($_COOKIE['user']) // do a mysql query by the ID (ala $U) and store the results to self::$USER } public function ID() { return self::$USER['id']; } }This is the code I am running... I do a user profile page that shows different properties of the USER from the database: USERNAME(),ID(),PHONE(),EMAIL(), etc. etc. // creates an instance of a different user (other than myself) $PROFILE = new USER($ID); // $ID: 26 will retrieve USERNAME: Test // create an instance of user class for myself using the cookie holding my id $ME = new USER($_COOKIE['user']) // $_COOKIE['user']: 01 will retrieve USERNAME: Monster echo($PROFILE->USERNAME()); // displays Monster echo($PROFILE->ID()); // displays 01Any idea what I am doing wrong? I would assume that $PROFILE->USERNAME() would display Test and $ME->USERNAME() would show monster. I have an existing instance of my class Database, now I want to call that instance in my Session class, how would I go about doing this? Hi All
I have not really played around with PHP in ages so I am having a hard time trying to figure out the best way to proceed. Anyhow... what I need to get done is to take a singleton pattern core database class that has a extended driver based class (ie; the type of database server the connection is connecting to), and build a new class that dynamically handles as many driver based connections that are called using a single instance. As a side note, I tried PDO but it only supports a single driver per class instance, and then each of those connections cannot not have their on set of properties that relate to each connection. Anyway, I was thinking that the best way to handle all the driver specific connections, is to hand out a 'unique hash reference' that points to an array of connection objects and the object properties. then when the client runs any sql function they pass the 'unique hash reference' which the class then returns the object and it properties that will be used by the class to call up the driver specific sql function that was requested by the client. So what do you all thing about that....
TIA stephanieT
PS...
I reason i need this is because I need to update up 25 different databases based on data stored on all the databases and not all of the database servers are of the same type, (ie; MSSQL, Oracle, MySQL, MariaDB, berkeley DB, postgres, sqlite2,3, etc, etc)! Edited January 16, 2019 by StephanieTHey, I've not used PHP for a while and never really used classes! I was reading some code today and I saw a statement something like: Code: [Select] $s = &MyClass::("Something"); From reading the PHP Manual it has an example which looks like this for 5.3, however my server still uses 5.2 (.9), how do I do similar using that? Preferably something along these lines... Code: [Select] class spook{ function __construct($n){ if($n==1){ return "hello"; } else { return "goodbye"; } } } $a=spook::(); print $a; Cheers! i.e. What was the old method before the Scope resolution operator? Script:
<?php class Article{ public function fetch_all(){ global $pdo; $query = $pdo->prepare("SELECT * FROM `articles` ORDER BY `article_timestamp` DESC"); $query->execute(); return $query->fetchAll(); } public function fetch_data($article_id){ global $pdo; $query = $pdo->prepare("SELECT * FROM `articles` WHERE `article_id` = ?"); $query->bindValue(1, $article_id); $query->execute(); return $query->fetch(); } /* * These have gotten added later on. */ public function delete($id){ global $pdo; $query = $pdo->prepare("DELETE FROM `articles` WHERE `article_id` = ?"); $query->bindValue(1, $id); $query->execute(); // The "return" here. } public function edit_page($title, $content, $aticle_id){ global $pdo; $query = $pdo->prepare("UPDATE `articles` SET `article_title` = ?, `article_content` = ? WHERE `article_id` = ?"); $query->bindValue(1, $title); $query->bindValue(2, $content); $query->bindValue(3, $article_id); $query->execute(); // The "return" here. } } ?>I have this from a tutorial. In the function "fetch_all()" it uses "fetchAll()" at the spot where the "return" is, and in the function "fetch_data()" it uses "fetch()" at the spot where the "return" is. My Question: What may have to use for the function "delete()" and the function "edit_page()" at the spot where "return" would be? Edited by glassfish, 29 October 2014 - 12:32 PM. Hi I have a problem with the following: Code: [Select] <?php class ClassA { public $propertyClassName = "ClassB"; public function methodClassName() { return "ClassB"; } } class ClassB { public function bmethod() { echo "great!"; } } //works $a = new ClassA(); $b = new $a->propertyClassName(); $b->bmethod(); //doesn't work $a = new ClassA(); $b = new $a->methodClassName(); $b->bmethod(); ?> Of course I could do Code: [Select] <?php $a = new ClassA(); $className = $a->methodClassName(); $b = new $className; $b->bmethod(); ?>but isn't there a way to do this without saving the method's return to a variable? Thanks in advance flolam Hey guys, So im building a Content Management System for my A2 project in Computing, and i have a dataBase class. Now, i can return one thing, or do things like inserts however im having a problem returning a list of things such as: dataBase.class.php Code: [Select] public static function getNYCPost($table, $limit) { dataBase::_dbConnect(); if($limit == 0) { //debug: echo 'in as 0'; $data = mysql_query("SELECT id, linklabel FROM ".$table." WHERE showing='1' AND id >= 2"); } if($limit == 1) { //debug: echo 'in'; $data = mysql_query("SELECT id, linklabel FROM ". $table ." WHERE showing='1' AND id >= 2 ORDER BY id DESC LIMIT 5"); return $data; } } When i try to do this in the main code: index.php Code: [Select] <?php $list = dataBase::getNYCPost($pages,1); // echo $list; while ($row = mysql_fetch_array($list)) { $pageId = $row["id"]; $linklabel = $row["linklabel"]; $menuDisplay .= '<a href="index.php?pid=' . $pid . '">' . $linklabel . '</a><br />'; } echo $menuDisplay; ?> $list doesnt return anything, the previous method i used in the class was to make a list and an array and put the contents of the query in an array like: Code: [Select] list($list[] = $row); or something i cant quite remember i saw a youtube video tutorial and it worked for them, but it wasnt for me. If anyone knows how i can return various rows from a database it would be appreciated Thanks. All my code is returning is the username... Please help.
index.php
<?php include('user.class'); $user = new user("Jbonnett", "0", "Admin", "Jamie", "Bonnett", "jbonnett@site.co.uk", "01/09/1992"); echo "username: " . $user->getUsername() . "<br/>"; echo "id: " . $user->getId() . "<br/>"; echo "level: " . $user->getLevel() . "<br/>"; echo "Forename: " . $user->getForename() . "<br/>"; echo "Surname: " . $user->getSurname() . "<br/>"; echo "Email: " . $user->getEmail() . "<br/>"; echo "Dob: " . $user->getDob() . "<br/>"; ?>user.class <?php class user { private $username; private $id; private $level; private $forename; private $surname; private $email; private $dob; public function user($username, $id, $level, $forname, $surname, $email, $dob) { $this->setUsername($username); $this->setId($id); $this->setLevel($level); $this->setForename($forename); $this->setSurname($surname); $this->setEmail($email); $this->setDob($dob); } public function destroy() { unset($this->username); unset($this->id); unset($this->level); unset($this->forename); unset($this->surname); unset($this->uemail); unset($this->dob); } public function setUsername($username) { $this->username = $username; } public function getUsername() { return $this->username; } public function setId($id) { $this->id = $id; } public function getId() { return $this->$id; } public function setLevel($level) { $this->level = $level; } public function getLevel() { return $this->level; } public function setForename($forename) { $this->foreName = $forename; } public function getForename() { return $this->forename; } public function setSurname($surname) { $this->surName = $surname; } public function getSurname() { return $this->surname; } public function setEmail($email) { $this->email = $email; } public function getEmail() { return $this->email; } public function setDob($dob) { $this->dob = $dob; } public function getDob() { return $this->dob; } }; ?> { "data": [ { "name": "Social Media Manager", "category": "Local business", "id": "164691116879928" }, { "name": "Support! Muffin the fool (Oldham Chronicle FAKE)", "category": "Community", "id": "181377645219010" }, { "name": "Northplanet", "category": "Local business", "id": "132483460132622" }, { "name": "Social Media Manager", "category": "Application", "id": "102650199811234" }, { "name": "Top Ten Things To Remember Me By!", "category": "Application", "id": "375102030458" } ]} how would i use $user = json_decode($json) to access the value of the first id like $user->id(0); but that dose'tn work! This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=350103.0 php5 I am using json_encode() to store an array of data as a string in a mysql data base. I then extract the sting from the data base and convert the back into an array using json_decode. This works great up until I have any line breaks in any of the data. When there is a line break, the json_decode() function chokes and returns nothing. I would really like to keep the line breaks. Has anyone come across this issue/have an suggestions/solutions? Hi This non php person would sure appreciate some help. My site has a simple search box. Upon searching for a keyword, it returns listings which match 1 of 10 keywords included in that specific listing- skey. $query .= " and keywords like '%$skey%' and category like '%Mycategory%'"; I would like to also have the "bname" field checked for the specific keyword and included in the listings returned. Not knowing php at all, I tried this $query .= " and keywords like '%$skey%' or '%bname%' and category like '%Mycategory%'"; and $query .= " and keywords like '%$skey%' or '%$bname%' and category like '%Mycategory%'"; which did not work. A little help with correct code would be great. Tks, Larry I have a site where people vote, currently if two computers that are on the same network vote, my site will see them as one computer because I only track people by IP address. What would be a good way to track 2+ computers with the same IP address? This topic has been moved to PHP Freelancing. http://www.phpfreaks.com/forums/index.php?topic=330801.0 Hi I have created a table containing users. Now they can log in. and I want to use the username and display a welcome message. How do I display that? <H1> Welcome Ms <?php echo $myusername; ?> </H1> If I confused you then please let me know Hey I hope this is the right place to put this question.... I'm trying to make a social network(Just to test what i can do), and i wanted to make a feature so that u could check if a person is online or not. So the person could start a chat session with a user, i have no idea how u could make this. So i hope that there is some genius that will help me with this. Thank you - Nicolaj Hello everyone , I am new to php .. I am trying to make website that other people can order my books.So I saw video tutorial about making shopping cart and everything works , until part when other person need to send me information what ordered. With paypal it works , but in my country paypal is not available to use , so I want them to send me their details , and I will send them books . I made database , it works to get their details , but can't get hidden parts , product_id , product_id_array and cartTotal so I can know what they ordered , and how much they need to pay me .. How to "grab" what they ordered , they shopping cart when have products .. Thanks in advance for help )) cart.php codes Quote <?php session_start(); // Start session first thing in script // Script Error Reporting error_reporting(E_ALL); ini_set('display_errors', '1'); // Connect to the MySQL database include "storescripts/connect_to_mysql.php"; ?> <?php ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Section 1 (if user attempts to add something to the cart from the product page) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (isset($_POST['pid'])) { $pid = $_POST['pid']; $wasFound = false; $i = 0; // If the cart session variable is not set or cart array is empty if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) { // RUN IF THE CART IS EMPTY OR NOT SET $_SESSION["cart_array"] = array(0 => array("item_id" => $pid, "quantity" => 1)); } else { // RUN IF THE CART HAS AT LEAST ONE ITEM IN IT foreach ($_SESSION["cart_array"] as $each_item) { $i++; while (list($key, $value) = each($each_item)) { if ($key == "item_id" && $value == $pid) { // That item is in cart already so let's adjust its quantity using array_splice() array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $pid, "quantity" => $each_item['quantity'] + 1))); $wasFound = true; } // close if condition } // close while loop } // close foreach loop if ($wasFound == false) { array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" => 1)); } } header("location: cart.php"); exit(); } ?> <?php ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Section 2 (if user chooses to empty their shopping cart) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (isset($_GET['cmd']) && $_GET['cmd'] == "emptycart") { unset($_SESSION["cart_array"]); } ?> <?php ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Section 3 (if user chooses to adjust item quantity) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (isset($_POST['item_to_adjust']) && $_POST['item_to_adjust'] != "") { // execute some code $item_to_adjust = $_POST['item_to_adjust']; $quantity = $_POST['quantity']; $quantity = preg_replace('#[^0-9]#i', '', $quantity); // filter everything but numbers if ($quantity >= 100) { $quantity = 99; } if ($quantity < 1) { $quantity = 1; } if ($quantity == "") { $quantity = 1; } $i = 0; foreach ($_SESSION["cart_array"] as $each_item) { $i++; while (list($key, $value) = each($each_item)) { if ($key == "item_id" && $value == $item_to_adjust) { // That item is in cart already so let's adjust its quantity using array_splice() array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity))); } // close if condition } // close while loop } // close foreach loop } ?> <?php ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Section 4 (if user wants to remove an item from cart) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (isset($_POST['index_to_remove']) && $_POST['index_to_remove'] != "") { // Access the array and run code to remove that array index $key_to_remove = $_POST['index_to_remove']; if (count($_SESSION["cart_array"]) <= 1) { unset($_SESSION["cart_array"]); } else { unset($_SESSION["cart_array"]["$key_to_remove"]); sort($_SESSION["cart_array"]); } } ?> <?php ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Section 5 (render the cart for the user to view on the page) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// $cartOutput = ""; $cartTotal = ""; $pp_checkout_btn = ''; $product_id_array = ''; if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) { $cartOutput = "<h2 align='center'>Your shopping cart is empty</h2>"; } else { // Start PayPal Checkout Button $pp_checkout_btn .= '<form action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_cart"> <input type="hidden" name="upload" value="1"> <input type="hidden" name="business" value="">'; // Start the For Each loop $i = 0; foreach ($_SESSION["cart_array"] as $each_item) { $item_id = $each_item['item_id']; $sql = mysql_query("SELECT * FROM products WHERE id='$item_id' LIMIT 1"); while ($row = mysql_fetch_array($sql)) { $product_name = $row["product_name"]; $price = $row["price"]; $details = $row["details"]; } $pricetotal = $price * $each_item['quantity']; $cartTotal = $pricetotal + $cartTotal; setlocale(LC_MONETARY, "en_US"); $pricetotal = number_format ($pricetotal , $decimals = 0); // Dynamic Checkout Btn Assembly $x = $i + 1; $pp_checkout_btn .= '<input type="hidden" name="item_name_' . $x . '" value="' . $product_name . '"> <input type="hidden" name="amount_' . $x . '" value="' . $price . '"> <input type="hidden" name="quantity_' . $x . '" value="' . $each_item['quantity'] . '"> '; // Create the product array variable $product_id_array .= "$item_id-".$each_item['quantity'].","; // Dynamic table row assembly $cartOutput .= "<tr>"; $cartOutput .= '<td><a href="product.php?id=' . $item_id . '">' . $product_name . '</a><br /><img src="inventory_images/' . $item_id . '.jpg" alt="' . $product_name. '" width="40" height="52" border="1" /></td>'; $cartOutput .= '<td>' . $details . '</td>'; $cartOutput .= '<td>$' . $price . '</td>'; $cartOutput .= '<td><form action="cart.php" method="post"> <input name="quantity" type="text" value="' . $each_item['quantity'] . '" size="1" maxlength="2" /> <input name="adjustBtn' . $item_id . '" type="submit" value="change" /> <input name="item_to_adjust" type="hidden" value="' . $item_id . '" /> </form></td>'; //$cartOutput .= '<td>' . $each_item['quantity'] . '</td>'; $cartOutput .= '<td>' . $pricetotal . '</td>'; $cartOutput .= '<td><form action="cart.php" method="post"><input name="deleteBtn' . $item_id . '" type="submit" value="X" /><input name="index_to_remove" type="hidden" value="' . $i . '" /></form></td>'; $cartOutput .= '</tr>'; $i++; } setlocale(LC_MONETARY, "en_US"); $cartTotal = number_format ($cartTotal , $decimals = 0); $cartTotal = "<div style='font-size:18px; margin-top:12px;' align='right'>Cart Total : ".$cartTotal." USD</div>"; // Finish the Paypal Checkout Btn $pp_checkout_btn .= '<input type="hidden" name="custom" value="' . $product_id_array . '"> <input type="hidden" name="notify_url" value="http://mywebsite.com"> <input type="hidden" name="return" value="http://mywebsite.com"> <input type="hidden" name="rm" value="2"> <input type="hidden" name="cbt" value="Return to The Store"> <input type="hidden" name="cancel_return" value="http://mywebsite.com"> <input type="hidden" name="lc" value="US"> <input type="hidden" name="currency_code" value="USD"> <input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but01.gif" name="submit" alt="Make payments with PayPal - its fast, free and secure!"> </form>'; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Your Cart</title> <link rel="stylesheet" href="style/style.css" type="text/css" media="screen" /> </head> <body> <div align="center" id="mainWrapper"> <div id="pageContent"> <div style="margin:24px; text-align:left;"> <br /> <table width="100%" border="1" cellspacing="0" cellpadding="6"> <tr> <td width="18%" bgcolor="#C5DFFA"><strong>Product</strong></td> <td width="45%" bgcolor="#C5DFFA"><strong>Product Description</strong></td> <td width="10%" bgcolor="#C5DFFA"><strong>Unit Price</strong></td> <td width="9%" bgcolor="#C5DFFA"><strong>Quantity</strong></td> <td width="9%" bgcolor="#C5DFFA"><strong>Total</strong></td> <td width="9%" bgcolor="#C5DFFA"><strong>Remove</strong></td> </tr> <?php echo $cartOutput; ?> <!-- <tr> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> </tr> --> </table> <?php echo $cartTotal; ?> <br /> <br /> <form action="create.php" method="post"> <input type="hidden" name="inputid" value="<?php echo $id; ?>"> <br/> <input type="hidden" name="product_id" value="' . $product_id . '"> <br/> <input type="text" name="inputPayer_email" value="" /> <br/> <input type="text" name="inputFirst_name" value="" /> <br/> <input type="text" name="inputLast_name" value="" /> <br/> <input type="text" name="inputAddress_street" value="" /> <br/> <input type="text" name="inputAddress_city" value="" /> <br/> <input type="text" name="inputAddress_state" value="" /> <br/> <input type="hidden" name="custom" value="' . $product_id_array . '"> <br/> <input type="hidden" name="inputcartTotal" value="" /> <input type="submit" name="submit" /> </form> <?php echo $pp_checkout_btn; ?> <br /> <br /> <a href="cart.php?cmd=emptycart">Click Here to Empty Your Shopping Cart</a> </div> <br /> <a href="http://mywebsite.com">Home</a> <br/> <a href="http://mywebsite.com">Order</a> </div> <?php include_once("template_footer.php");?> </div> </body> </html> create.php codes Quote <?php $id = $_POST['inputid']; $product_id = $_POST['inputproduct_id']; $Payer_email = $_POST['inputPayer_email']; $First_name = $_POST['inputFirst_name']; $Last_name = $_POST['inputLast_name']; $Address_street = $_POST['inputAddress_street']; $Address_city = $_POST['inputAddress_city']; $Address_state = $_POST['inputAddress_state']; $product_id_array = $_POST['inputproduct_id_array']; $cartTotal = $_POST['inputcartTotal']; if(!$_POST['submit']) { echo "please fill out this form"; header('Location: index.php'); } else { mysql_query("INSERT INTO `transactions` ( `id` , `product_id` , `payer_email` , `first_name` , `last_name` , `address_street` , `address_city` , `address_state` , `product_id_array` , `cartTotal` ) VALUES (NULL , '$product_id', '$Payer_email', '$First_name', '$Last_name', '$Address_street', '$Address_city', '$Address_state', '$product_id_array', '$cartTotal')") or die(mysql_error()); echo "Added already"; header('Location: index.php'); } ?> order form codes Quote <form action="create.php" method="post"> <input type="hidden" name="inputid" value="<?php echo $id; ?>"> <br/> <input type="hidden" name="product_id" value="' . $product_id . '"> <br/> <input type="text" name="inputPayer_email" value="" /> <br/> <input type="text" name="inputFirst_name" value="" /> <br/> <input type="text" name="inputLast_name" value="" /> <br/> <input type="text" name="inputAddress_street" value="" /> <br/> <input type="text" name="inputAddress_city" value="" /> <br/> <input type="text" name="inputAddress_state" value="" /> <br/> <input type="hidden" name="custom" value="' . $product_id_array . '"> <br/> <input type="hidden" name="inputcartTotal" value="" /> <input type="submit" name="submit" /> </form> This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=352271.0 I need a php code to send an activation link to the user,and when the user clicks the link the account gets activated.
I am trying to implement this for two days now but stuck with logics ! Please help. |