I have a code in php where i m clikcing on women products or any other link for any other product.On click of which i m going to next page and passing the product name in querystring.
And then in next page i m using my sql query,which will give me the list of products which u clicked on first page.There are lot of queries in my project like this one.This query is quite prone to Google bots hacking with SQL injection.Following is the code
<html>
<head>
</head>
<body>
<ul id="list">
<li><h3>tops</h3></li>
<li><h3>suits</h3></li>
<li><h3>jeans</h3></li>
<li><h3>more</h3></li>
</ul>
</body>
</html
Search.php
<?php
$mysqli = new mysqli('localhost', 'root', '', 'shop');
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
}
?>
<html>
<head>
</head>
<body>
<?php
session_start();
$lcSearchVal=$_GET['name'];
//echo "hi";
$lcSearcharr=explode("-",$lcSearchVal);
$result=count($lcSearchVal);
//echo $result;
$parts = array();
$parts1=array();
foreach( $lcSearcharr as $lcSearchWord ){
$parts[] = '`PNAME` LIKE "%'.mysql_real_escape_string($lcSearchWord).'%"';
$parts1[] = '`TAGS` LIKE "%'.$lcSearchWord.'%"';
//$parts[] = '`CATEGORY` LIKE "%'.$lcSearchWord.'%"';
}
$stmt = $mysqli->prepare('SELECT * FROM xml where'.'PNAME LIKE ?');
var_dump($stmt);
$parts='%women%';
$stmt->bind_param('s',$parts);
$list=array();
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
$list[]=$row;
}
}
$stmt->close();
$mysqli->close();
foreach($list as $array)
{
?>
<div class="image">
<img src="<?php echo $array['IMAGEURL']?>" width="200px" height="200px"/></a>
<?php
}
?>
</div>
</body>
</html>
The query i m using above is quite prone to Google Bot hacking.Please guide me what should i change in this query so that Google Bot wont be able to hack my application with mysql injection..There are some other similar queries in my application to this one.Please guys help me on this.
The reason this is open to SQL injection is that you have not escaped the input.
For example you have the line:-
$parts[] = '`PNAME` LIKE "%'.$lcSearchWord.'%"';
If someone had used a link something like as follows (ignoring the encoding to get it to work in a URL):-
search.php?name=fred%' UNION SELECT * FROM users #
the SQL you would land up with would be something like:-
SELECT * FROM xml WHERE (`PNAME` LIKE "%fred%' UNION SELECT * FROM users #%")limit '.$offset.', '.$limit1.'
then they can execute a query to get data from the other table (possibly one containing the passwords, etc), with just a bit of patience getting the right number of columns, etc.
If you switch to mysqli_* you can use parameterised queries, but these are a minor pain when the SQL itself changes (as yours does in this case with a variable number of LIKE statements).
The simple solution would be to use mysql_real_escape_string() / mysqli_real_escape_string() on the variable you use in the SQL.
foreach( $lcSearcharr as $lcSearchWord )
{
$parts[] = '`PNAME` LIKE "%'.mysql_real_escape_string($lcSearchWord).'%"';
$parts1[] = '`TAGS` LIKE "%'.mysql_real_escape_string($lcSearchWord).'%"';
//$parts[] = '`CATEGORY` LIKE "%'.mysql_real_escape_string($lcSearchWord).'%"';
}
It is worth switching to mysqli_* if you can.
EDIT
Played with script using mysqli_() and a class and function to cope with variable numbers of parameters
<?php
session_start();
$mysqli = new mysqli('localhost', 'root', '', 'shop');
if(mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
}
?>
<html>
<head>
</head>
<body>
<?php
if (array_key_exists('name', $_GET))
{
$lcSearchVal = $_GET['name'];
$lcSearcharr = explode("-",$lcSearchVal);
$result = count($lcSearchVal);
$parts = array();
foreach( $lcSearcharr as $lcSearchWord ){
$parts[] = "%$lcSearchWord%";
}
$bindParam = new BindParam();
$parms = array();
foreach($parts as $aPart)
{
$parms[] = ' PNAME LIKE ? ';
$bindParam->add('s', $aPart);
}
$query = 'SELECT IMAGEURL FROM xml where '.implode(' OR ', $parms);
$stmt = $mysqli->prepare($query);
if ($stmt)
{
call_user_func_array(array($stmt, "bind_param"), refValues($bindParam->get()));
if ($stmt->execute())
{
while ($row = $stmt->fetch())
{
echo '<div class="image"><img src="'.$row['IMAGEURL'].'" width="200px" height="200px"/></a>';
}
}
else
{
echo $mysqli->error;
}
$stmt->close();
$mysqli->close();
}
else
{
echo $mysqli->error;
}
}
else
{
?>
<ul id="list">
<li><h3>tops</h3></li>
<li><h3>suits</h3></li>
<li><h3>jeans</h3></li>
<li><h3>more</h3></li>
</ul>
<?php
}
?>
</div>
</body>
</html>
<?php
function refValues($arr)
{
if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
{
$refs = array();
foreach($arr as $key => $value) $refs[$key] = &$arr[$key];
return $refs;
}
return $arr;
}
class BindParam
{
private $values = array(), $types = '';
public function add( $type, $value )
{
$this->values[] = $value;
$this->types .= $type;
}
public function get()
{
return array_merge(array($this->types), $this->values);
}
}
?>
Related
This code leaks information from the login page when a route that does not exist is being tried to navigate at.
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Login</h1>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="uname">
password: <input type="password" name="upass">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$loginusername = $_POST['uname'];
$loginpassword = $_POST['upass'];
if (empty($loginusername) || empty($loginpassword)) {
echo "Please enter username and password";
} else {
$user = getEnv('USER');
$password = getEnv('PASSWORD');
$database = getEnv('DATABASE');
$table = getEnv('SONGS');
$db = new PDO("mysql:host=localhost;dbname=$database", $user, $password);
$query = "SELECT * FROM $table where user_name = :username and password = :loginPassword";
$statement = $db->prepare($query);
$statement->bindParam(":username",$loginusername, PDO::PARAM_STR);
$statement->bindParam(":loginPassword",$loginpassword, PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetchAll();
if(!$result) {
echo "<p>No result!</p>";
exit;
} else {
$userid = $result[0][0];
$username = $result[0][1];
}
}
}
?>
</body>
</html>
This is an indexing page which will index all articles that are in the website.
<html>
<head>
<title>Some title</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
Return
<?php
if (isset($_GET['file'])) {
$file = $_GET['file'];
$file = file_get_contents($file);
echo "$file";
echo '<br />Index';
}
else {
$user = getEnv('USER');
$password = getEnv('PASSWORD');
$database = getEnv('DATABASE');
$table = getEnv('ARTICLES');
$db = new PDO("mysql:host=localhost;dbname=$database", $user, $password);
$query = "SELECT * FROM $table";
$stmt = $db->prepare($query);
$stmt = $db->query($query);
echo "<ul>";
foreach($stmt as $row) {
$href = $row[2];
$title = $row[1];
echo "<li> <a href='/myPage?file=../dir/$href'>$title</a> </li> ";
}
echo "</ul>";
}
?>
</body>
</html>
When this href echo "<li> <a href='/myPage?file=../dir/$href'>$title</a> </li> "; is changed manually at browser at suppose this route /myPage/?file=../login.php it will cause to leak code from the login file, which can uncover to the attack some crucial information about my backend setup. Is there any way how to patch this problem.
Yes, it's easily avoided by sanitizing your input.
Structures such as this
if (isset($_GET['file'])) {
$file = $_GET['file'];
$file = file_get_contents($file);
are highly problematic.
But there isn't a one-size-fits-all solution without knowing what the legit files that you want to allow to be referenced are.
Roughly how many valid files are there ? are they all located in the same directory ? do they follow some sort of specific naming convention ? do they all have the same extension (or lack any at all) ?
Edit: I suspect you'll want something along these lines. I haven't tested it, so it's possible i made a typo somewhere, but it shouldn't suffer from the same vulnerabilities atleast.
<html>
<head>
<title>Some title</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
Return
<?PHP
$user = getEnv('USER');
$password = getEnv('PASSWORD');
$database = getEnv('DATABASE');
$table = getEnv('ARTICLES');
$db = new PDO("mysql:host=localhost;dbname=$database", $user, $password);
$filekey = 'ref';
$dbcolumn = 'href'; // <--- should match the name of the column in mysql
if (isset($_GET[$filekey]) && $request = $_GET[$filekey]) {
$stmt = $db->prepare("SELECT $dbcolumn FROM $table WHERE $dbcolumn = ?");
$stmt->execute([ $request ]);
if ( $records = $stmt->fetchAll(PDO::FETCH_ASSOC)
&& !empty($records)
&& $record = reset($records)
&& isset($record[$dbcolumn])
&& $request = $record[$dbcolumn]
) {
echo file_get_contents("../dir/$request");
echo '<br />Index';
} else {
die('Access denied');
}
} else {
$query = "SELECT * FROM $table";
$stmt = $db->prepare($query);
$stmt = $db->query($query);
echo "<ul>";
foreach($stmt as $row) {
$href = $row[2];
$title = $row[1];
printf('<li><a href='/myPage?%s=%s'>%s</a></li>',
$filekey,
htmlentities($href, ENT_QUOTES),
htmlentities($title, ENT_QUOTES)
);
}
echo "</ul>";
}
?>
</body>
</html>
Make sure you set $dbcolumn correctly (should match the mysql column name), and optionally change $filekey to whatever you want to see in the URL.
This fixes your security problem: it only allows filenames to be specified in the URL, that actually exist in your database table, so it cant be used to pull random files anymore. If someone tries to manually change thevalue in the URL to something not in the database they get the error above.
It also fixes potential problems with the title in the listing, which was being output raw (i added htmlentities). Depending on the type of content inside the files, you may want to wrap a htmlentities call around file_get_contents() aswell, but don't do that if there is actual html inside those files.
I did see some other oddities , such as that you create a prepared statement and then don't use it :) but that has no security implications in this case, i left it as is.
Hey guys so i really have a problem in php and i have been working on it for like an hour and i can get it to work. So in my database i have two tables:
usuarios and menus
So each user have a menu assigned like this:
usuarios
id email ....... menus
1 email ...... 1,2,3,4
where 1,2,3,4 is text that i will explode and convert it into an array so latter i can get the menus checking the menu id's.
menus
id url .....
1 profile ..........
2 messages ..........
3 log out ..........
4 support ..........
I dont know why it is not working, please help.
<?php
if (!empty($_SESSION['id'])) {
include_once "database.php";
$section = !empty($_GET['s']);
try {
$stmt = $db->prepare("SELECT * FROM usuarios WHERE id=:usuid");
$stmt->execute(array(':usuid'=>$_SESSION['id']));}
// Checks the user id from his session (session has been already started in headers)
if($stmt->rowCount() > 0){
$row = $stmt->fetch();
$menus = $row['menus'];
//Gets the menus
$menus = explode(",", $menus);
//Converts the text into an array.
$i = 0;
$menusize = sizeof($menus);
//Checks how big is $menus array
$menusize = $menusize -1;
//This is because $i=0 and not 1
while ($i == $menusize) {
try{
$stmt = $db->prepare("SELECT * FROM menus WHERE id=:menus");
$stmt->execute(array(':menus'=>$menus[$i]));
$row = $stmt->fetch();
if ($section==$row['url']) {
echo '<li class="liselected"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}else{
echo '<li class="menuelement"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}
$i++;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
//Here is the problem, in this while
} else {
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}else{
header("Location:index.php");
}
?>
I have checked and what happends is that $i doesnt seems to be incrementing, i have been working on it but nothing seems to do it.
Thank you all for your support!
You should do it a little bit differently altogether, like storing the menu's in different rows but for now:
<?php
if (!empty($_SESSION['id'])) {
include_once "database.php";
$section = !empty($_GET['s']);
try {
# When you set the $_SESSION['id'] and you're sure it's sanitized you don't have to prepare a query. Instead execute it directly.
# Preparing is useful for user submitted data or running the same query more then once with different values (seen below)
$stmt = $db->prepare("SELECT * FROM usuarios WHERE id=:usuid");
$stmt->execute(array(':usuid'=>$_SESSION['id']));
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if($stmt->rowCount() > 0){
// This part of the code does not match your description of your database.
$row = $stmt->fetch();
$menu = explode(",", $row['menus']);
// end
$stmt = $db->prepare("SELECT * FROM menus WHERE id=:menus");
try{
foreach($menu as $value){
$stmt->execute(array(':menus'=>$value));
$row = $stmt->fetch();
$css_class = ($section == $row['url']) ? 'liselected' : 'menuelement';
echo '<li class="'.$css_class.'"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
} else {
header("Location:index.php");
}
?>
Please note that I only prepared the query once, this is the proper way to do it. Preparing takes server performance, but once prepared you can rebind the values.
Also, I changed the loop to a foreach loop, easier to maintain.
There where also some bracket issues in the code, my advice always code in the same way so these issues are easy to spot.
I've been using mysql and it did what I want, but as my project is getting larger, I decided to opt for mysqli.
I looked at the tutorial at enter link description here which was really straight forward up until the point where I want to display some data
stored procedure (connect.php)
<?php
function db_connect() {
// Define connection as a static variable, to avoid connecting more than once
static $con;
// Try and connect to the database, if a connection has not been established yet
if(!isset($con)) {
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file('config.ini');
$con = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}
// If connection was not successful, handle the error
if( $con === false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return mysqli_connect_error();
}
return $con;
}
function db_query($query) {
// Connect to the database
$con = db_connect();
// Query the database
$result = mysqli_query( $con,$query);
return $result;
}
function db_error() {
$con = db_connect();
return mysqli_error($con);
}
function db_select($query) {
$rows = array();
$result = db_query($query);
// If query failed, return `false`
if($result === false) {
return false;
}
// If query was successful, retrieve all the rows into an array
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
function db_quote($value) {
$con = db_connect();
return "'" . mysqli_real_escape_string($con,$value) . "'";
}
?>
php/html
<div class="grid_4">
<div class="left-1">
<h2 class="top-1 p3">Find a property</h2>
<form id="form-1" method="post" class="form-1 bot-1" action="prop_result.php">
<div class="select-1">
<label>Select Area</label>
<select name="field4" id="field4" >
<?php
$rows = db_select("SELECT id,city_id,area FROM area");
if($rows === false) {
$error = db_error();
}else
{
while($rows=mysqli_fetch_assoc($result))
{
?>
<option value=""><?php $rows['
area'];?></option>
<?php
}}
?>
</select>
</div>
What I don't understand is how to use the stored procedure in a while loop so it will output the data in the fields ID and Area so my select box and any other input can be properly populated based on the query
current
I've tried different ways :
<?php
$rows = db_select("SELECT id,city_id,area FROM area");
if($rows === false) {
$error = db_error();
}
while($rows=mysqli_fetch_assoc($result))
{
?>
<option value=""><?php $rows['
area'];?></option>
<?php
}
?>
and
$rows = db_select("SELECT id,city_id,area FROM area");
if($rows === false) {
$error = db_error();
}
{
?>
<option value=""><?php $rows['
area'];?></option>
<?php
}
?>
and
<?php
$rows = db_select("SELECT area_id from property");
if($rows === false) {
$error = db_error();
}
{
echo "<option value='".$rows['id']."'>".$rows[$col4]."</option>";
}
?>
None of these output any data. Echoing $rows gives no data. I don't know what the logic is for using the stored procedure to display the output.
Any help would be appreciated, if any other information is required to assist in resolving this issue, please let me know.
Awesome to hear that the data is returning. Try this out for size...
foreach($rows as $key => $value){
foreach($value as $k => $v){
if($k == 'id'){
$newID = $v;
}
if($k == 'type'){
$newType = $v
}
}
echo "<option value='".$newID."'>".$newType."</option>";
}
with this you should be able to make it work for you liking.
Edit: Didnt see the additional arrays until later...the nested loop should suite you better.
Siniseus way works but its too much code for a simple task. I did work with it to finally come to this
<select name="field4" id="field4" >
<?php
$rows = db_select("SELECT id, city_id,area FROM area");
foreach($rows as $row){
echo "<option value='".$row['id']."'>".$row['area']."</option>";
}
?>
</select>
Simple, clean and really straight forward without too many variables.
$rows = db_select ("Select Query")foreach($rows as $row){
do this
}
On my server I include 'config.php' in each function and it works perfectly, however when I do the same on my LOCALHOST the variable $mysqli cannot be found, will the PHP version differ from server to localhost? The paths are both 100% correct.
The error is as follows;
Notice: Undefined variable: mysqli in
C:\Users\PC\Documents\XAMPP\htdocs\php\myfunctions.php on line 20
config.php
$mysqli = new mysqli('localhost', 'userone', 'password', 'iitb');
The connection obviously changes when I use server
myfunctions.php
<?php
class News
{
function getLatest()
{
include 'config.php'; // WHERE TO PUT THIS CANNOT FIND MYSQL
$time = date('Y-m-d G:i:s', strtotime("-1 week"));
$stmt = $mysqli->prepare("SELECT ForumId, ForumTitle, ForumPostText FROM `forum` WHERE `PostDate` > ? ORDER BY PostDate desc LIMIT 5 ");
$stmt->bind_param('s', $time);
$stmt->execute();
$stmt->bind_result($ForumId, $ForumTitle, $ForumPostText);
$stmt->store_result();
if ($stmt->num_rows() == 0) {
echo "<p>No latest article available</p>";
} else {
while ($row = $stmt->fetch()) {
echo '<p class="posttitle">' . $ForumTitle . ' </p>';
echo '<p class="posttext">' . substr($ForumPostText, 0, 93) . ' ...</p>';
}
$stmt->free_result();
}
}
function mostPopular()
{
include 'config.php'; // WHERE TO PUT THIS CANNOT FIND MYSQL
$stmt = $mysqli->prepare("SELECT ForumId, ForumTitle, ForumPostText FROM forum ORDER BY Views DESC LIMIT 5");
$stmt->execute();
$stmt->bind_result($ForumId, $ForumTitle, $ForumPostText);
$stmt->store_result();
if ($stmt->num_rows() == 0) {
echo "<p>No latest article available</p>";
} else {
while ($row = $stmt->fetch()) {
echo '<p class="posttitle">' . $ForumTitle . ' </p>';
echo '<p class="posttext">' . substr($ForumPostText, 0, 93) . ' ...</p>';
}
$stmt->free_result();
}
}
}
Rather than having include 'config.php'; // WHERE TO PUT THIS CANNOT FIND MYSQL in each of your functions, add the $database parameter Eg function mostPopular($database){... and change $mysqli-> to $database->
Then when you call the functions, pass the database through mostPopular($database)
On an unrelated note: You may also find it easier to have the functions return an array rather than echo HTML so that your functions just get the data format it and return values. (It also means you can get away from echoing full HTML.
Here is an example using your mostPopular function
Function:
function mostPopular($databaseName){
$stmt = $mysqli->prepare("SELECT ForumId, ForumTitle, ForumPostText FROM forum ORDER BY Views DESC LIMIT 5");
$stmt->execute();
$stmt->bind_result($ForumId,$ForumTitle,$ForumPostText);
$stmt->store_result();
$returnData = array();
if($stmt->num_rows() > 0){
$i = 0;
while($row = $stmt->fetch()){
$returnData[$i]['ForumId'] = $ForumId;
$returnData[$i]['ForumTitle'] = $ForumTitle;
$returnData[$i]['ForumPostText'] = substr($ForumPostText, 0,93) . ' ...';
++$i;
}
$stmt->free_result();
}
}
return $returnData;
}
Use:
<div id="mostPopular">
<?php
$mostPopular = mostPopular($mysqli);
if(count($mostPopular) === 0){
?>
<p>No latest article available</p>
<?php
} else {
foreach($mostPopular as $Popular){
?>
<p class="posttitle"><?php echo $Popular['ForumTitle'];?></p>
<p class="posttext"><?php echo $Popular['ForumPostText'];?></p>
<?php
}
}
?>
</div>
The problem is that the config.php script is not started with the PHP start tag of
<?php
The config file should be like this:
<?php
$mysqli = new mysqli('localhost', 'userone', 'password', 'iitb');
EDIT: Make sure also to check the php_short_tags. It could be that the config.php file starts with a short tag <? and the short_open_tag is disabled on your localhost server.
I highly appreciate that you try to help me.
My problem is this script:
<?php include("inc/incfiles/header.inc.php"); ?>
<?php
$list_user_info = $_GET['q'];
if ($list_user_info != "") {
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$list_user_info'");
$get_user_list = mysql_fetch_assoc($get_user_info);
$user_list = $get_user_list['username'];
$user_profile = "profile.php?user=".$user_list;
$profilepic_info = $get_user_list['profile_pic'];
if ($profilepic_info == "") {
$profilepic_info = "./img/avatar.png";
}
else {
$profilepic_info = "./userdata/profile_pics/".$profilepic_info;
}
if ($user_list != "") {
?>
<br>
<h2>Search</h2>
<hr color="#FF8000"></hr>
<div class="SearchList">
<br><br>
<div style="float: left;">
<img src="<?php echo $profilepic_info; ?>" height="50" width="50">
</div>
<?php echo "<h1>".$user_list."</h1>"; ?>
</div>
<?php
}
else {
echo "<br><h3>User was not found</h3>";
}
}
else {
echo "<br><h3>You must specify a search query</h3>";
}
?>
I am creating a search script that takes the mysql databse information and shows the result associated to the search query. My script is the above, but keep in mind the sql connection is established in an extern scipt.
The problem is that i want the script to first check if the user is found with the search query in the username row, and then get the entre information from that user and display it. If the user is not found with the username query, it should try and compare the search query with the name row, and then with the last name row. If no result is displayed it should then return an else statement with an error, e.g. "No user wsas found"
Yours sincerely,
Victor Achton
Do the query as Muhammet Arslan ... but just counting the rows would be faster ...
if(mysql_num_rows($get_user_info)){
//not found
}
you should add a "Limit 1" at the end if you are just interested in one result (or none).
But read about prepared statements
pdo.prepared-statements.php
This is how it should be done in 2013!
Something like this but you don't need 3 queries for this. you can always use OR in mysql statements
$handle1 = mysql_query("SELECT * FROM users WHERE username = $username"); // Username
if (($row = mysql_fetch_assoc($handle1) !== false) {
// username is found
} else {
$handle2 = mysql_query("SELECT * FROM users WHERE name = $name"); // name
if (($row = mysql_fetch_assoc($handle2) !== false) {
// name is found
} else {
$handle3 = mysql_query("SELECT * FROM users WHERE lastname = $lastname"); // Last name
if (($row = mysql_fetch_assoc($handle3) !== false) {
// last name is found
} else {
// nothing found
}
}
}
Already you did ,but you can improve it by using "AND" or "OR" on ur sql statement.
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$list_user_info' or name = '$list_user_info' or last_name = '$list_user_info'");
$get_user_list = mysql_fetch_assoc($get_user_info);
if(empty($get_user_list))
{
echo "No User was found";
}
and you should control $list_user_info or u can hacked.
Here some adapted copy pasting from php.net
Connect
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
fetch data
$stmt = $dbh->prepare("SELECT * FROM users where name LIKE '%?%'");
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
the rest is your programing ...
And do some reading it's very dangerous to use copied code without understanding !