PHP - Best Way To Store Objects In A Database
What is the better way, in terms of best practice and also speed of storing PHP objects in a database? Is it:
Serialize Code: [Select] $SQL = "INSERT INTO my_table (my_object) VALUES ('" . seralize($php_object). "')"; OR JSON Code: [Select] $SQL = "INSERT INTO my_table (my_object) VALUES ('" . json_encode($php_object). "')"; Any idea which is faster serialize() / unserialize() or json_ecode() / json_decode()? Similar TutorialsHi I am trying to connect to my database but i am having some problems where the server( WAMP) crashes and does not load this page. here is the php coding
<?php $db = new PDO("mysql:host=localhost;dbname=test;port=80", "root", ""); var_dump($db);when i run this no error comes the page doesnt load. anyone know why? when using PDO do i have to do some sort of configuration changes to wamp? i have even changed the directory of the file and still same issue. any suggestions would be wonderful. I've been doing some research and I was wondering what the best way is to store IP addresses in a MySQL database, and what would be the field type and length? I've seen that you can use the inet_aton() function but supposedly this doesn't support IPv4. So is there a workaround using these functions? Alternatively, if I was to just store the IP address as it is, what type of field and length would I be looking at? I've read somewhere that 45 is the max? Anyone could help or giude how to secure this script by storing session into database?
login.php
<?php //Start session session_start(); //Include database connection details require_once('config.php'); //Get ip function get_client_ip() { $ipaddress = ''; if ($_SERVER['HTTP_CLIENT_IP']) $ipaddress = $_SERVER['HTTP_CLIENT_IP']; else if($_SERVER['HTTP_X_FORWARDED_FOR']) $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR']; else if($_SERVER['HTTP_X_FORWARDED']) $ipaddress = $_SERVER['HTTP_X_FORWARDED']; else if($_SERVER['HTTP_FORWARDED_FOR']) $ipaddress = $_SERVER['HTTP_FORWARDED_FOR']; else if($_SERVER['HTTP_FORWARDED']) $ipaddress = $_SERVER['HTTP_FORWARDED']; else if($_SERVER['REMOTE_ADDR']) $ipaddress = $_SERVER['REMOTE_ADDR']; else $ipaddress = 'UNKNOWN'; return $ipaddress; } //Array to store validation errors $errmsg_arr = array(); //Validation error flag $errflag = false; //Function to sanitize values received from the form. Prevents SQL injection function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } //Sanitize the POST values $login = clean($_POST['login']); $password = clean($_POST['password']); $ip = get_client_ip(); //Input Validations if($login == '') { $errmsg_arr[] = 'Login ID missing'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'Password missing'; $errflag = true; } /* if($login != '' || $password != '') { if($login !='admin' && $ip !=''.$log_ip.''){ $errmsg_arr[] = 'Your IP <b>'.$ip.'</b> is not recognized...'; $errflag = true; } } */ //If there are input validations, redirect back to the login form if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); //header("location: index.php"); echo ('<meta http-equiv="refresh" content="0;url=index.php">'); exit(); } //Create query $qry="SELECT * FROM members WHERE login='$login' AND passwd='".$_POST['password']."'"; $result=mysql_query($qry); //Check whether the query was successful or not if($result) { if(mysql_num_rows($result) == 1) { //Login Successful session_regenerate_id(); $member = mysql_fetch_assoc($result); $_SESSION['SESS_MEMBER_ID'] = $member['member_id']; $_SESSION['SESS_LOGIN_NAME'] = $member['login']; $_SESSION['SESS_PASS'] = $member['passwd']; session_write_close(); //header("location: member-index.php"); echo ('<meta http-equiv="refresh" content="0;url=member-index.php">'); exit(); }else { //Login failed //header("location: login-failed.php"); echo ('<meta http-equiv="refresh" content="0;url=login-failed.php">'); exit(); } }else { die("Query failed"); } ?>auth.php (included on top of all php pages <?php //Start session session_start(); //Check whether the session variable SESS_MEMBER_ID is present or not if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) { //header("location: access-denied.php"); echo ('<meta http-equiv="refresh" content="0;url=access-denied.php">'); exit(); } ?> Hey guys!, Any help is greatly appreciated! what i want to do is store a link to a pdf file which will open the file when clicked. just now when clicked will only open the file name but not with the extension .pdf? Thanks! How do I access objects inside an array of database results? I have a method that returns MySQL results as an array "$projects". Running print_r($projects) gives me this: array(1) ( "projects" => object Database_MySQL_Result(6) { protected _internal_row => integer 0 protected _query => string(875) "SELECT [skipping remainder of long query]" protected _result => resource(mysql result) protected _total_rows => integer 53 protected _current_row => integer 0 protected _as_object => string(13) "Model_Project" } ) If I do this: foreach($projects as $project) { echo $project->PROJECT_NAME; } I get "Undefined property: Database_MySQL_Result::$PROJECT_NAME" If I do this: foreach($projects as $project) { echo $project[0]; } the browser will display projects.id for the first returned row *only* echo $project[1] returns the project.id for the second row only. And so on. Each returned row contains over a dozen cells. It's almost as if I'm referring to the array incorrectly, or referring to the wrong array. I feel as though I'm making a very simple (and perhaps dumb) mistake here, but can't quite figure out what it is. Thanks. Hi! So I'm fairly new to PHP, and am currently making a website from scratch including as much PHP functionality as I can for learning purposes. As I have just finished making a blog function, I started to wonder. Is it normal to store every part of a website in a the database? The blog part of the website I just created has of course all the differet blog entries stored in a table in the db, but is it also normal practice to store about, contact etc. in tables too? Or should categories like these be created using brand new .php documents? I am in the progress of making a page controller and thought I should clearify things first, before I go any further. This question may seem stupid, but I don't know alot about what the normal practices of doing things like these in php are. Anyways, hope someone can help me out! Hi, I'm trying to store the first+lastname from my mysql user datababase into arrays like this: // Fill up array with names $a[]="Anna"; $a[]="Brittany"; $a[]="Cinderella"; $a[]="Diana"; $a[]="Eva"; $a[]="Fiona"; $a[]="Gunda"; $a[]="Hege"; $a[]="Inga"; $a[]="Johanna"; $a[]="Kitty"; $a[]="Linda"; $a[]="Nina"; $a[]="Ophelia"; $a[]="Petunia"; $a[]="Amanda"; $a[]="Raquel"; $a[]="Cindy"; $a[]="Doris"; $a[]="Eve"; $a[]="Evita"; $a[]="Sunniva"; $a[]="Tove"; $a[]="Unni"; $a[]="Violet"; Is there a recommended BEST PRACTICE for storing (and retrieving) telephone numbers from a database table? Is it best to store (in the USA) the area code separate from the rest of the number? Remove parenthesis and/or dashes? Or is there no reason to concern myself with performance or hacking issues regarding the storage of phone numbers as 323-555-1212 or (323)555-1212 inside my table? Hey, i need help storing an image in my database via the URL(image location) at the moment my php code is storing the image in a folder on the directory called upload. here is the code: <?php // Where the file is going to be placed $target_path = "upload /"; /* Add the original filename to our target path. Result is "uploads/filename.extension" */ $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); $target_path = "upload/"; $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { echo "The file ". basename $_FILES['uploadedfile']['name']). " has been uploaded"; } else{ echo "There was an error uploading the file, please try again!"; } ?> Click <a href="products.php">HERE</a> to go back to form if someone could help me i'd be very grateful Hi, my goal is to be able to create a web based interface for someone who has no programming skills or interest to be able to maintain a list of usernames and passwords for protecting a page of links on a website. so, I've created a page that can write to a database, and I can see that it is working, I can read entries, etc. now, I need to know how to make a script that will check against that database for valid UN/PW combinations. what is the best method for this? James Hi, I'm building a webshop and im stuck at the checkout. I'm using this Shopping Cart class http://www.webforcecart.com/manual.html The cart is stored as an object in $_SESSION[cart]. This method Code: [Select] print_r($cart->get_contents());would get this as output: Array ( => Array ( [id] => 7 [qty] => 1 [price] => 11.00 [info] => Test [subtotal] => 11 ) [1] => Array ( [id] => 6 [qty] => 2 [price] => 19.00 [info] => White 0 [subtotal] => 38 ) ) In the table Order I would like to store order-id customer-id total products total quantity total price date In the table Orderrow I would like to sto order-id, product-id, product-name, quantity, price, subtotal I know i can get the order-id with the function mysql_insert_id() but how can i store each product in the array with their info in the table Orderrow? Or is there a better way to do this? please advice me, thank you. Hi, I have this form which will create a checkbox list using data from my database and also determin if a checkbox had been checked before and check if it had. <form style="text-align:center" name="PrefRestaurant" id="PrefRestaurant" action="preferances_check.php" method="post"><table align="center"> <?php checkbox(id, name, restaurants, id); ?></table> <input type="submit" name="Prefer" id="Prefer" value="Επιλογή"/></form> function checkbox($intIdField, $strNameField, $strTableName, $strOrderField, $strMethod="asc") { $strQuery = "select $intIdField, $strNameField from $strTableName order by $strOrderField $strMethod"; $rsrcResult = mysql_query($strQuery); while ($arrayRow = mysql_fetch_assoc($rsrcResult)) { $testqry = "SELECT * FROM user_restaurant WHERE user_id = $_SESSION[UserId] AND restaurant_id = $arrayRow[id]"; $rsltestqry = mysql_query($testqry); $numrows = mysql_num_rows($rsltestqry); if ($numrows == 1) { echo "<tr align=\"left\"><td><input type=\"checkbox\" name=\"restaurant[]\" value=\"$arrayRow[id]\" checked/>$arrayRow[name]</td></tr>"; } else{ echo "<tr align=\"left\"><td><input type=\"checkbox\" name=\"restaurant[]\" value=\"$arrayRow[id]\" />$arrayRow[name]</td></tr>"; } } } Now the part which I can't get to work is when I'm trying to store the new values in my database. When I click the submit button I clear my database of any row that is related to the currently loggedin user and I want to store his new preferences (checked cheboxes). I've read that only the cheked checkboxes' values are POSTed so I did this (preferances_check.php) foreach($_POST['restaurant'] as $value) { $query="INSERT INTO user_restaurant VALUES ('$_SESSION[UserId]','$value')"; } But it is not working, nothing gets written in my table Could someone please enlighten me on this? Thnks! Hi Guys, I have been contacted by a client who wants me to develop an application which performs the following functionality: Lets say the domain name is xyz.com . We provide an email of our domain to the person who signup on our website for our services. Lets say the email that is given to the customer is email@xyz.com The client wants to built PHP application in which if an email is sent to email@xyz.com it gets downloaded and is stored in the MySql Database. After the download there is going to be a set of algorithms which will decided whether to forward this email to the client or not on his email address. I have no idea how to accomplish this functionality. Any suggestions would be appreciated. Thanks Sadan Masroor. I am building a project that requires I store query strings in a table (stage_reqs) which are called to determine permissions. These strings will look something like this: Code: [Select] select salesman from jobs where salesman is not NULL and job_id='".$this->job_id."' limit 1 The variable value needs to be determined from within the function it is being accessed in. Can I use eval to do this? Thanks, Chris Hello people, I have created an application in Code Charge where my site users can login and play games online.The game code is run via flash and html. The Game has 5 stages and from a page in my application called transfertogame.php , i transfer them to the game page. Now i want to be able to track each players progress via database so that when they log back in and they get to the transfertogame.php page, it can check the page they were on before and immediately take them to the page without starting from page 1. Any help will be appreciated as i am very poor with php scripting This is the session ID i guess is being used from my application page //Initialize Method @4-537EA73F function Initialize() { if(!$this->Visible) return; $this->ds->Parameters["sesUserID"] = CCGetSession("UserID"); } //End Initialize Method //Validate Method @4-7E1FC38C function Validate() { $Validation = true; $Where = ""; $this->CCSEventResult = CCGetEvent($this->CCSEvents, "OnValidate"); return (($this->Errors->Count() == 0) && $Validation); } //End Validate Method Unfortunately I have no code for this yet cuz I don;t even know if its possible... I am programming an application that is used by a couple of stores, which could end up being a lot of stores. Anyways, the basis is that the stores would, though a separate application (and therefore separate database) create a username and password, I now want to use this username and password to do the following 1. Allow them to login to my application using the same username and password 2. I want the store the username in a session to pull tables based on the username from my database For instance, a user has the login store123, after loggin in it now pulls the information from the tables store123_items, store123_prices, store123_settings, etc. Now my database will have quite a lot of store###_tables I am, sadly, a noobie to PHP and I do recall seeing an article (somewhere on the net, and I stupidly forgot to bookmark it, knowing I would need it eventually) on how to access multiple databases easily. Now because they are both under my account I can use the same username and password for both, its accessing the MySQL username/password database and storing the info I know I am lacking on how to do it. Any ideas? Say I have two functions that convert from Dollar to Cents and Cents to Dollar. function convertToDollar($value) { $amount = $value / 100; return $amount; } function convertToCents($value) { $amount = $value * 100; return $amount; } Currently I convert all the Dollar amounts to cents and store the cents in the mysql database column. When I showcase those amounts on a page, I simply convert the Cents back to Dollar. Am I doing this correctly or is there a better way to store product pricing in mysql table? Hello all!
I have this array of objects:
Array ( [0] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => p@yahoo.com [date] => 2014-09-21 07:23:12 [status] => 2 [approval_date] => 2014-09-21 07:31:10 [assessment_id] => 1 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-21 07:31:27 [mainmanger] => 3 ) [1] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => p@yahoo.com [date] => 2014-09-20 07:39:55 [status] => 2 [approval_date] => 2014-09-20 07:40:41 [assessment_id] => 3 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-20 07:41:07 [mainmanger] => 3 ) [2] => stdClass Object ( [first_name] => jimmy john john [last_name] => john [title] => Lorad and Master [id] => 32 [type] => 4 [manager] => 3 [email] => j@j.com [date] => 2014-09-21 07:38:50 [status] => 2 [approval_date] => 2014-09-19 07:39:25 [assessment_id] => 2 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-19 07:39:25 [mainmanger] => 0 ) )Where "id" = the user ID. If there are two or more entries for a user, I want to remove all but the most recent by the "approval_date",... So for the above example it would return: Array ( [0] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => piznac@yahoo.com [date] => 2014-09-21 07:23:12 [status] => 2 [approval_date] => 2014-09-21 07:31:10 [assessment_id] => 1 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-21 07:31:27 [mainmanger] => 3 ) [1] => stdClass Object ( [first_name] => jimmy john john [last_name] => john [title] => Lorad and Master [id] => 32 [type] => 4 [manager] => 3 [email] => j@j.com [date] => 2014-09-21 07:38:50 [status] => 2 [approval_date] => 2014-09-19 07:39:25 [assessment_id] => 2 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-19 07:39:25 [mainmanger] => 0 ) )I'm having a hard time wrapping my head around this concept, so I don't have any example code. And I don't really need or expect someone to code this for me,. just a push in the right direction would be awesome. I'm working on a Social Network from scratch. I'm stuck on how to store friend relationships between users? On one topic here, I found an idea. Have a table with 3 columns; id,user_1,user_2 each relationship would have a new row in the database. Would this be the best way to do this? I can imagine the table would get quite big. If each user has 100 friends and there's 10000 users that's 1000000 rows. etc Quote i need to store a variable from database like if i have "copies" in one of my column in my database then i have to store a particular value for copies store it to $copies here i want that i can store value of copies into $copies $update_book="update book set copies=copies-1 where bookid='$bookid'"; $result=mysql_query($update_book,$linkID1); if($result) { print "<html><body background=\"header.jpg\"> <p>book successfully subtracted from database</p></body></html>"; } else { print "<html><body background=\"header.jpg\"> <p>problem occured</p></body></html>"; } } |