I have an ajax call that posts data to a php script and returns data. If I echo the data in the php script, I can alert it fine in javascript. But if I return it as json, the al
As requested in the comments here is an example of a parameterized query using PDO.
$sql=new PDO("mysql:host=127.0.0.1;dbname=name","user","password");
$query="Select * from Northwind where Id=:ID";
$stmt=$sql->prepare($query);
$stmt->bindParam(':ID',$random_Id);
$stmt->execute();
$dr=$stmt->fetch();
$sql=null;
Let's go over it line by line.
$sql=new PDO("mysql:host=127.0.0.1;dbname=name","user","password");
$sql becomes a new PDO object (pdo can support many types of databases ( in this example we are using MYSQL).
$query="Select * from Northwind where Id=:ID;
note instead of providing an actual Id from the Northwind table, we are supplying ':ID.'
$stmt=$sql->prepare($query);
Here comes the fun part. The prepare statement sends our query string to the sql server. At this point the server knows the sql command we will run, but doesn't yet know the value of our variable.
$stmt->bindParam(':ID',$random_Id);
bindParam then sends the value of $random_Id to replace the ':ID.'
$stmt->execute();
$dr=$stmt->fetch();
our query is then executed, and the results are put into $dr. You can get your data out of $dr like you would a hash table. So lets say the northwind table looks like this:
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| Id | int | NO | PRI | NULL | |
| Name | varchar(10) | NO | UNI | NULL | |
| Passwd | varchar(50) | NO | | NULL | |
| Salt | varchar(50) | NO | UNI | NULL | |
+--------+-------------+------+-----+---------+-------+
and we want the value of 'Name.' We would type something like this:
$userName=$dr['Name'];
$sql=null;
this line destroys the PDO object, freeing it from memory and closes the Database connection.
There are two advantages of doing SQL this way. The first is speed. If you needed to run that query above, I dunno 6 times with 6 different Ids you could do something like this after the prepare statement:
for($i=0;$i<=6;$i++)
{
$stmt->bindParam(':ID',$i);
$stmt->execute;
}
The server already has the main query, so we just send it whats changed. If we were doing something like this to insert many records, it would be much faster than putting the whole query in the loop.
The second benefit is it makes SQL injections impossible (the main reason I use it).