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.
Related
This is my HTML code:
<input type='checkbox' name='cbox[]' value='Jaywalking'/>
Jaywalking<br/>
<input type='checkbox' name='cbox[]' value='Littering'/>
Littering<br/>
<input type='checkbox' name='cbox[]' value='Illegal Vendor'/>
Illegal Vendor
This is my posting code:
if(is_array($_POST['cbox']))
$violation_save=implode(',',$_POST['cbox']);
else
$violation_save=$_POST['cbox'];
mysql_query("UPDATE tblcitizen SET violation='$violation_save' WHERE id='$id'") or die mysql_error());
How can I fetch the selected values from the database?
First of all you should NOT use the mysql_* functions of php anymore. These functions are marked as deprecated and will be removed in the next major php release.
So if $_POST['cbox'] is an array, you must handle it as an array.
// how to save checked values
try {
$db = new PDO(...);
$stmt = $db->prepare("UPDATE yourTable SET myField = :myField WHERE id = :id");
$stmt->bindParam(':id' , $id, PDO::PARAM_INT);
foreach ($_POST['cbox'] as $myField) {
$stmt->bindParam(':myField', $myField);
$stmt->execute();
}
} catch (PDOException $e) {
// error handling
}
// how to fetch checked values
try {
$myValues = array();
$db = new PDO(...);
$stmt = $db->prepare("SELECT myField FROM myTable WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$myValues[] = $row['myField'];
}
} catch (PDOException $e) {
// error handling
}
// HTML Part
<input type="checkbox" name="cbox[]" value="bla"<?php if (in_array('bla', $myValues)) { ?> checked="checked"<?php } ?> />
Just have a look at the php manual for PDO or the MySQLi extension.
I'm attempting to use functions to get certain data from database. For example, I want to get info from an user with ID 1.
try {
$connection = new PDO("mysql:host=localhost;dbname=database", "root", "password");
}
catch (PDOException $e) {
die("Error: " . $e->getMessage());
}
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function getUser($id) {
global $connection;
$query = $connection->prepare("SELECT * FROM accounts WHERE ID = '$id'");
$query->execute();
while($row = $query->fetch()) {
echo $row['playername'];
$user[] = $row;
}
}
And then in my index.php.
include 'inc/db.php';
getUser("1");
foreach($user AS $user) {
echo $user['ID'];
}
The first echo works, I get the username displayed, but the foreach doesn't echo anything. I tried to var_dump($user); but ended up getting NULL.
You need to have:
function getUser(...) {
...
$user = array();
while(...) {
$user[] = $row;
}
return $user;
}
And then in your main code:
$users = getUser(1);
foreach($users as $user) { .... }
Right now you're defining local variables and then not returning them, so they're lost when the method exits. And then not capturing any possible returned values anyways, making your code basically pointless.
Your problem is that you are writing too much code. PHP can't process so much, chokes and dies.
All you actually need is
$pdo = new PDO("mysql:host=localhost;dbname=database", "root", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
function getUser($id)
{
global $pdo;
$query = $pdo->prepare("SELECT * FROM accounts WHERE ID = ?");
$query->execute(array($id));
return $query->fetch();
}
$user = getUser(1);
echo $user['playername'];
to make it little more serious, you should use prepared statement to pass variable into query and return data from the function.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How can I put those two code snippets in a class so the databasehandling is in a class? Like a PDO connection or put all that have to do with database is in a class, how would you guys do it?
Here are two parts of the code from different files. I am trying to develop a blog application.
<?php
mysql_connect("localhost", "root", "")or die(mysql_error());
mysql_select_db("blogg1")or die(mysql_error());
if(isset($_POST["submit"])){
$title = $_POST["title"];
$category = $_POST["category"];
$content = $_POST ["content"];
mysql_query("INSERT INTO blogdata(title , category , content) VALUES('$title', '$category', '$content')");
}else{
?>
<?php
mysql_connect("localhost", "root", "")or die(mysql_error());
mysql_select_db("blogg1")or die(mysql_error());
$sql = mysql_query("SELECT * FROM blogdata ORDER BY id DESC")or die(mysql_error());;
while($row = mysql_fetch_array($sql)){
$title = $row["title"];
$category = $row["category"];
$content = $row["content"];
?>
<table border = "1">
<tr><td><?php echo $title; ?></td><td><?php echo $category; ?></td></tr>
<tr><td colspan="2"><?php echo $content; ?></td></tr>
</table>
<?php
}
?>
First, you should keep your database credentials in a separate PHP file in a folder not accessible by the web, for example ~/lib/db.php
<?php
define('SQL_HOST', 'localhost');
define('SQL_DATABASE', 'your-db-name');
define('SQL_USER', 'your-db-user');
define('SQL_PASS', 'your-db-password');
?>
Then your Database class (also in ~/lib):
<?php
require_once('~/lib/db.php');
require_once('~/lib/BlogData.php');
class Database
{
protected $db = null;
function __construct()
{
// db connection options
$driverOptions = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_EMULATE_PREPARES => false
);
// set new connection
$this->db = PDO(
"mysql:dbname=".SQL_DATABASE.";host=".SQL_HOST,
SQL_USER, SQL_PASS, $driverOptions
);
}
// This function lets you fetch blog data using any sort order you'd like and any WHERE criteria you want
function getBlogData($where = "1", $orderBy = "id DESC")
{
$stmt = $this->db->prepare("
SELECT *
FROM {'blogdata'} WHERE $where
ORDER BY $orderBy
");
$blogData = Array();
if ($stmt->execute())
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$oneBlogData = new BlogData($this);
$oneBlogData->init($row);
$blogData[] = $oneBlogData;
}
}
return $blogData;
}
function insertBlogData(BlogData $blogData)
{
$stmt = $this->db->prepare("
INSERT INTO {'blogdata'} (title , category , content) VALUES
(:title, :category, :content);
");
$stmt->bindParam(':title', $blogData->title, PDO::PARAM_STR);
$stmt->bindParam(':category', $blogData->category, PDO::PARAM_STR);
$stmt->bindParam(':content', $blogData->content, PDO::PARAM_STR);
$stmt->execute();
}
}
?>
Then I would define another class for your blog data:
<?php
class BlogData {
public $title;
public $category;
public $content;
private $db;
function __construct(Database $db)
{
$this->db = $db;
}
function init($dbRow)
{
$this->title = $dbRow['title'];
$this->category = $dbRow['category'];
$this->content = $dbRow['content'];
}
function save()
{
// TODO: Write sql statement to save the row...
}
}
?>
Then your first block of code could create a new BlogData entry like this:
<?php
require_once('~/lib/Database.php');
$db = new Database();
if(isset($_POST["submit"]))
{
$blogData = new BlogData($db);
$blogData->title = $_POST["title"];
$blogData->category = $_POST["category"];
$blogData->content = $_POST["content"];
$db->insertBlogData($blogData);
}
?>
And your second block of code could look like this:
<?php
require_once('~/lib/Database.php');
$db = new Database();
$blogDataArray = $db->getBlogData("1", "id DESC");
echo "<table border = '1'>";
foreach($blogDataArray as $blogData)
{
echo "<tr><td>" . $blogData->title . "</td><td>" . $blogData->category . "</td></tr>";
echo "<tr><td colspan='2'>" . $blogData->content . "</td></tr>";
}
echo "</table>";
?>
This also makes it really easy to modify BlogData entries - just fetch the blog data from the Database using the getBlogData function, modify the object by simply changing it's values and calling save. For example:
<?php
// ...
$newContent = "New Content";
$blogData = $db->getBlogData("id='1'");
$blogData->content = $newContent;
$blogData->save();
?>
I should also point out the obvious that you need some unique field for your blog data entries. With some id, it'd be easier to write addToDatabase and save in one function.
Please see below for the code example:
class SomeClass {
protected $db = null;
protected $table = 'blogdata';
public function __construct()
{
// db connection options
$driverOptions = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
);
// set new connection
$this->db = PDO(
"mysql:dbname=blogg1;host=localhost",
'root', '', $driverOptions
);
}
public function save($data)
{
// prepare your data
$title = $data["title"];
$category = $data["category"];
$content = $data ["content"];
// prepare statement
$stmt = $this->db->prepare("
INSERT INTO {$this->table} (title , category , content) VALUES
(:title, :category, :content);
");
$stmt->bindParam(':title', $title, PDO::PARAM_STR);
$stmt->bindParam(':category', $category, PDO::PARAM_STR);
$stmt->bindParam(':content', $content, PDO::PARAM_STR);
$stmt->execute();
}
public function getRecords()
{
$stmt = $this->db->prepare("
SELECT *
FROM {$this->table}
ORDER BY id DESC
");
$stmt->execute();
return $stmt->fetchAll();
}
}
And a usage example:
<?php
require_once('SomeClass.php');
$ent = new SomeClass();
if (isset($_POST["submit"])) {
$ent->save($_POST);
}
else {
// get and output
$records = $ent->getRecords();
if (count($records) > 0) {
?>
<table>
<?php
foreach ($records as $record) {
echo "<tr><td>{$record->title}</td><td>{$record->category}</td></tr>
<tr><td colspan='2'>{$record->content}</td></tr>";
}
?>
</table>
I'm tinkering with a class that 'should' allow me to easily execute a fetchall query and display the results within a foreach statement. I assume all is working correctly as I have no errors. As for the foreach - this must be the problem? How would I foreach the results gained from the $connect->query()? I'm new to using any database OOP framework in my functions so I could be along the wrong lines completely.
<?
error_reporting(1);
class dbconnect {
private $host;
private $database;
private $username;
private $password;
private $pdo;
private $error;
public function __construct() {
$this->host = "localhost"; // Host
$this->database = "images"; // Database Name
$this->username = "*"; // Username
$this->password = "*"; // Password
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
);
try {
$this->pdo = new PDO("mysql:host={$this->host};dbname={$this->dbname};charset=utf8", $this->username, $this->password, $options);
}
catch(PDOException $e) {
$this->error = $e->getMessage();
}
}
public function query($query) {
try {
$stmt = $this->pdo->prepare($query);
$stmt->execute();
} catch(PDOException $ex) {
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
return $rows;
}
}
$connect = new dbconnect;
$rows = $connect->query("select * from photos");
foreach($rows as $row):
print $row['id'];
endforeach;
?>
The $rows variable you're declaring inside query is not accessible to the outside, it is local to that function. Most likely, you simply want to return those results to the caller:
$rows = $stmt->fetchAll();
return $rows; // return value from function...
and have the caller capture that return value in its own variable:
$rows = $connect->query("select * from images"); // ... is received by caller
foreach($rows as $row):
Also check out dougjore's answer, you're mixing $this->stmt and $stmt inside your query method.
Pretty sure you aren't ever actually executing the query:
$this->stmt = $this->pdo->prepare($query);
$stmt->execute();
I believe (I could be wrong, I'm rather new to PDO myself and I haven't built a class for it), that you need to say $this->stmt->execute();
You could do
//PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set
$this->stmt = $this->pdo->prepare($query);
$this->stmt->execute();
while ($result = $this->stmt->fetch(PDO::FETCH_ASSOC))
{
//do something with the result
}
Have a look here for more options to fetch PDO query results:
http://php.net/manual/en/pdostatement.fetch.php
$connect = new dbconnect;
$sql="select * from photos";
$stmt=$connect->pdo->prepare($sql);
$stmt->execute();
$result=$stmt->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
echo $key . "-" . $value . "<br/>";
}
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);
}