Search form with PDO - php

The below code now works but how can I make it so if no results are found it echos a message instead of blank.
I think I've managed to create a search query for my database. Its only a very basic search but it doesn't seem to work for some reason. Any advice would be appreciated im still new to pdo (very new! be kind!).
Also no user submitted data is inserted into the database so I think i can rule out xss assuming its SQL inject free? Which from what I understand PDO is? plus im using a stand alone DB user with no write access.
Have replace data with xxx for security
file is called search.php
*updated to reflect changes suggested
*2nd update to reflect help provided
*3rd update
<html>
<head>
</head>
<body>
<form name="frmSearch" method="post" action="search.php">
<table width="599" border="1">
<tr>
<th>Keyword
<input name="var1" type="text" id="var1">
<input type="submit" value="Search"></th>
</tr>
</table>
</form>
<?php
$nameofdb = 'xxxxxx';
$dbusername = 'xxxxxxxxxxxxxx';
$dbpassword = 'xxxxxxxxxxxxx';
// Connect to MySQL via PDO
try {
$dbh = new PDO("mysql:dbname=$nameofdb;host=localhost", $dbusername, $dbpassword);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$var1 = str_replace(array('%','_'),'',$_POST['var1']);
if (!$var1)
{
exit('Invalid form value: '.$var1);
}
$query = "SELECT * FROM xxxxx WHERE xxxxxx LIKE :search OR xxxxx LIKE :search";
$stmt = $dbh->prepare($query);
$stmt->bindValue(':search', '%' . $var1 . '%', PDO::PARAM_INT);
$stmt->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $stmt->fetchAll();
foreach( $result as $row ) {
echo $row["id"];
echo $row["title"];
}
?>
</body>
</html>

The problem is in the form. the method is GET but in your php you expect $_POST
So this line:
<form name="frmSearch" method="get" action="search.php">
should be:
<form name="frmSearch" method="post" action="search.php">
UPDATE
Change your code to this:
// Connect to MySQL via PDO
$dbh = new PDO("mysql:dbname=$nameofdb;host=localhost", $dbusername, $dbpassword);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$var1 = $_POST['var1'];
$query = "SELECT * FROM xxxxx WHERE xxxx LIKE :search OR xxxxx LIKE :search";
$stmt = $dbh->prepare($query);
$stmt->bindValue(':search', '%' . $var1 . '%',);
$stmt->execute();
To check if there are no line and give a message you can do it like this:
$result = $stmt->fetchAll();
if ($result) {
foreach( $result as $row ) {
echo $row["id"];
echo $row["title"];
}
} else {
echo 'There is nothing to show';
}

i wrote this method and use in every project i working on it . try it :)
public function searchForQueryString($queryString)
{
$query = "SELECT * FROM `xxxx` WHERE (`xxxxxxx` like :queryString or `xxxxx` like :queryString) ";
$sth = $this->prepare($query);
$queryString = '%' . $queryString . '%';
$sth->bindParam('queryString', $queryString, PDO::PARAM_STR);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_OBJ);
if(empty($result) or $result == false)
return array();
else
return $result;
}

I modified Amir's code and it works:
protected $pdo;
public function __construct($pdo)
{
$this->pdo = $pdo;
}
public function selectSearch($table, $search)
{
$statement = $this->pdo->prepare("select * from {$table} WHERE post_tags LIKE '%$search%'");
$statement->execute();
$result = $statement->fetchAll();
if(empty($result) or $result == false){
echo "<h1> No Result</h1>";
return array();
} else{
return $result;
}}
if(isset($_POST['submit'])){
$search = $_POST['search'];
$data = $query->selectSearch('posts', $search);
}

Related

jQuery Ajax - $sql is an object Error

