I have a simple search form that sends a post request to my php file, that contains the input like this "searchword=test1". I then use that with PDO to search my table for mathing data.
So far I was only searching one column, using this statement:
$query = $db->prepare("SELECT * FROM articles WHERE title LIKE :seachword);
but now I want to search trought 3 columns (named title, extract and body). I changed my code to:
$query = $db->prepare("SELECT * FROM articles WHERE title LIKE :seachword OR extract LIKE :searchword OR body LIKE :searchword");
and now I get an error saying "Error!: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens<br/>".
If I run the SQL statement using bash ( SELECT * FROM articles WHERE title LIKE '%test%' OR body LIKE '%elem%';), the query results return fine.
Any idea what I'm missing?
Here's my code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
try {
$hostname = "localhost";
$username = "root";
$password = "";
$db = new PDO("mysql:host=$hostname;dbname=topdecka_PTC",$username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!empty($_POST["searchword"])) {
$searchword = $_POST["searchword"];
$query = $db->prepare("SELECT * FROM articles WHERE title LIKE :seachword OR extract LIKE :searchword OR body LIKE :searchword");
$query->execute(array(":seachword" => "%" . $searchword . "%"));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
die();
}
else {
$query = $db->prepare('SELECT * FROM articles');
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
die();
}
} catch (PDOException $e) {
echo "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
You have a typo: 2 x :seachword and 2 x :searchword
Related
Want to output search result from database into an html table, but all I'm getting is a printed array. Fairly certain that's due to "print_r", but how do I output to html table instead and getting shown more than just the first result?
My html table using data from my database works fine - but there I'm just using a "SELECT *" with no user input.
I've tried playing around with my php-code that works with just the "SELECT *", but no luck.
<?php
$servername = "test";
$username = "test";
$password = "test";
$dbname = "test";
$journal = (isset($_SESSION["journal"])) ? $_SESSION["journal"]
: null;
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("connection failed: " . mysqli_connect_error());
mysqli_select_db($conn, $dbname) or die("something went wrong");
if(isset($_POST["form_submit"]))
{
$journal =$_POST["journal"];
$stmt = $conn->prepare("SELECT * FROM straffesager WHERE journalnummer=?");
$stmt->bind_param("s",$journal);
$stmt->execute();
$val = $stmt->get_result();
$row_count= $val->num_rows;
if($row_count >0)
{
$result =$val->fetch_assoc();
print_r($result);
}
else{
echo "<br><br>Den indtastede information matcher ikke sager i databasen.";
}
$stmt->close();
$conn->close();
}
?>
This is my result: "Array ( [idnumber] => 4 [journalnummer] => 17-1717171 [status] => lukket".
The result above is just text. I'd like it to be in the html table I'm using somewhere else as well.
How do I output the result from my code to an HTML table and have more than one search result being shown?
Thanks for helping out a rookie.
instead of
$result =$val->fetch_assoc();
print_r($result);
you should print your table with help of your $result variable
like this
echo "<table><tr><th>HEAD1</th><th>HEAD2</th><th>HEAD3</th></tr>";
while ($row = $val->fetch_assoc()) {
printf("<tr><td>%s</td><td>%s</td><td>%s</td></tr>",
$row['idnumber'],$row['journalnummer'],$row['status']);
//it will put $row instead of %s
}
echo "</table>";
I need some help and I can't figure it out,i tried searching the internet but I found nothing
So I'm using this code from w3schools
<?php
$servername = "localhost"; //Obviously this are set to my parameters
$username = "username"; //Obviously this are set to my parameters
$password = "password"; //Obviously this are set to my parameters
$dbname = "myDB"; //Obviously this are set to my parameters
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM People";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Some code goes here
}
} else {
echo "0 results";
}
$conn->close();
?>
How can I modify this code to echo certain items only?
EXAMPLE
I have 10 items in talbe People (Table people contains id,age,name,gender)
I want to echo out 3 out of 10 People by using their ID which are 1 trough 10
I know i can use this AND id IN(1, 5, 9)"; This just echoes them out 1 after another
Is there a way to echo out id 1 goes here , id 5 goes here and than id 9 goes there like in 3 different places with 3 different codes or something? is this even possible?
You could use:
class people
{
public function people()
{
$sql = $this->conn->prepare("SELECT * FROM `people`");
$sql->execute();
$result = $sql->fetch(PDO::FETCH_OBJ);
return $result;
}
}
then when you want certain information you could simply use in say index.php:
$fetch = new people();
$info = $fetch->people();
you can then run simple echo's such as $info->name or $info->id etc etc..
Depending on how you're searching for the user you could just add
WHERE `userid` = :id
$sql->bindParam(':id', $userid);
and add $userid into the people($userid)
But this will vary depending on how you're pulling out specific users.
use this code
<?php
//using PDO
try
{
$conn = new PDO('mysql:dbhost=myhost;dbname=mydbname;', 'user','pass');
}
catch (PDOException $e)
{
echo $e->getMessage();
}
$getId = $conn->query("
SELECT * FROM users
WHERE id = 1
AND id = 5
AND id = 9
");
while ($ids = $getId->fetch(PDO::FETCH_OBJ)
{
echo $getId->id . '<br>';
}
I am trying to fetch values from a mysql query using PDO...it works with one column but I need to return 2 columns from the query. Below is the piece of code I have made...
try {
$conn = new PDO('mysql:host=localhost;dbname=****', 'root', '****'>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$sth = $conn->prepare("select distinct prod_url,ean from tab_nl where ean in (select ean1 from test_sku where sku='$sku') and prod_url like '%prijzen%'");
$sth->execute();
$urlsku = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
$urlean = $sth->fetchAll(PDO::FETCH_COLUMN, 1);
echo $sku;
echo $urlsku;
echo $urlean;
It returns me some array values...which I really can't figure out. Can anyone please help me with this.
If you use fetch() with the PDO::FETCH_ASSOC style it is easy to get both columns:
while($row = $sth->fetch(PDO::FETCH_ASSOC) {
echo $row['prod_url'];
echo $row['ean'];
}
By placing the fetch in a loop all of the rows will be returned which you can then limit as you see fit.
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
echo $data[0]['prod_url'];
echo $data[0]['ean'];
Add LIMIT 2 in the query , to get two sets of result :)
try {
$conn = new PDO('mysql:host=localhost;dbname=****', 'root', '****'>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$sth = $conn->prepare("select distinct prod_url,ean from tab_nl where ean in (select ean1 from test_sku where sku='$sku') and prod_url like '%prijzen%' LIMIT 2");
$sth->execute();
$urlsku = $sth->fetchAll(PDO::FETCH_ASSOC, 0);
$urlean = $sth->fetchAll(PDO::FETCH_ASSOC, 1);
print_r($urlsku);
print_r($urlean);
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 . "';";
try {
$conn = new PDO('mysql:host=localhost;dbname=dbtable', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = $conn->prepare('SELECT * FROM table WHERE name = ' . $conn->quote($name).' AND id = '. $conn->quote($id));
$data->execute();
while($row = $data->fetch(PDO::FETCH_ASSOC)) {
echo "ID : ".$row['id'].'</br>';
echo "Name : ".$row['name'].'</br>';
echo "Name : ".$row['header'].'</br>';
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
The above works for one parameter (name) but when i use AND operator it shows no results. URL is as given below.
http://www.mywebsite.com/page.php?id=2&name=xyz
As mentioned in the documentation, you're strongly advised to use parametrized queries, like so:
$data = $conn->prepare('SELECT * FROM table WHERE name = :name AND id = :id');
$data->bindParam(":name", $name);
$data->bindParam(":id", $id);
If this still does not work, I would suggest running a similar query directly against your database, through either phpMyAdmin or the MySQL Workbench, to verify that the query actually returns anything.
$data = $conn->prepare("SELECT * FROM table WHERE name = '$name' AND id <> '$id' ");
The above code worked for me.