Login Register


Basic PDO Retrieving Data filter_list
Author
Message
Basic PDO Retrieving Data #1
I'm here today with a tutorial on Inserting and Retrieving Data with PDO. I wanted to stick with just basic SQL until I figured out by a friend how much easier and better PDO is. I recommend everyone try and switch over too it.

Alright, lets get started. Go to PhpMyAdmin and lets make a new table called 'People' with 3 columns. Here is the set up:

[Image: hwpCTYh.png]

Next, lets add one item. Click insert, and leave the ID field blank. Enter in a first name and a last name and click go. You should see something like this when you click Browse now:

[Image: WuncEVn.png]


We are now on the PHP portion of this! Create a new file, and call it whatever you want.

Under the "<?php" you will want to add this and fill it in with your database info where it says change me!

Code:
$user = "ChangeMe"; $pass = "ChangeMe"; $details = "mysql:dbname=ChangeMe;host=localhost"; $dbh = new PDO($details, $user, $pass);

Once you have done that, we will go ahead and create our query. Its very simple, and it will grab all the rows within the column we are selecting from.

Code:
$query = $dbh->prepare("SELECT * FROM `People`"); $query->execute();

That will execute the query, next we have to grab each row of info which can be done like so:

Code:
while($row = $query->fetch(PDO::FETCH_ASSOC)) { echo "We have the person: " . $row['first'] . " " . $row['last'] . " in the database! <br />"; }

That is it for this tutorial! Next tutorial will be selecting by a parameter and binding. If you did this right then you should see something like this:

[Image: nceb.png]
[Image: GiXvY27.png]

Reply

RE: Basic PDO Retrieving Data #2
This is ace needed to update one of my projects from sqli to pdo. Thanks alot Smile

Reply







Users browsing this thread: 1 Guest(s)