UPDATE at bottom of question
I'm getting the error:
Warning: mysqli_query() expects parameter 2 to be string, object
given
Questions about this are incredibly common on Stack Overflow - my apologies in advance. I haven't been able to find a good answer for my specific problem. If there is a thread that addresses this, please let me know.
Here is my Ajax code:
$.ajax({
url: "get.php",
type: "post",
datatype: "json",
data:{ ajaxid: altCheck }, //this is an integer passed to MySQL statement
success: function(response){
console.log(response);
},
error: function(){
console.log("test");
}
});
get.php
<?php
$db = mysqli_connect("...", "...", "...", "...");
$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING);
$value = mysqli_real_escape_string($db, $value);
var_dump($value); //checking to see what $value is at this point
$sql = $db->prepare("SELECT * FROM table WHERE screeningId = ?");
$sql->bind_param("s",$value);
//THIS LINE THROWS THE ERROR
$result = mysqli_query($db, $sql);
$temp = array();
while ($row = mysqli_fetch_array($result)){
//output data
array_push($temp,$row['imageURL']);
}
echo json_encode($temp);
?>
The fourth line of code var_dump($value); outputs string(0).
UPDATE: MySQLi
<?php
$db = mysqli_connect("...", "...", "...", "...");
$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING);
$value = mysqli_real_escape_string($db, $value);
$query = $db->prepare('SELECT * FROM table WHERE screeningId = ?');
$query->bind_param('s', $_GET[$value]);
$query->execute();
if ($result = mysqli_query($db, $query)) {
while ($url = mysqli_fetch_object($result, 'imageURL')) {
echo $url->info()."\n";
}
}
?>
Screenshot of MySQL table data columns:
EDIT
Okay... 8 edits spent on mysqli... Enought!
Here is how I DO using PDO. And it WILL work first shot.
I have a separate file for the database connection info.
dbconnection.php:
(The advantage of the separate definition file is one place to update the user password when needed.)
<?php
// Database connection infos (PDO).
$dsn = 'mysql:dbname=[DATABASE_NAME];host=127.0.0.1';
$user = '[DATABASE_USER]';
$password = '[USER_PASSWORD]';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connexion failed : ' . $e->getMessage();
}
?>
Now in your PHP files where a database request has to be done, include the PDO definition file, the just request what you want:
<?php
include('dbconnection.php');
// JUST TO DEBUG!!!
$_REQUEST['ajaxid'] = "1";
// Database request.
$stmt = $dbh->prepare("SELECT * FROM table WHERE screeningId = ?");
$stmt->bindParam(1, $_REQUEST['ajaxid']);
$stmt->execute();
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
die;
}
// Looping through the results.
$result_array =[];
while($row=$stmt->fetch()){
array_push($result_array,$row['imageURL']);
}
// The result array json encoded.
echo json_encode($result_array);
?>
Since you are using mysqli_* all other place in your project, update your get.php as below.
<?php
$db = mysqli_connect("...", "...", "...", "...");
$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING);
$value = mysqli_real_escape_string($db, $value);
//var_dump($value); //checking to see what $value is at this point
$sql = "SELECT * FROM table WHERE screeningId = '$value'";
$result = mysqli_query($db, $sql);
$temp = array();
while ($row = mysqli_fetch_array($result)){
//output data
array_push($temp,$row['imageURL']);
}
echo json_encode($temp);
EDIT
With respect to bind param with mysqli,
<?php
$conn = new mysqli('db_server', 'db_user', 'db_passwd', 'db_name');
$sql = 'SELECT * FROM table WHERE screeningId = ?';
$stmt = $conn->prepare($sql);
$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING);
$stmt->bind_param('s', $value);
$stmt->execute();
$res = $stmt->get_result();
$temp = array();
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
array_push($temp,$row['imageURL']);
}
echo json_encode($temp);
Select Data With PDO in get.php:
<?php
if( isset($_POST['ajaxid']) ) {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM table WHERE screeningId = :screeningId");
$stmt->execute(array(':screeningId' => $_POST['ajaxid']));
$row = $stmt->fetch();
}
?>
You configure PDO to throw exceptions upon error. You would then get a PDOException if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $conn object:
$stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Iterating through a Multidimensional Array in php without known keys

