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);
Related
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) {
...
In my code, I have two forms for users to select options. The first variable will save but as soon as the user submits the second form, the variable from the first form is no longer saved.
<div class = "school">
<h3>Please select the university you previously attended</h3>
<form action = "" method = "post" name = "school_form">
<select name="school" size ="10">
<?php
//shows options for $selected_school
$sql = "SELECT DISTINCT school FROM data;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0){
while($row = mysqli_fetch_assoc($result)){
// inserts all data as array
echo "<option>". $row['school'] ."</option>";
}
}
?>
</select>
<br>
<input type ="submit" name = "submit_school" value = "Enter">
</form>
<?php
//saves selected option as $selected_school
if(isset($_POST['submit_school'])){
$selected_school = mysqli_real_escape_string($conn, $_POST['school']);
echo "You have selected: " .$selected_school;
}
?>
</div>
<div class ="courses">
<h3>Please select the courses you took</h3>
<form action = "" method ="post" name ="course_form">
<?php
//user shown options for courses
$sql2 = "SELECT transfer_course, transfer_title FROM data WHERE school = ? ORDER BY transfer_course ASC";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql2)) {
echo "SQL statement failed";
} else {
mysqli_stmt_bind_param($stmt, "s", $selected_school);
mysqli_stmt_execute($stmt);
$result2 = mysqli_stmt_get_result($stmt);
while($row2 = mysqli_fetch_assoc($result2)){
echo "<input type='checkbox' name ='boxes[]' value = '" . $row2['transfer_course'] . "' >" . $row2['transfer_course'] . "<br>";
}
}
?>
<br>
<input type ="submit" name = "submit_courses" value = "Enter">
</form>
<br>
<?php
//saved selected option(s) as $selected_course
if(isset($_POST['submit_courses'])){//to run PHP script on submit
if(!empty($_POST['boxes'])){
foreach($_POST['boxes'] as $selected_course){
echo "You have selected: " . $selected_course . "</br>";
}
}
}
?>
</div>
<div class = "output">
<h3>Course Equivalency</h3>
<?php
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " . $selected_school . " AND transfer_course = " . $selected_course . "";
$result3 = mysqli_query($conn, $sql3);
if($result3)
{
while($row3 = mysqli_fetch_assoc($result3)){
echo $row3['arcadia_course'] . " " . $row3['arcadia_title'] . "<br>";
}
} else {
echo "failed";
echo $sql3;
}
?>
So by the time I get to my next sql statement
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " . $selected_school . " AND transfer_course = " . $selected_course . "";
When the school is selected, it saves the variable, but when the course is selected, $selected_school becomes blank again.
I already have session_start() at the top of the page.
You can used session variable ,it will help to make data accessible across the various pages .
So,whenever form get submitted you can save that value in session and retrieve it anytime.In top of your php file you need to start session i.e session_start(); .Then in your code
<?php
//saves selected option as $selected_school
if(isset($_POST['submit_school'])){
$_SESSION['selected_school ']=$selected_school;// here you are storing value to session
$selected_school = mysqli_real_escape_string($conn, $_POST['school']);
echo "You have selected: " .$selected_school;
}
?>
Same you can do with your $selected_course also .Then you can passed value to your query like below :
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " .$_SESSION['selected_school ']. " AND transfer_course = " .$_SESSION['selected_course']. "";
For more information refer here
It looks like your option doesn't have a value it is passing. Try this in your first form while loop:
echo '<option value="' . $row['school'] . '">' . $row['school'] . '</option>';
It looks like there may be some more issues you are having as well. If this doesn't fix your issue, I'll dig deeper.
EDIT: Then, yes, as others have suggested, you probably want to add a hidden input field to pass that variable value on the second form submit as well.
What we are saying about the hidden input field is this:
<input type="hidden" name="selected_school" value="<?php if(isset($selected_school) echo $selected_school; ?>">
So i am trying to insert some data in my database, unfortunatly it doesn't work as i hoped.
This is my index.php file here i made a little piece of php code to get the select options from my database(this works fine). But now i want people to select from the options in my database and store the selected option in another db table.
<?php
$query = "SELECT event_naam FROM events";
$result2 = mysqli_query($dbconn, $query);
$options = "";
while($row2 = mysqli_fetch_array($result2))
{
$options = $options."<option>$row2[0]</option>";
}
?>
<form class="inschrijven" method="POST" action="includes/inscscript.php">
<select name="iselect">
<?php echo $options;?>
</select><br><br>
<span>Uw Naam: </span><input type="text" name="inaam" placeholder="Naam"><br>
<span>Leeftijd: </span><input type="number" name="leeftijd"><br>
<span>Aantal Personen:</span><input type="number" name="personen"><br>
<input type="submit" name="inschrijven" value="Inschrijven!">
</form>
I have tried this, but it doesn't do anything it also doesn't give an error.
require_once 'connectie.php'; //Connection to Database File
$sql = "INSERT INTO inschrijven (inschrijf_event, inschrijf_naam, inschrijf_leeftijd, inschrijf_personen) VALUES
('".$_POST['iselect']."','".$_POST['inaam']."','".$_POST['leeftijd']."','".$_POST['personen']."')";
if ($dbconn->query($sql) === TRUE) {
header( "Location: ../index.php" );
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $dbconn->error."');</script>";
}
$dbconn->close();
This is my inscscript.php file
I tried searching for similair qeustions but couldn't find anything like this.
$query = "SELECT event_naam FROM events";
$result=mysqli_query($con,$query)
{
// Return the number of rows in result set
while($rowcount=mysqli_num_rows($result)){
echo "<option value='".$rowcount['event_naam']."'>".$rowcount['event_naam']."</option>
}
Include this php file to your html between select opend and closing tags
Doing a simple PHP/SQL search bar on my database and the results aren't appearing. The search bar appears, and whatever i type isn't appearing in the URL. Code is below. I'm connecting to a database through a different file.
Index.php
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<center>
<form action="search.php" method="post">
<input type="text" name="search" autocomplete="off">
<input type="submit" value="search">
</form>
</center>
</body>
</html>
search.php
<?php
$search = $_GET['search'];
require 'constants.php';
?>
<?php
$query = "SELECT Name, Zip, Address, Type FROM parks WHERE Zip = '%{$search}%'";
$result = mysqli_query($db_connection,$query);
while ($row = mysqli_fetch_array($result))
{
// loop through output one row at a time
$name = $row["Name"];
$zip = $row["Zip"];
$address = $row["Address";
$type = $row["Type"];
echo $name . $zip . $address . $type;
}
?>
First off, you explicitly set the method type as POST:
<form action="search.php" method="post">
then, you're trying to get values of:
<input type="text" name="search" autocomplete="off">
Thru $search = $_GET['search'];. Use $_POST['search'];
Second, this doesn't make sense
WHERE Zip = '%{$search}%'";
If you want to search with a wildcard, better use LIKE clause.
And why not use prepared statements:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
if(isset($_POST['search'])) {
require 'constants.php';
$search = '%' . $_POST['search'] . '%';
$query = "SELECT Name, Zip, Address, Type FROM parks WHERE Zip LIKE ?";
$select = $db_connection->prepare($query);
$select->bind_param('s', $search);
$select->execute();
$select->store_result();
if($select->num_rows > 0) {
$select->bind_result($name, $zip, $address, $type);
while($select->fetch()) {
// loop through output one row at a time
echo $name . $zip . $address . $type . '<br/>';
}
}
}
?>
Another way of fetching:
if(isset($_POST['search'])) {
require 'constants.php';
$search = '%' . $_POST['search'] . '%';
$query = "SELECT Name, Zip, Address, Type FROM parks WHERE Zip LIKE ?";
$select = $db_connection->prepare($query);
$select->bind_param('s', $search);
$select->execute();
$results = $select->get_result();
if($select->num_rows > 0) {
while($row = mysqli_fetch_assoc($results)) {
// loop through output one row at a time
$name = $row["Name"];
$zip = $row["Zip"];
$address = $row["Address"];
$type = $row["Type"];
echo $name . $zip . $address . $type . '<br/>';
}
}
}
How can I update a row in my mySql database from a HTML form. I have tried every technique and nothing seems to work. I would like that users could update their own profile page information.
I have a form on my page but the data doesn't get sent through.
What am i missing?
Here is my code:
------------INDEX.php
<?php
require_once("inc/database.php");
require_once("inc/query.php");
?>
<div class="wrapper">
<div class="content">
<h1>User Profiles</h1>
<?php
while ($row = $results->fetch()) {
$id = ($row["id"]);
$name = ($row["name"]);
$age = ($row["age"]);
$password = ($row["password"]);
print '<div ' . 'class= id-' . ($id) . '">';
print "<p>" . ($name) . "</p>";
print "<p>" . ($password) . "</p>";
print "<p>" . ($age) . "</p>";
print "</div>";
}
?>
</div>
</div>
<form action="inc/addnew.php" method="post">
<p>Name: <input type="text" name="name" required></p>
<p>ID: <input type="text" name="id" value="<?php echo $id; ?>"></p>
<p><input type="submit" value="Lisää"></p>
</form>
------------QUERY.php
<?php
try{
$results = $db->query("SELECT name, password, age, id FROM users");
$results->execute();
// echo "Our query ran successfully.";
} catch (Exception $e){
echo "Data could not be retrived from the database.";
exit;
}
------------DATABASE.php
<?php
try{
$db = new PDO('mysql:host=localhost;dbname=user_profile;port=8889', 'User_profile','bFeLcZjMmVw4PBaF');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch (Exception $e){
echo "Could not connect to the database.";
exit;
}
------------UPDATE.php
<?php
require_once("database.php");
if( isset( $_POST['name'] ) && strlen( $_POST['id'] )){
$id = $_POST['id'];
$name = $_POST['name'];
$results=("UPDATE users SET name='$name' WHERE id=$id");
}
header("Location: ../index.php");
}
else
{
//error either $_POST['login'] is not set or $_POST['login'] is empty form field
echo 'Name or ID field was empty. Please fill out those fields. Back to site <br>';
}
How you expect this query to execute?
$results=("UPDATE users SET name='$name' WHERE id=$id");
you are just generating a query here on UPDATE.php without actually doing anything with it.
Replace this line with:
$results = $db->query("UPDATE users SET name='$name' WHERE id=$id");
You need to prepare and execute your query, not just define it as a string:
$sth = $db->prepare("UPDATE users SET name=:name WHERE id=:id")
$sth->execute(array("name" => $_POST["name"], "id" => $_POST["id"]));
You should be using placeholders to insert your data. Your query uses string interpolation which is extremely dangerous due to SQL injection bugs. Do not put $_POST data directly into a query, it's never safe.