I currently have a HTML search form which takes the users input (for example 123456) and using PHP searches a database to see if that number exists as an item number. It then returns information on that item in a table.
Is it possible to search for multiple items at once for example 123456, 654321, 000000 and have the results for each displayed in a table ? I currently have not been able to find any documentation on how I could achieve this. Any help would be greatly appreciated.
My current code which searches and brings back the data for one item is.
<div id="div1">
<!-- [SEARCH FORM] -->
<form method="post" action="nweb.php">
<h1>Product Information</h1>
<input type="text" name="search" required/>
<input type="submit" value="Search"/>
</form>
<?php
if (isset($_POST['search'])) {
require "2-search.php";
if (count($results) > 0) {
foreach ($results as $r) {
echo "<table>";
echo "<tr><td>Item number</td><td>" . $r['item_number'] . "</td></tr>";
echo "<tr><td>Stock available</td><td>" . $r['stock_available'] . "</td></tr>";
echo "<tr><td>Available Stock</td><td>" . $r['available_stock'] . "</td></tr>";
echo "<tr><td>Detailed Description</td><td>" . $r['detailed_desc'] . "</td></tr>";
echo "<tr><td>Gender</td><td>" . $r['gender'] . "</td></tr>";
echo "<tr><td>Group</td><td>" . $r['group'] . "</td></tr>";
echo "<tr><td>Subgroup</td><td>" . $r['sub_group'] . "</td></tr>";
}
echo "</table>";
} else {
echo "No results found";
}
}
?>
</div>
My search code is.
try {
$pdo = new PDO(
"sqlsrv:Server=$server;Database=$database", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$stmt = $pdo->prepare ("SELECT * FROM dbo.[data] WHERE [item_number] LIKE ? OR [stock_available] LIKE ?");
$stmt->execute(["%" . $_POST['search'] . "%", "%" . $_POST['search'] . "%"]);
$results = $stmt->fetchAll();
if (isset($_POST['ajax'])) { echo json_encode($results); }
?>
One simple way, without too many drastic changes in your code, would be to choose a separator (maybe a comma) and write your items like that, then, you'd separate these items into an array of search items:
$searchFor = explode(',', $_POST['search']);
And search for them one by one:
$resultsArray = [];
foreach ($searchFor as $searchItem){
$stmt = $pdo->prepare ("SELECT * FROM dbo.[data] WHERE [item_number] LIKE ? OR [stock_available] LIKE ?");
$stmt->execute(["%" .$searchItem . "%", "%" . $searchItem . "%"]);
$results = $stmt->fetchAll();
array_push($resultsArray, $results);
}
Finally, you'd echo the tables almost the same way you did until now:
foreach ($resultsArray as $results) {
...
foreach ($results as $r) {
...
Related
i am working on a project, in which i want to use Categories and their Sub and Child categories, i've created 3 tables ( MainCats, SubCats, ChildCats ).
now i want to fetch data from those tables and want to store in option of HTML.
Here is code PHP, MYSQLI and HTML code.
$cat_fetch = "SELECT categories, sub_categories, child_categories FROM categories.maincatSd, sub_categories.subcat_name, child_categories.child_cat_name";
$cat_run = mysqli_query($con, $cat_fetch);
echo "<option value='' >ڪيٽيگري چونڊيو</option>";
if(mysqli_num_rows($cat_run) >0){
while($cat_row = mysqli_fetch_array($cat_run)){
$cat_name = $cat_row['child_cat_name'];
$cat_name = $cat_row['subcat_name'];
$cat_name = $cat_row['maincatSd'];
//$cat_name = $cat_row['subcat_name'];
echo "<option value='".$cat_name."' ".((isset($Catagory) and $Catagory == $cat_name)?"selected":"")." >".ucfirst($cat_name)."</option>";
}
}else{
echo "<option name='Catagory' tabindex='2' id='Catagory' value=''>NoCat</option>";
}
From the output of your given image.. I don't feel you need to maintain any kind of relation at the time of fetching records from tables. It just needs to fetch records from those three tables & build the options list & print show on the web page. If that's exactly what you want, then check out this.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Connect to DB
$mysqli = new mysqli('127.0.0.1', 'host', 'password', 'DB_Name');
if ($mysqli->connect_errno) {
echo "Error: Failed to make a MySQL connection, here is why: \n";
echo "Errno: " . $mysqli->connect_errno . "\n";
echo "Error: " . $mysqli->connect_error . "\n";
exit;
}
// ---Fetch all main category records---
$sql = "SELECT * FROM main_cat";
if (!$result = $mysqli->query($sql)) {
echo "Errno: " . $mysqli->errno . "\n";
echo "Error: " . $mysqli->error . "\n";
exit;
}
$totRecordsMainCat= array();
if($result->num_rows){
while($dataSource = $result->fetch_assoc()){
$totRecordsMainCat[] = $dataSource;
}
}
// ---Fetch all Sub category records---
$sql = "SELECT * FROM sub_cat";
if (!$result = $mysqli->query($sql)) {
echo "Errno: " . $mysqli->errno . "\n";
echo "Error: " . $mysqli->error . "\n";
exit;
}
$totRecordsSubCat= array();
if($result->num_rows){
while($dataSource = $result->fetch_assoc()){
$totRecordsSubCat[] = $dataSource;
}
}
// ---Fetch all Child category records---
$sql = "SELECT * FROM child_cat";
if (!$result = $mysqli->query($sql)) {
echo "Errno: " . $mysqli->errno . "\n";
echo "Error: " . $mysqli->error . "\n";
exit;
}
$totRecordsChildCat= array();
if($result->num_rows){
while($dataSource = $result->fetch_assoc()){
$totRecordsChildCat[] = $dataSource;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
echo "<select>";
echo "<option value=''>Select Category</option>";
foreach ($totRecordsMainCat as $key => $value)
{
$cat_name = $value['cat_name'];
echo "<option value='$cat_name'>$cat_name</option>";
}
foreach ($totRecordsSubCat as $key => $value)
{
$cat_name = $value['subcat_name'];
echo "<option value='$cat_name'>$cat_name</option>";
}
foreach ($totRecordsChildCat as $key => $value)
{
$cat_name = $value['childcat_name'];
echo "<option value='$cat_name'>$cat_name</option>";
}
echo "</select>";
?>
</body>
</html>
Why not do it using 3 different queries and nested loops..
SELECT * FROM main_cat
// Loop query result
SELECT * FROM sub_cat WHERE sub_cat_id = main_cat_id
// Loop query result
SELECT * FROM child_cat WHERE child_cat_id = sub_cat_id
// Loop query results
I been trying to implement PDO with prepare(), bindParam() and execute() functions to allow a query to be constructed from data entered by the user.
I wanted to display the list of books and then allow the user to filter the list and then see the new list and the full list.
When I enter criteria into the form to search nothing happens. What am I overlooking?
here is the code
<?php
$pageTitle = "Book List";
$pageHeading = "Book List";
include_once ('header.php');
include_once('databaseConnection.php');
if(isset($_POST['txtSearchBookTitle'])) {
$db = new DatabaseConnection();
$db = $db->db_connection;
$searchTitle = ($_POST['txtSearchBookTitle']);
$sql = $db->prepare("SELECT title FROM tblBook WHERE title LIKE ('%:searchTitle%') ORDER BY title");
$sql->bindParam(':searchTitle', $searchTitle);
$sql->execute();
$result = $sql->fetchAll();
print_r($result);
foreach ($result as $row) {
echo "<li>" . " " . $row["title"]. " " . "</li>";
}
}
?>
<form name="searchBookTitle" method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>" >
<fieldset>
<legend>Search Books</legend>
<label for="txtSearchBookTitle">Search by Book Title</label>
<input type="text" name="txtSearchBookTitle" id="txtSearchBookTitle">
<input type="submit" value="Submit">
</fieldset>
</form>
<?php
include_once('getBooks.php');
getBooks();
include 'footer.php';
?>
You need to prepare the inputs this way:
$searchTitle = $_POST['txtSearchBookTitle'];
$sql = $db->prepare("SELECT title FROM tblBook WHERE title LIKE :searchTitle ORDER BY title");
$sql->execute(array(':searchTitle' => '%' . $searchTitle . '%'));
Or like this:
$searchTitle = $_POST['txtSearchBookTitle'];
$sql->bindParam(':searchTitle', "%{$searchTitle}%");
Use PDO::FETCH_ASSOC in your fetchAll.. it means it will return the data as an array
So make it like this one
$result = $sql->fetchAll(PDO::FETCH_ASSOC);
usually i help people with whatever they need, this time i'm asking for your help.
i'm trying to get a specific row from my database after preforming multiple checkbox select i spend 50 hours on that and i couldn't manage to do that.
each time i'm changing something in my code i get a different ERROR.
i was looking for an answer in every HTML page that exist on the INTERNET !
please show me the light..
here is a part of my form.... value means "size" of the toy
<div class=""><input type="checkbox" name="toys[]" value="6X2" /><label></label></div>
<div class=""><input type="checkbox" name="toys[]" value="4X3" /><label></label></div>
<div class=""><input type="checkbox" name="toys[]" value="8X2.5" /><label></label></div></strike>
here is the PHP code...
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
}
}
$query = $db->query = 'SELECT * FROM `toys` WHERE SIZE = '.$each_check;
echo "<table>";
echo "<tr>
<th>ratio</th>
<th>size</th>
<th>built</th>
<th>description</th>
</tr>";
while ($row = $query->fetch(PDO::FETCH_ASSOC))
echo "<tr><td>" . $row['ratio'] .
"</td><td>" . $row['size'] .
"</td><td>" . $row['built'] .
"</td><td>" . $row['description'] .
"</td></tr>";
echo "</table>";
This is so very far from being valid:
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
}
}
$query = $db->query = 'SELECT * FROM `toys` WHERE SIZE = '.$each_check;
More like:
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
$query = $db->query("SELECT * FROM `toys` WHERE SIZE = '".$each_check."'");
}
}
But should be more like:
if (isset($_POST['toys'])) {
$query = 'SELECT * FROM `toys` WHERE SIZE = ?';
$sth = $db->prepare($query);
foreach($_POST['toys'] as $each_check) {
if( ! $sth->execute(array($each_check)) ) {
die('MySQL Error: ' . var_export($sth->error_info(), TRUE);
}
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
// code here
}
}
}
You're assigning $db->query instead of using it as a function. Change your query line to this:
$query = $db->prepare('SELECT * FROM `toys` WHERE SIZE = :size');
$query->bindValue(':size',$each_check);
$query->execute();
Also, you're going through $_POST['toys'], but not assigning it to any value. I'm guessing you want to add all of your query and table code within the foreach.
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
// put everything else here
}
}
I want to suggest that you use MySQL's IN (...) clause in your WHERE condition to retrieve all the rows with matching 'size' in just 1 query:
SELECT * FROM toys WHERE size IN ( $chosenSizes )
To get the list of sizes, use PHP's implode function:
$chosenSizes = implode(', ', $_POST['toys']);
You can then use PDO's fetchAll to fetch all rows into a result array.
$resultRows = $sth->fetchAll();
Note: Only use this method when you are quite certain that the result arrays is not too big!
Hagay, the following should work for you:
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'my_name', 'my_pass');
if (isset($_POST['toys'])) {
$sizes = implode(', ', array_map(array($pdo, 'quote'), $_POST['toys']));
$sql = "SELECT * FROM toys WHERE size IN (" . $sizes . ")";
echo '<table>', PHP_EOL;
echo '<tr><th>ratio</th><th>size</th></tr>', PHP_EOL;
foreach( $pdo->query($sql) as $row ) {
echo '<tr><td>', $row['ratio'], '</td><td?', $row['size'], '</td></tr>', PHP_EOL;
}
echo '</table>', PHP_EOL;
}
The following code:
<?php
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
echo "Connection is successful!<br/>";
$sql = "SELECT * FROM users";
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
$dbh = null;
}
catch (PDOexception $e) {
echo "Error is: " . $e-> etmessage();
}
Output:
Connection is successful!
person A-male
person B-female
Running "foreach" twice is not my purpose, I'm just curious why TWO "foreach" statements only output the result once?
Following is the similar case:
<?php
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
echo "Connection is successful!<br/>";
$sql = "SELECT * FROM users";
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
$result = $users->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
echo $key . "-" . $value . "<br/>";
}
$dbh = null;
}
catch (PDOexception $e) {
echo "Error is: " . $e-> etmessage();
}
Output:
Connection is successful!
person A-male
person B-female
SCREAM: Error suppression ignored for
Warning: Invalid argument supplied for foreach()
But when I delete the first "foreach" from the above codes, the output will become normal:
<?php
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
echo "Connection is successful!<br/>";
$sql = "SELECT * FROM users";
$users = $dbh->query($sql);
echo "<br/>";
$result = $users->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
echo $key . "-" . $value . "<br/>";
}
$dbh = null;
}
catch (PDOexception $e) {
echo "Error is: " . $e-> etmessage();
}
Output:
Connection is successful!
user_id-0000000001
name-person A
sex-male
Why does this happen?
A PDOStatement (which you have in $users) is a forward-cursor. That means, once consumed (the first foreach iteration), it won't rewind to the beginning of the resultset.
You can close the cursor after the foreach and execute the statement again:
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . " - " . $row["sex"] . "<br/>";
}
$users->execute();
foreach ($users as $row) {
print $row["name"] . " - " . $row["sex"] . "<br/>";
}
Or you could cache using tailored CachingIterator with a fullcache:
$users = $dbh->query($sql);
$usersCached = new CachedPDOStatement($users);
foreach ($usersCached as $row) {
print $row["name"] . " - " . $row["sex"] . "<br/>";
}
foreach ($usersCached as $row) {
print $row["name"] . " - " . $row["sex"] . "<br/>";
}
You find the CachedPDOStatement class as a gist. The caching iterator is probably more sane than storing the result set into an array because it still offers all properties and methods of the PDOStatement object it has wrapped.
Executing the same query again only to get the results you already had, as suggested in the accepted answer, is a madness. Adding some extra code to perform such a simple task also makes no sense. I have no idea why people would devise such complex and inefficient methods to complicate such primitive, most basic actions.
PDOStatement is not an array. Using foreach over a statement is just a syntax sugar that internally uses the familiar one-way while loop. If you want to loop over your data more than once, simply select it as a regular array first
$sql = "SELECT * FROM users";
$stm = $dbh->query($sql);
// here you go:
$users = $stm->fetchAll();
and then use this array as many times as you need:
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
Also quit that try..catch thing. Don't use it, but set the proper error reporting for PHP and PDO
This is because you are reading a cursor, not an array. This means that you are reading sequentially through the results and when you get to the end you would need to reset the cursor to the beginning of the results to read them again.
If you did want to read over the results multiple times, you could use fetchAll to read the results into a true array and then it would work as you are expecting.
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
Here $users is a PDOStatement object over which you can iterate. The first iteration outputs all results, the second does nothing since you can only iterate over the result once. That's because the data is being streamed from the database and iterating over the result with foreach is essentially shorthand for:
while ($row = $users->fetch()) ...
Once you've completed that loop, you need to reset the cursor on the database side before you can loop over it again.
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
$result = $users->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
echo $key . "-" . $value . "<br/>";
}
Here all results are being output by the first loop. The call to fetch will return false, since you have already exhausted the result set (see above), so you get an error trying to loop over false.
In the last example you are simply fetching the first result row and are looping over it.
$row = $db->getAllRecords(DB_TBLPREFIX . '_payplans', '*', ' AND ppid = "' . $myid . '"');
foreach ($row as $value) {
$bpprow = array_merge($bpprow, $value);
}
This is based on PHP functions where you can globally use this data.
I have a simple program that I am trying to implement some sort of pagination/capability to navigate through individual records in a MySQL database. The code itself calls a function that returns an associative array so that the records may be navigated sequentially in the case of non-sequential indices being made by deletes.
function getKeys($handle, $user, $password) {
try {
$conn = new PDO($handle,$user,$password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Error connectiong to database. Error: (" . $e -> getMessage() . ")";
}
$sql = "Select Workstation_ID from Workstation";
$result = $conn -> query($sql);
$resultArray = array();
while ( $row = $result -> fetch()) {
$resultArray[] = $row;
}
$conn = null;
return $resultArray; }
I am attempting to store the result from this function into a variable and from there try to increment that variable for use in an other function:
$Keys = getKeys($dsn,$un,$pw);
$i = 0;
$currID = $Keys[$i][0];
$row = getResultSet($dsn,$un,$pw,$currID);
I would then use the $row to display the current workstation :
echo "<hr class='viewHR'>";
echo "</br></br><div class='viewFormat'>";
echo "<form name = 'updateWorkstationForm' action ='updateWorkstation.php' method ='post'>";
echo "<b>Workstation Name:</b><br><input type = 'Textbox' name = 'pcName' value = '" . $row['Workstation_Name'] . "'/></br>";
echo "<b>Serial Number: </b><br> <input type = 'Textbox' name = 'SN' value = '" . $row['Serial_Number'] . "'/></br>";
echo "<b>Model</b></br>";
echo "<select name ='modelSelect'>";
echo "<option value = '".$row['Model_ID'] . "'>" . $row['Model'] . "</option>";
echo "</select></br>";
echo "<b>Department</b></br>";
echo "<select name ='DepartmentSelect'>";
echo "<option value = '".$row['Department_ID'] . "'>" . $row['Department'] . " </option>";
echo "</select></br>";
I was wondering if I was going about this completely wrong or how I would approach incrementing the array's index to display each record on a click of an anchor tag or button the whole file is as follows :
<html>
<body>
<div>
<?php
$un = "xxx";
$pw = "xxxxxx";
$dsn = "mysql:host=127.0.0.1;dbname=xxxxxxxxxxx";
$Keys = getKeys($dsn,$un,$pw);
$i = 0;
$currID = $Keys[$i][0];
$row = getResultSet($dsn,$un,$pw,$currID);
echo "<hr class='viewHR'>";
echo "</br></br><div class='viewFormat'>";
echo "<form name = 'updateWorkstationForm' action ='updateWorkstation.php' method = 'post'>";
echo "<b>Workstation Name:</b><br> <input type = 'Textbox' name = 'pcName' value = '" . $row['Workstation_Name'] . "'/></br>";
echo "<b>Serial Number: </b><br> <input type = 'Textbox' name = 'SN' value = '" . $row['Serial_Number'] . "'/></br>";
echo "<b>Model</b></br>";
echo "<select name ='modelSelect'>";
echo "<option value = '".$row['Model_ID'] . "'>" . $row['Model'] . "</option>";
echo "</select></br>";
echo "<b>Department</b></br>";
echo "<select name ='DepartmentSelect'>";
echo "<option value = '".$row['Department_ID'] . "'>" . $row['Department'] . "</option>";
echo "</select></br>";
echo "<b>Room</b></br>";
echo "<select name ='RoomSelect'>";
echo "<option value = '".$row['Room_ID'] . "'>" . $row['Room'] . "</option>";
echo "</select></br>";
echo "<b>Property Status</b> </br>";
echo "<select name = 'propertyStatus'>";
echo "<option value = '".$row['Property_Status_ID'] . "'>" . $row['Property_Status'] . "</option>";
echo "</select></br>";
if ($row['Property_Status'] != "Owned"){
echo "<b>Lease Company:</b> ";
echo "<select name = leaseSelect>";
echo "<option value = '" . $row['Lease_Info_ID'] ."'>Company:" . $row['Company'] . ", Start: " . $row['Start_Date'] . "End: " .$row['End_Date'] . "</option>";
echo "</select></br>";
}
echo "<b>Cart</b></br>";
echo "<select name ='cartSelect'>";
echo "<option value = '".$row['Cart_ID'] . "'>" . $row['Cart_Type'] . "</option>";
echo "</select></br>";
echo "<b>Workstation Comments: </b><br> <Textarea rows='5' cols='60' name = 'wsComments'> ". $row['Workstation_Comment'] . " </Textarea></br>";
echo "<b>Location Comments: </b><br> <Textarea rows='5' cols='60' name = 'locComments'> ". $row['Workstation_Comment'] . " </Textarea></br>";
echo "<input type = 'submit' value = 'Update' />";
echo "<input type = 'button' value = 'Cancel' onclick = 'location.reload(this);' />";
echo "</form>";
echo "</div>";
/*Function to return a parallel array. This is so that non-sequential records in the database may be described sequentially with the help of an array's indices*/
function getKeys($handle, $user, $password) {
try {
$conn = new PDO($handle,$user,$password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Error connectiong to database. Error: (" . $e -> getMessage() . ")";
}
$sql = "Select Workstation_ID from Workstation";
$result = $conn -> query($sql);
$resultArray = array();
while ( $row = $result -> fetch()) {
$resultArray[] = $row;
}
$conn = null;
return $resultArray;
}
function getResultSet($handle, $user, $password, $ID) {
$resultSet = "";
try {
$conn = new PDO($handle,$user,$password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Error connectiong to database. Error: (" . $e -> getMessage() . ")";
}
$sql = "Select Workstation.Workstation_ID,Workstation.Model_ID,Workstation.Property_Status_ID,workstation.Lease_Info_ID, Workstation.Workstation_Name, Workstation.Serial_Number, Model.Model, Department.Department,Room.Room,Property_Status.Property_Status,Lease_Info.Start_Date,Lease_Info.End_Date,Lease_Info.Company,Lease_Info.Lease_Comment,Cart.Cart_Type,Workstation.Workstation_Comment,Workstation.Location_Comment from Workstation INNER JOIN Model ON Workstation.Model_ID = Model.Model_ID INNER JOIN Department ON Workstation.Department_ID = Department.Department_ID INNER JOIN Room ON Workstation.Room_ID = Room.Room_ID INNER JOIN Property_Status ON Workstation.Property_Status_ID = Property_Status.Property_Status_ID INNER JOIN Lease_Info ON Workstation.Lease_Info_ID = Lease_Info.Lease_Info_ID INNER JOIN Cart ON Workstation.Cart_ID = Cart.Cart_ID where Workstation_ID = :ID";
$pstmt = $conn -> prepare($sql);
if(!$pstmt) {
echo "Error preparing the statement. Error: (" . $conn -> ErrorInfo() . ")";
}
$pstmt -> bindParam(':ID', $ID);
try {
$pstmt -> execute();
}
catch(PDOException $e) {
echo "Failed to execute prepared Statement. Error: (" . $e -> getmessage() . ")";
}
$resultSet = $pstmt -> fetch();
return $resultSet;
$conn = null;
}
?>
</div>
</body>
</html>
Any criticism, insight, or pointers would be greatly appreciated.
You shouldn’t be fetching all records if you only intend to display a subset, or just one.
To paginate, use the LIMIT clause. So, if you split records into pages of ten, then to get the first page your query would be:
SELECT * FROM workstations LIMIT 0,10
Where the first number is the offset, and the second number is the number of records after the offset you wish to fetch. To fetch the second page, you’d change the limit clause to be LIMIT 10,10; to fetch the third page LIMIT 20,10, and so on. The PHP equation is:
$offset = (($page - 1) * $records_per_page);
The page value can come from a $_GET variable, like http://www.example.com/?page=1.
Secondly, if you’re only wanting to display one record, then fetch that one:
SELECT * FROM workstations WHERE id = ? LIMIT 1
Pass the ID via a $_GET parameter again, and use PDO to bind it to avoid SQL injection vulnerabilities:
<?php
$sql = "SELECT * FROM workstations WHERE id = :id LIMIT 1";
$sth = $db->prepare($sql);
$sth->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
$sth->execute();
$row = $sth->fetchObject();