I am writing a web application and I believe one of the parts requires a
multidimensional array. The array holds a list of applications in a database.
I want to be able to display the list of applications by the individuals name or
a unique ID. I have this part working. Then I want to click on an individual
application and only pull up that particular row of information to fill in a form.
Currently when I do this it either brings up all of the rows from the database or
the first row only. Does anyone have any suggestions?
I am not great with explanations so I am including parts of my code. I am sorry
it's so long. I tried to reduce it as much as possible. Even though its included
in the code, i didn't include config.php because it's just my database connection.
userList.php:
<?php
include("config.php");
?>
<!DOCTYPE html>
<html>
<body>
<h1>Test</h1>
<p><b><u>Users</b></u></p>
</body>
</html>
<?php
require_once("/class/users.php");
$rowt = array(array());
$rowt = users::fillForm($rowt);
foreach($rowt as $test) {
if(is_array($test))
{
echo "<a href='userDisplay.php'>".$test['name']."</a><br/>";
}
}
?>
userDisplay.php:
<!DOCTYPE html>
<html>
<body>
<h1>Tester</h1>
<?php
include("config.php");
//declare array
$rowt = array(array());
//pass array into class function
//since functions can't return more than one variable, you have to pass the
//array and set it equal to the original variable while calling the pdo function
$rowt = users::fillForm($rowt);
foreach($rowt as $test=> $rowt){
?>
<h2>Application for <?php echo $rowt['name']?></h2>
<table>
<tr><th><b>Name</b></th>
<th><b>Phone Number</b></th>
<th><b>Best Time to Call<b></th>
</tr>
<tr></tr>
<tr><td><output type='text' maxlength="30" required name='name'><?php echo $rowt['name']?></output></td>
<td><output type="text" maxlenth="30" required name="p_num"><?php echo $rowt['phone_number']?></output></td>
<td><output type='text' maxlength="30" required name='bc_time'><?php echo $rowt['best_call_time']?></output></td></tr>
<tr></tr>
<tr>
<th><b>Visa Status<b></th>
<th><b>IT Experience<b></th>
<th><b>Relevant Experience<b></th>
</tr>
<tr></tr>
<tr><td><output type='text' maxlength="30" required name='v_status'><?php echo $rowt['visa_status']?></output></td>
<td><output type='text' maxlength="30" required name='it_exp'><?php echo $rowt['it_exp']?></output></td>
<td><output type='text' maxlength="30" required name='rel_exp'><?php echo $rowt['relevant_exp']?></output></td>
</tr>
<tr></tr>
<tr>
<th colspan="3"><b>Description<b></th>
</tr>
<tr></tr>
<tr>
<td colspan="3"><output name="description" rows="4" cols="100"></output><?php echo $rowt['description']?>></td>
</tr>
</table>
</body>
</html>
<?php
}
echo "<a href='userList.php'>Back</a>";
?>
Functions from users.php users class:
public function insertForm() {
$correct = false;
try {
$con = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO user(name, phone_number, best_call_time, description,
visa_status, it_exp, relevant_exp) VALUES(:name, :p_num, :bc_time, :description,
:v_status, :it_exp, :rel_exp)";
$stmt = $con->prepare($sql);
$stmt->bindValue("name", $this->name, PDO::PARAM_STR);
$stmt->bindValue("p_num", $this->p_num, PDO::PARAM_STR);
$stmt->bindValue("bc_time", $this->bc_time, PDO::PARAM_STR);
$stmt->bindValue("v_status", $this->v_status, PDO::PARAM_STR);
$stmt->bindValue("it_exp", $this->it_exp, PDO::PARAM_STR);
$stmt->bindValue("rel_exp", $this->rel_exp, PDO::PARAM_STR);
$stmt->bindValue("description", $this->description, PDO::PARAM_STR);
$stmt->execute();
return "Entry Successful <br/> <a href='userForm.php'>Home</a>";
}catch(PDOException $e) {
return $e->getMessage();
}
}
public static function fillForm($rowt) {
$successt = false;
try{
$conn = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql1 = "SELECT * FROM user";
$stmt1 = $conn->prepare($sql1);
$stmt1->execute();
$rowt = $stmt1->fetchAll(PDO::FETCH_NUM&PDO::FETCH_ASSOC);
return $rowt;
}catch (PDOException $et) {
echo $et->getMessage();
return $successt;
}
}
There is a lot going on here, but if I get the gist of your question you want to be able to return one individual user when a row in a list of users is clicked. To do that you would need to update your SQL query to pull a particular user. Something along the lines of:
// Formatting into a class to cut down on repetition.
<?php
class User {
private $dbConnect;
// functionally these two are similar but I separated users and user
// for clarity of purpose.
public function getUsers()
{
// Enumerating your select columns is clearer, and more efficient.
$sql = "SELECT name, phone_number, best_call_time, description,
visa_status, it_exp, relevant_exp
FROM user";
$result = $this->makeQuery($sql);
return ($result) ? $result : array();
}
public function getUser($name)
{
// Enumerating your select columns is clearer, and more efficient.
$sql = "SELECT name, phone_number, best_call_time, description,
visa_status, it_exp, relevant_exp
FROM user
WHERE name = :name";
$param = $this->prepareUserInfo(array('name' => $name));
$result = $this->makeQuery($sql, $param);
return ($result) ? $result : array();
}
public function createUser($userInfo)
{
$sql = "INSERT INTO user(name, phone_number, best_call_time, description,
visa_status, it_exp, relevant_exp) VALUES(:name, :p_num, :bc_time, :description,
:v_status, :it_exp, :rel_exp)";
$params = $this->prepareUserInfo($userInfo);
try {
$this->connect();
$stmt = $this->dbConnect->prepare($sql);
$stmt = $this->bindParams($stmt, $data);
$stmt->execute();
return "Entry Successful <br/> <a href='userForm.php'>Home</a>";
} catch(PDOException $e) {
return $e->getMessage();
}
}
private function prepareUserInfo($userInfo)
{
$infoArray = array();
foreach ($userInfo as $key => $value) {
// Going with your original code I'm hardcoding param type here, but
// you could easily write a check for data type and set param dynamically.
$infoArray[] = array(
'key' => $key,
'value' => $value,
'type' => PDO::PARAM_STR,
);
}
return $infoArray;
}
private function makeQuery($sql, $data = array())
{
try{
$this->connect();
$stmt = $this->dbConnect->prepare($sql);
if (!empty($data)) {
$stmt = $this->bindParams($stmt, $data);
}
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_NUM&PDO::FETCH_ASSOC);
return (!empty($result)) ? $result : false;
} catch (PDOException $e) {
echo $e->getMessage();
return false;
}
}
private function bindParams($stmt, $data)
{
foreach ($data as $item) {
$stmt->bindValue("name", $this->name, PDO::PARAM_STR);
$stmt->bindValue($item['key'], $item['value'], $item['type']);
}
return $stmt;
}
private function connect()
{
$dbConnect = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$dbConnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->dbConnect = $dbConnect;
}
}
?>
From there your click handler would need to trigger a User->getUser('some name'); request. You could take this abstraction further by separating your PDO connect into it's own class and handle query building and execution from there.
Seconding the above comment about not mixing your presentation with your data layer. Check out a templating engine like Twig or (less advisable but sometimes necessary) roll your own by building a view loader that loads template files to an output buffer, adds dynamic variables, and returns a rendered string.

