Hi Bob,
I actually have several tables with relatioships. The thing is that i wanted to know if it was a bad idea/practice to store the data as json/serialized. (It seems so simple to code it)
thanks for your answer.
Hi Bob,
I actually have several tables with relatioships. The thing is that i wanted to know if it was a bad idea/practice to store the data as json/serialized. (It seems so simple to code it)
thanks for your answer.
thanks diafol. that is how is have it....User, Events, Events_countries and Countries tables. But after saying someone storing json i kind of wanted to go the same way...It will save me so much coding..
I have a table that will have several fields, such as counties, age_groups, gender, sports, etc..
on countries I will be storing data with this format["US","CA","DK","FI","RU","SE"]
on age groups I will be storing data with this format["2000","1999","1998"]
on age groups I will be storing data with this format["M","F"]
on age groups I will be storing data with this format["soccer","hockey", "tennis"]
Is it a bad idea/practice so store serialized/json_encoded data on mysql?
Hello!
I have a table called Events and one of the colums is called "country". I want to be able to query events based on the user country. So eventID #1 might have "country" = US, CA, MX (multiple values), so if a user is from the US logs-in will see the eventID 1 , but also if a user from CA logs-in will see the same event.
I created a <select name=country[] multiple> with a list of countries. I would like to be able to select several countries and save them in a colum. I tested json_encode and serialize and it like better json_encode but I was wonderig what's your view?
so on my form i have someeting like this....
<select name="country[]" size="10" multiple>
<?php foreach ($countries as $key => $val) { ?>
<option value="<?=$key?>" <?php if (in_array($key, json_decode($event->country))) { echo 'selected'; } ?>><?=$val?></option>
<?php } ?>
</select>
my controller looks like this:
function save($id)
{
$event = Event::find($id);
$event->country = json_encode($input['country']);
$event->save();
}
my query looks like this
function getEvents() {
return 'Select * From events where country IN ($user->country) ';
}
Hello. I am trying to implement a Laravel API that will be consumed by different clients (domains). The API basically, sends json response to the clients. For instance, when the client app.anyclient.com sends a AJAX/post request to api.myapi.com/login …the API is able to validate and login the user; however, the session will not persist. So if I want to check if the session still active I always get a false response, as if the session was never imitated. The interesting thing is that if I send the same request from the same domain, I am able to get the true response.
I was wondering how you guys do it. I am not sure if this is a Laravel issue or just me not understanding how CORS works…any recommendations?
Hello,
I am trying to populate the state drop-down based on the country selection. I creates this jQuery scrip that WORKS in firefox, chrome and mobile but for some reason does not work in IE8 (dont have IE7 or IE9 to test).
What am i missing?
//update states/province drwon down
$( "#country" ).change(function()
{
var id = $(this).val();
var request = $.ajax({
type : "GET",
dataType : "json",
url : "/api/v1/country/"+id+"/states",
cache : true,
beforeSend : function ()
{
$("#state").html('<select name="state" id="state" class="form-control input-sm " required ><option value="">Loading...</option></select>').show();
}
});
request.done(function( response )
{
cuntries = '<select name="state" id="state" class="form-control input-sm " required >';
$.each(response.data, function(i,data) {
cuntries +='<option value="'+data.code+'">'+data.name+'</option>';
});
cuntries += '</select>';
$("#state").html(cuntries);
});
request.fail(function( jqXHR, textStatus )
{
alert( "Request failed: " + textStatus );
});
return false;
});//close change
thanks for your quick response.
MVC Design Question
Hello, I would like to move an web application to MVC Laravel 4 (not sure yet). The challenge is that the application is used by many customers and each customer have its own website/front-end but they all use the same backend/admin.
The strucutre is something like this...
backend.domain.com (all customers go to here to update their site)
www.cliente1.com (a folder on the server with customized hml, css, etc that access the share PHP code)
www.cliente2.com (a folder on the server with customized hml, css, etc that access the share PHP code)
www.cliente3.com (a folder on the server with customized hml, css, etc that access the share PHP code)
So basically the question is: can i use MVC for this type of solution? if so, what would be your recomendation from a design stand point
Thanks!
What's your recommendation for PHP MVC frameworks?? i tested Codeigniter and it seem easy to use....
I am not a full time developer, but I do have some customers with backends, etc…My intention is to migrate some of old php code to PDO but I am now wondering if I should move the code to MVC....any recommendation?
BY THE WAY....i think you forgot to bindValue() on our code..
this is how i do it, based on great feedback from the forum:
DB CONNECTION CLASS:
class db {
/*** Declare instance ***/
private static $instance = NULL;
/**
*
* the constructor is set to private so
* so nobody can create a new instance using new
*
*/
private function __construct() {
/*** maybe set the db name here later ***/
}
/**
*
* Return DB instance or create intitial connection
*
* @return object (PDO)
*
* @access public
*
*/
public static function getInstance()
{
if (!self::$instance)
{
self::$instance = new PDO("mysql:host=ip_Addred_or_hostname;dbname=your_bd_name", 'your_db_username', 'your_db_password');;
self::$instance-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$instance;
}
/**
*
* Like the constructor, we make __clone private
* so nobody can clone the instance
*
*/
private function __clone(){
}
} /*** end of class ***/
PAYMENT CLASS
class payment
{
function __construct()
{
$this->table = 'YOUR_TABLE_NAME';
}
/**
* @param string $this->table Table name
* @param array $data Array with columns and values
* @return mixed Last inserted ID if insert succeeded, false otherwise
*/
public function insert($data)
{
$result = false;
$columns = array ();
$values = array ();
foreach ($data as $column => $value)
{
$columns[] = $column;
$values[] = ":$column";
}
$columns = implode(',', $columns);
$values = implode(',', $values);
$query = " INSERT INTO $this->table ($columns) VALUES ($values)";
$statement = db::getInstance()->prepare($query);
foreach ($data as $column => $value)
{
$statement->bindValue(":$column", $value );
}
if ($statement->execute() )
{
$result = db::getInstance()->lastInsertId();
}
return $result;
}
/**
* @param …
thank u sir!
Hello, do you guys recomend any CLASS or script to create Thumbnails? what are you using these days?
Hello, what would be the best way to prvent people to run a php script/file that is on ajax.post(URL)
$.ajax({
type: 'POST',
url: 'http://www.mydomain.com/ajax/somefile.php?action=insert',
data: data,
success: success,
dataType: dataType
});
if you see code above...let's say that an advanced user or hacker go to: http://www.mydomain.com/ajax/somefile.php?action=insert i would like to echo something like: go away...and prevent any code for running.
I saw codeigniter uses this at the top of every file:
if (!defined('BASEPATH')) exit('No direct script access allowed');.
Any recomendation??? .htaccess????
recomendation 1: on your local server run a cron to read the online database every minute, and get the reservation info
recomendation 2: have the online version send you an email, then read the mailbox infor and insert a record on the local DB.
recomendation 3: make the local server and online server, so your web app can read/write the local db. You dont need to host your web app on the local server, just make it visible
Hello,
i have this code to the insert:
class test {
function __construct() {
$this->table = 'testtable';
}
public function insert($values = array() )
{
foreach ($values as $field => $v)
{
$data[] = ':' . $field;
}
$data = implode(',', $data);
$fields = implode(',', array_keys($values));
$sql = " INSERT INTO $this->table ($fields) VALUES ($data)";
$statement = db::getInstance()->prepare($sql);
foreach ($values as $f => $v)
{
$statement->bindValue(':' . $f, $v);
}
if ($statement->execute() )
{
$result = db::getInstance()->lastInsertId();
}
return $result ;
}
}
but if i pass this code:
$a = new test();
$values = array(
'customer_id' => '13127'
,'product_id' => '2698'
,'notes' => "<script>alert('test')</script>"
);
$last_id = $a->insert($values);
the datbase gets an injection....I thought that the binValue() is safer... Should i need to clean the code before i pass it to teh class?
Sorry if someone think this is a stupid quesiton..
Hello, i wanted to know what you guys use with PDO.
Do you use ->fetchAll() or ->fetch() + while
based on some reading i have done, it seems that PDO->fetchAll() is faster but uses more momory...
Thanks for the feedback...I charge 65$ so i wanted to compare..
i charge:
- easy website : $1200 USD
- medimum website: 1200-3500 USD
- complex website: 3500 - 5000 USD
- very complex: starts at 5k+
hour rate: $65/hour
Hello,
I was wondering how much you guys charge an hour....
Hi there,
i was wondering if you can recomend a php class for google maps api v3. I statrted using this one today (http://code.google.com/p/php-google-map-api/) but i wanted to know if there is anything bettter out there...
thanks
Hello, I would like my customers to be able to add fields to a form, with differnt values, etc..
Basicly, i would like them to be able to add any type of fields and customize their forms; like google forms for instance. And of course, i need the databse to be able to insert/update etc
Do you guys have any example?
hi, I use 1and1.com as hosting provider. Here is what you need to do for 1nad1. http://faq.1and1.com/scripting_languages_supported/cron_jobs/3.html
If your hosting is linux, i guess it would be very similar.
Thanks pritaeas.
Would it be possible for you to give an example of of a function from a conf array?
hello, i was wondering if you could tell me what would you diffent/better on the following code. I am trying to become a better developer and i would like to learn what the best PHP pratice is. I remove the comments to make it a bit cleaner
//THIS IS THE CLASS I USE TO CONNECT TO THE DB - I USE PDO
class db
{
private static $instance = NULL;
private function __construct()
{
}
public static function getInstance()
{
if (!self::$instance)
{
self::$instance = new PDO("mysql:host=localhost;dbname=DB", '', '');;
self::$instance-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$instance;
}
private function __clone()
{
}
} /*** end of class ***/
//ONE CLASE AS EXPAMPLE
class Contact
{
function __construct()
{
}
//LOGIN FUNCTION
public function login()
{
$sql = " SELECT *
FROM contacts
WHERE username = :username AND password = :password
LIMIT 1;
";
try
{
$rs = db::getInstance()->prepare($sql);
$rs->bindParam(':username' , $this->username);
$rs->bindParam(':password' , $this->password);
$rs->execute();
if($rs->rowCount() > 0 )
{
//USER EXIST
$result = $rs->fetch(PDO::FETCH_ASSOC);
$this->login = 1;
@session_start();
$_SESSION["login"]= $this->login ;
foreach($result as $key => $value)
{
$_SESSION[$key] = $value;
}
header('Location: home/');
}else{
/* user not exist*/
$this->error = 'Username/Password not valid. Try again';
return false;
}
} catch (PDOException $e) {
print $e->getMessage();
}
}
//GET ONE RECOROD
public function getRecord($var)
{
try
{
$sql = "
SELECT `contacts`.*
FROM `contacts`
WHERE `contacts`.`contact_id` = :id
LIMIT 1;
";
$rs = db::getInstance()->prepare($sql);
$rs->bindParam(':id' , $var);
$rs->execute();
if($rs->rowCount() > 0 )
{
$result = $rs->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) …
Hello, i am working on PHP and jQuery trying to do a post with jquery. It seems to work in FF but IE is giving me several error:
The follwing is the code i am using:
<script>
$(function()
{
$("#mainForm").submit(function()
{
dataString = $("#mainForm").serialize();
$.ajax({
type : "POST",
url : "/gops/views/groups//ajax.php",
data : dataString,
//dataType : "json",
success : function(data) {
gid = $("#group_id").val();
$('#load_skills').load('/gops/views/groups/get_skills.php?gid='+gid);
}
});
return false;
});///close submit
});//close function
</script>
These are the errors i am getting in IE8:
Webpage error details
User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; BRI/2; InfoPath.2)
Timestamp: Thu, 19 Jul 2012 14:11:45 UTC
Message: Object doesn't support this property or method
Line: 3
Char: 13
Code: 0
Webpage error details
User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; BRI/2; InfoPath.2)
Timestamp: Thu, 19 Jul 2012 14:12:04 UTC
Message: Object doesn't support this property or method
Line: 3
Char: 13
Code: 0
URI:
Message: Object doesn't support this property or method
Line: 2
Char: 9
Code: 0
URI:
Message: Could not complete the operation due to error 80020101.
Line: 2
Char: 11321
Code: 0
URI: http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js?_=1342707101099
Hello,
I am trying to move 20 someting websites from a 1and1.com shared hosting to a 1and1.com cloud servers.....I found an issues that I havennt been able to fix. For every single INCLUDE or REQUIRE I am now getting "open_basedir restriction in effect"
I read about, and it seems to be a open_base issue....but i have tried it all..and still doesnt work...
did anyone ran into the same issue ?
Thank you for your quick reply.....i have few more basic questions:
The fact that you called the method user, the same as the class...and then you just did
<?php
$user = new User($_GET['userid']);
?>
without calling the method...would that work?
and...
what about if i want to call the method user like i did..."getRecord()"
how would you use the it?
Thanks again...and very sory for the basic question
By the way...
i love the
foreach($fieldValues as $key => $value) {
$this->$key = $value;
}
you have no idea how many lines of code you just saved me....
Hi there,
i am trying to use the classes proplery and i have a basic question....The following is the class i am using in order to get information from the DB...It is workinkg and i dont have any problem. But the question is how do i show the information on a form based on the data i got from the class?
file name: user.class.php
class User
{
function __construct()
{
}
public function getRecord($var)
{
try
{
/*** query ***/
$sql = " SELECT * FROM users WHERE userID= :id ";
/*** prepare the select statement ***/
$rs = db::getInstance()->prepare($sql);
/*** bind the parameters ***/
$rs->bindParam(':id' , $var);
/*** execute the prepared statement ***/
$rs->execute();
/*** Save result in $result ***/
$result = $rs->fetch(PDO::FETCH_ASSOC);
return $result;
}
catch (PDOException $e)
{
print $e->getMessage();
}
}
}//close class
on the web form i do this:
$User =new User();
$User->getRecord($_GET[userid]);
i know that i could do the following and it will work, but i am not sure if it;s the best way to do it:
$User =new User();
$Row = $User->getRecord($_GET[userid]);
<input name="first_name" type="text" id="first_name" value="<?=$Row['first_name']?>" />
I just want to do it right....
Hello,
is there any way to show what the size of the records is? I mean, i have a database that almost 500Mb and I want to see what records are causing it.
hello, i was wondering if someone can explain me what the difference is between the following classes.
I found class B nicer to use, but i want to have your comments.....
class A
{
public function setField($var)
{
$this->anyfield = $var;
}
}
//this is how i use it
$A = new A();
$A->setField($_POST['values']);
class B
{
public static function setField($var)
{
self::$anyfield = $var;
}
}
//this is how i use it
B::setField($_POST['values']);
Question:
- What does "static" means when declaring a function?
- Is "$this->" equal to "self: : $ " ? is there any difference?
The reason i am asking the questions is because i am about to re-code a big application I developed with PHP 4; and i want to do it right. I am also using PDO and trying to use/learn MVC.
Thank you all in advance.
Hello, i have a very basic question.
Is there a way to hide the file name/folder (ajax/post.php) used on the AJAX post request?
$.ajax({
type: 'POST',
url: 'ajax/post.php',
data: data,
success: success,
dataType: dataType
});
I dont want people to see this: 'ajax/post.php',
Hello,
I wanted to ask the full time PHP developers how important you think MVC Pattern is. Are you coding all your projects with MVC?
Would you have any recommendation in terms of PHP frameworks?
Hello there!
I am new with PDO and I am trying to replace the old code with PDO...
The main issue i have is that i dont know how to get/use the objects vs the arrays when it comes to showing data.
Please see bellow examples and let me know if you can help.
CURRENT/OLD CODE:
class customer
{
function getCustomer($customer_id)
{
$Sql = "SELECT * FROM customer WHERE customerID=".mysql_real_escape_string($customer_id);
$Res = @mysql_query($Sql);
$Row = @mysql_fetch_array($Res);
$this->Name = ucfirst(($Row['Name']));
$this->Email = ucfirst(($Row['Email']));
return $Row;
}
}
and in order to use the class i do the following:
//initiate the class
$Customer = new customer;
$Customer -> getCustomer($_GET[customer_id]);
echo $Customer->Name;
echo $Customer->Email;
i also use the code this way when i need forms:
<input name="customer_name" type="text" value="<?=$Customer->Name?>" />
SO...NEED SOME HELP BELOW...
I am learing PDO and i am trying to replace the old code (like the one above) with the new one, but i am not sure i am doing the right things...please see bellow:
NEW CODE:
//db coonection
$db = new PDO("mysql:host=$db_host;dbname=$db_name",$db_user,$db_pass);
class customer
{
function __construct($db)
{
$this->db = $db;
}
function getCustomer($customer_id)
{
$Sql = "SELECT * FROM customer WHERE customerID=".mysql_real_escape_string($customer_id);
$rs = $this->db->query($sql);
//$row = $rs->fetch(PDO::FETCH_ASSOC);
$row = $rs->fetch(PDO::FETCH_OBJ);
return $row;
}
}
//initiate the class
$Customer = new customer;
question:
1-how can i use the Name and Email as the example shown above?
could I the following?
//initiate the class
$Customer = $Customer -> getCustomer($_GET[customer_id]); …
Hi there, happy new year to all!
I started using PDO few weeks ago, and I am trying to figure out what is the best way to use it....I just put 3 samples bellow and I was hoping you can tell me what is the most secure and professional way of using it.
<?
//db Connection
$db = new PDO("mysql:host=$db_host;dbname=$db_name",$db_user,$db_pass);
class account
{
function __construct()
{
global $db;
$this->db = $db;
}
function getRecord($account_id)
{
$sql = "SELECT * FROM accounts WHERE account_id=".mysql_real_escape_string($account_id);
$rs = $this->db->query($sql) or die("failed!");
while($row = $rs->fetch(PDO::FETCH_ASSOC)){
$result[] = $row;
}
return $result;
}
}
$Account = new account();
// *
// * OR
// *
class account
{
function __construct()
{
}
function getRecord($account_id)
{
global $db;
$sql = "SELECT * FROM accounts WHERE account_id=".mysql_real_escape_string($account_id);
$rs = $this->db->query($sql) or die("failed!");
while($row = $rs->fetch(PDO::FETCH_ASSOC)){
$result[] = $row;
}
return $result;
}
}
$Account = new account();
// *
// * OR
// *
class account
{
function __construct($db)
{
$this->db = $db;
}
function getRecord($account_id)
{
$sql = "SELECT * FROM accounts WHERE account_id=".mysql_real_escape_string($account_id);
$rs = $this->db->query($sql) or die("failed!");
while($row = $rs->fetch(PDO::FETCH_ASSOC)){
$result[] = $row;
}
return $result;
}
}
$Account = new account($db);
?>
Is anyone familiar with this php class??? http://justinvincent.com/ezsql. I am planing to start using it as framework.
I think it is the based of Wordpress class.
hi there.....I have been working with PHP for a few years now, but i am not a professional developer. I would like to know if you have some tips about the PHP best practice.
For instance, i have been working on mysql but i know we have Mysqli..which one is better? any recomendation?
What about PEAR or any other framework? do you use them a lot?
sorry for these basic questions, but i want to get better at cooding and i found this website amazing!
Hello, how can i send an email every 10 min? I want to query the database and then send an email.
Thanks!
This worked!
<?php
class article {
function __construct($mysqli){
$this->mysqli = $mysqli; //now you can use the object as $this->mysqli throughout your class
}
function getArticles ()
{
$query = "
SELECT *
FROM topics
WHERE topictitle like '%$keyword%' or topicdescription like '%$keyword%';
";
if ($result = $this->mysqli->query($query) )
{
while ($row = $result->fetch_assoc()) {
echo $row['topictitle'].'<br>';
echo $row['topicdescription'].'<br><br>';
}
$result->close();
}
}
}
/* close connection */
include 'db.php';
$Article = new article($mysqli);
$Article->getArticles();
?>
sorry for being soo dummy, but this is what i am doing and still doenst work
<?php
class article {
private $mysqli;
function __construct($mysqli){
$this->mysqli = $mysqli; //now you can use the object as $this->mysqli throughout your class
}
function getArticles ()
{
$query = "
SELECT *
FROM topics
WHERE topictitle like '%$keyword%' or topicdescription like '%$keyword%';
";
if ($result = $this->$mysqli->query($query) )
{
while ($row = $this->$result->fetch_assoc()) {
echo $row['topictitle'].'<br>';
echo $row['topicdescription'].'<br><br>';
}
$result->close();
}
}
}
/* close connection */
include 'db.php';
$Article = new article($mysqli);
$Article->getArticles();
?>
ERROR:
Fatal error: Cannot access empty property in
if i do this, it works....But is it a good way?
class article {
private $mysqli;
function __construct($mysqli){
$this->mysqli = $mysqli; //now you can use the object as $this->mysqli throughout your class
}
function getArticles()
{
global $mysqli;
$query = "
SELECT *
FROM topics
WHERE topictitle like '%$keyword%' or topicdescription like '%$keyword%';
";
if ($result = $mysqli->query($query) )
{
while ($row = $result->fetch_assoc()) {
echo $row['topictitle'].'<br>';
echo $row['topicdescription'].'<br><br>';
}
$result->close();
}
}
}
Hi, i am trying to make this work but i guess i am missing something.....
This is what i have:
"db.php"
<?php
DEFINE('DATABASE_USER', 'root');
DEFINE('DATABASE_PASSWORD', '123456');
DEFINE('DATABASE_HOST', 'localhost');
DEFINE('DATABASE_NAME', 'livesearch');
$mysqli = new mysqli(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
else {
//connected
}
?>
"test.php"
<?php
class article {
function getArticles()
{
$query = "
SELECT *
FROM topics
WHERE topictitle like '%$keyword%' or topicdescription like '%$keyword%';
";
if ($result = $mysqli->query($query) )
{
while ($row = $result->fetch_assoc()) {
echo $row['topictitle'].'<br>';
echo $row['topicdescription'].'<br><br>';
}
$result->close();
}
}
}
include 'db.php';
$Article = new article($mysqli);
$Article->getArticles();
?>
The error I am getting is:
"Fatal error: Call to a member function query() on a non-object in C:\AppServ\www\test.php on line 13"
This line is not working:
if ($result = $mysqli->query($query) )
I don't know how to pass the $mysqli into the class and then into the function....... PLEASE HELP