PDO - Fatal error: Call to a member function prepare() on null

I searched similar issues here but could not fix my problem.
I'm trying to add a search function to my website, but for some reason the search results are not displayed. In my error_log I get this error:
PHP Fatal error: Call to a member function prepare() on null in /home/..../search.php on line 9
which is this line:
$query = $pdo->prepare("SELECT * FROM subs WHERE sub_title LIKE '%$search%' LIMIT 0, 10");
Here is my search.php code:
<?php
require_once('includes/config.php');
include("includes/header.php");
// Search from MySQL database table
$search = $_POST['search'];
$query = $pdo->prepare("SELECT * FROM subs WHERE sub_title LIKE '%$search%' LIMIT 0, 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if(!$query->rowCount() == 0) {
echo "Search found:<br>";
echo "<table>";
echo "<tr><td>Title</td><td>Category></td><td>Language</td><td>Time</td><td>Download</td></tr>";
while($results = $query->fetch()) {
echo "<tr><td>";
echo $results['sub_title'];
echo "</td><td>";
echo $results['category'];
echo "</td><td>";
echo $results['sub_lang'];
echo "</td><td>";
echo $results['timestamp'];
echo "</td><td>";
echo $results['sub_data'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo "Nothing found";
}
?>
Here is my config.php
<?php
$username = '------';
$password = '------';
try {
$conn = new PDO('mysql:host=localhost;dbname=-----', $username, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
}
catch(PDOException $e) {
echo "Failed to connect to database!" . "<br><br>";
echo $e->getMessage();
}
?>
and here is my search form which is in the header.php
<form class="form-inline" action="search.php" method="POST">
<input class="form-control" name="search" id="search" type="text" placeholder="Search">
</form>
you're using: $query = $pdo->prepare
It should be:
$query = $conn->prepare()
Because I am a lazy coder I made a new class to save a bit of time:
class DBCommon
{
private $conn;
/** #var Common */
public $common;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}

PHP - Search Using Form and Return Back Records

I am working in PHP/HTML/SQLITE3. I have a database that consist of several tables, one of the tables is called Item, which contains an itemID, name of item, and so forth. So my search takes the user input of the itemID and what I am suppose to return back is everything associated with that itemID.
I have tested out my search and it does return back the itemID, however, I am having a bit of trouble figuring out how to return back everything related to the itemID. Down below are my search form and what I have for a seperate file which contains the query.
<form method="POST" action="action.php">
<input name="search" type="text" size="20" maxlength="10"/>
<input type="submit" value="Search"/>
</form>
-----
<?php
if (isset($_POST["search"])) {
$itemID = $_POST["search"];
try {
$db->beginTransaction();
$query = "SELECT * FROM Item WHERE itemID = '$itemID';";
$result = $db->query($query);
if (empty($_POST['search'])){
echo "<strong>You didn't fill in anything!</strong>";
}
else {
echo $itemID;
}
$db->commit();
}
$db = null;
?>
Edit Code (Addition of attempt at fetchall):
<?php
if (isset($_POST["search"])) {
$itemID = $_POST["search"];
try {
$db->beginTransaction();
$query = "SELECT * FROM Item WHERE itemID = '$itemID';";
#$result = $db->query($query);
$result = sqlite_fetch_all($query, SQLITE_ASSOC);
foreach($result as $entry) {
echo 'ItemID: ' . $entry['itemID'] . ' Item Name' . $entry['name'];
}
if (empty($_POST['search'])){
echo "<strong>Esteemed customer did not fill in a
itemID number, please search again. </strong>";
}
$db->commit();
}
2nd Attempt:
<?php
$dbname = "mydatabase.db";
try {
// Establish connection to "mydatabase.db"
$db = new PDO("sqlite:" . $dbname);
// Set error handling so that errors throw an exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Enable foreign key constraints on the database
$db->exec("PRAGMA foreign_keys = ON;");
} catch (PDOException $e) {
echo "SQLite connection failed: " . $e->getMessage();
exit();
}
if (isset($_POST["search"])) {
$itemID = $_POST["search"];
try {
$sth = $db->prepare("SELECT * FROM Item WHERE itemID = '$itemID'");
#$query = "SELECT * FROM Item WHERE itemID = '$itemID';";
#$result = $db->query($query);
$sth->execute();
$result = $sth->fetchAll();
print_r($result);
#if (empty($_POST['search'])){
#echo "<strong>Esteemed customer did not fill in a
#itemID number, please search again. </strong>";
}
}
?>
Any input would be greatly appreciated.
You should concatenate the itemid to the query
$query = "SELECT * FROM Item WHERE itemID = '" . $itemID . "';";

Run a call from a function PHP

i'm building an website using php and html, im used to receiving data from a database, aka Dynamic Website, i've build an CMS for my own use.
Im trying to "simplify" the receiving process using php and functions.
My Functions.php looks like this:
function get_db($row){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$row = $stmt->fetchAll();
foreach ($row as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Where i will get the rows content like this: $row['row'];
I'm trying to call it like this:
the snippet below is from the index.php
echo get_db($row['session_id']); // Line 22
just to show whats in all the rows.
When i run that code snippet i get the error:
Notice: Undefined variable: row in C:\wamp\www\Wordpress ish\index.php
on line 22
I'm also using PDO just so you would know :)
Any help is much appreciated!
Regards
Stian
EDIT: Updated functions.php
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Instead of echoing the values from the DB, the function should return them as a string.
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = '';
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result .= $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then call it as:
echo get_db();
Another option would be for the function to return the session IDs as an array:
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = array();
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result[] = $row['session_id'];
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then you would use it as:
$sessions = get_db(); // $sessions is an array
and the caller can then make use of the values in the array, perhaps using them as the key in some other calls instead of just printing them.
As antoox said, but a complete changeset; change row to rows in two places:
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
Putting this at the start of the script after <?php line will output interesting warnings:
error_reporting(E_ALL|E_NOTICE);
To output only one row, suppose the database table has a field named id and you want to fetch row with id=1234:
$stmt = $pdo->prepare("SELECT * FROM lp_sessions WHERE id=?");
$stmt->bindValue(1, "1234", PDO::PARAM_STR);
I chose PDO::PARAM_STR because it will work with both strings and integers.

Categories