I'm trying to create a searchbar that search for the title .. database is working , content showing under searchbar then i search sth , it show me "connection succesfully and then no results .. what's wrong ?
<?php
include 'header.php';
?>
<h3>Rezultate</h3>
<div class"article-container">
<?php
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
echo "Connected successfully";
if(isset($_POST['submit-search']))
{
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM article WHERE a_title LIKE '%search%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if($queryResult >0)
{
while ($row = mysqli_fetch_assoc($result))
echo"<div>
<h3>".$row['a_title']."</h3>
<p>".$row['a_text']."</p>
<p>".$row['a_author']."</p>
<p>".$row['a_dat']."</p>
</div>";
}
else
{
echo "<br>No result!";
}
}
?>
</div>
Your SQL is wrong, when referencing the variable $search in the SQL query. Just change the %search% to %$search%:
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM article WHERE a_title LIKE '%$search%'";
Also, I strongly believe you should consider using Prepared Statements for anything which involves user input.
$search = "%" . $_POST['search'] . "%";
$sql = "SELECT * FROM article WHERE a_title LIKE ?";
if($stmt = $mysqli_prepare($conn, $sql)) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $search);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $district);
/* fetch value */
mysqli_stmt_fetch($stmt);
printf("%s Search Result: %s\n", $search);
/* close statement */
mysqli_stmt_close($stmt);
}
This will protect you a bit more against SQL Injections.
$sql = "SELECT * FROM article WHERE a_title LIKE '%search%'";
Your current query is searching for terms like the string "search". Fix it so it's a PHP variable.
$sql = "SELECT * FROM article WHERE a_title LIKE '%$search%'";
Related
I am using ajax to search from mysql database.
But I am getting error in query syntax saying error near where division=UNKNOWN.
what is correct syntax
code :
<?php
include('db.php');
if(isset($_POST['division'])){
$division=$database->filter($_POST['division']);
$check_user = array(
'division' => $division
);
$exists = $database->exists( 'tablename', 'division', $check_user );
if ($exists){
$sql2 = "select * from tablename where division = '".$division."' group by branch order by branch ASC";
$sql=$database->get_results($sql2);
echo '<option value="">--Select Branch--</option>';
foreach($sql as $row){
$name=$row['branch'];
echo '<option value="'.$name.'">'.$name.'</option>';
}
}
}
?>
Here Which is correct?
1)
$sql2 = "select * from tablename where division = '".$division."' group by branch order by branch ASC";
Or
2)
$sql2 = "select * from tablename where division = '$division' group by branch order by branch ASC";
As stated in many comments (Joshua Bakker / Saty / ADyson), you should really consider using PPS : Prepared Parameterized Statements. This will help Preventing SQL injection
This is a raw example of what you could use (please adapt to what you need) :
<?php
error_reporting(E_ALL); ini_set('display_errors', 1); /* let PHP help us */
$host = ""; /* your credentials here */
$user = ""; /* your credentials here */
$pwd = ""; /* your credentials here */
$db = ""; /* your credentials here */
/* store in PHP variable */
/* you may also want to perfom some other/more checking on this var */
/* NEVER trust user side data */
$division = $_POST['division'];
echo"[ division -> $division ]"; /* just checking value -> to be removed */
/* connexion to db */
$mysqli = mysqli_connect("$host", "$user", "$pwd", "$db");
if (mysqli_connect_errno()) { echo "Error: no connexion allowed : " . mysqli_connect_error($mysqli); }
/* make sure 'tablename' and 'branch' use below are correct -> adapt to your needs */
$query = " SELECT `branch` FROM `tablename` WHERE division=? GROUP BY `branch` ORDER BY `branch` ASC ";
$stmt = $mysqli->prepare($query); /* prepare query */
$stmt->bind_param("s", $division); /* bind param will sanitize :
here we make use of $var 'division' with 's' because it's a string AFAIK */
print_r($stmt->error_list); /* any error ? */
print_r($stmt->get_warnings()); /* any error ? */
print_r($stmt->error); /* any error ? */
$results = $stmt->execute();
$stmt->bind_result($branch); /* we use the result of the query */
$stmt->store_result();
if ($stmt->num_rows > 0) {
echo '<option value="">--Select Branch--</option>';
while($stmt->fetch()){
echo '<option value="'.$branch.'">'.$branch.'</option>';
}
}
else
{ echo"[ no data ]"; }
?>
i am developing a search option using php. there i need to do search using user given criteria user can be search when user give id,name,status any of combination of these three parameters.below is my code
if(isset($_POST['search']))
{
echo "<script> document.getElementById('tblsearch').style.display = 'block' </script> ";
$serviceNumber=$_POST['serviceNumber'];
$name=$_POST['name'];
$pendingfrom=$_POST['pendingfrom'];
$status=$_POST['status'];
$datefrom=$_POST['datefrom'];
$dateto=$_POST['dateto'];
$searchkey='serviceNumber';
$mysqli = new mysqli("localhost", "root", "", "user_management");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = 'SELECT * FROM user WHERE ';
$where = array();
$values = array();
$types = '';
if (!empty($_POST['serviceNumber'])) {
$where[] = 'serviceNumber = ?';
$values[] = $_POST['serviceNumber'];
$types .= 'i';
}
if (!empty($_POST['name'])) {
$where[] = 'Username = ?';
$values[] = $_POST['name'];
$types .= 's';
}
if (!empty($_POST['status'])) {
$where[] = 'status = ?';
$values[] = $_POST['status'];
$types .= 's';
}
$query .= implode(' AND ',$where);
printf("rows inserted: %d\n", $query);
printf("rows inserted: %d\n", $values);
/* prepare statement */
if ($stmt = $mysqli->prepare($query)) {
/* Bind variable for placeholder */
$stmt->bind_param($types,$values);
/* execute statement */
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
printf("rows inserted: %d\n", $stmt->num_rows);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
below line i was going confused,because $values is an array.i need to pass user given paremeters to this in order to execute.
$stmt->bind_param($types,$values);
so in order to get correct results how do i need to do this.
You can use call_user_func_array() to call a function with an array of parameters. The parameters need to be stored as references in order to be passed to the bind_param method. Long story short, you need an array where the 1st value is a string and the rest are references to your parameters.
For example:
$bindParams = [$types];
foreach ($values as $key => $value) {
$bindParams[$key] = &$value;
}
call_user_func_array(
[$stmt, 'bind_param'], //array with the object and the method - callable
$bindParams
);
Try using below:
if(isset($_POST['search']))
{
echo "<script> document.getElementById('tblsearch').style.display = 'block' </script> ";
$serviceNumber=$_POST['serviceNumber'];
$name=$_POST['name'];
$pendingfrom=$_POST['pendingfrom'];
$status=$_POST['status'];
$datefrom=$_POST['datefrom'];
$dateto=$_POST['dateto'];
$searchkey='serviceNumber';
$mysqli = new mysqli("localhost", "root", "", "user_management");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = 'SELECT * FROM user WHERE ';
if (!empty($_POST['serviceNumber'])) {
$query .="serviceNumber='$searchkey' ";
}
if (!empty($_POST['name'])) {
$query .="and Username='$name' ";
}
if (!empty($_POST['status'])) {
$where[] = 'status = ?';
$values[] = $_POST['status'];
$query .=" and status='$status' ";
}
/* prepare statement */
if ($stmt = $mysqli->prepare($query)) {
/* Bind variable for placeholder */
$stmt->bind_param($types,$values);
/* execute statement */
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
printf("rows inserted: %d\n", $stmt->num_rows);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
Hope this helps.
I'm converting to Mysqli object-oriented (or trying to). I have various category pages. I'd like to use a parameter placeholder '?' in the include and then call up the right category on the category page.
This is as far as I've gotten. How do I indicate the category on my page? All works fine if I indicate WHERE category = apples.
I have this include at top of a category page
<?php require_once 'maincats_mysqli.php' ?>
which is below:
<?php
$db = new mysqli('host', 'userName', '', 'dbName');
if ($db->connect_error) {
$error = $db->connect_error;
} else {
$sql = "SELECT pageName, gImage, prodName, prodPrice
FROM tableName
WHERE category = '?'
ORDER BY dtList DESC";
$stmt->bind_param('s', ['$category']);
$result = $db->query($sql);
if ($db->error) {
$error = $db->error;
}
}
function getItem($result) {
return $result->fetch_assoc();
}
?>
Below is part of one category page. How do I indicate which category? Any help would be appreciated.
<?php
if (isset($error)) {
echo "<p>$error</p>";
}
?>
<?php
while ($item = getItem($result)) {
?>
<a href="http://www.example.com/<?php echo $item['pageName']; ?>">
<img src="http://www.example.com/<?php echo $item['gImage']; ?>"</a>
<a href="http://www.example.com/<?php echo $item['pageName']; ?>">
<?php echo $item['prodName']; ?></a>
<?php echo $item['prodPrice']; ?>
<?php
}
?>
First, you don't declare $stmt.
Second, ? is not a wildcard in this case, it's a parameter placeholder. You can use such placeholders when preparing the query, with $mysqli->prepare($sql). See documentation: http://php.net/manual/en/mysqli-stmt.bind-param.php
$sql = "SELECT pageName, gImage, prodName, prodPrice
FROM tableName
WHERE category = ?
ORDER BY dtList DESC";
$stmt = $db->prepare($sql);
Third, you encapsulate your variable in single quotes, so it's a string with a dollar and the name of your variable, not its content. And it must not be in an array:
$stmt->bind_param('s', $category);
Last: where does $category comes from? It's not defined in the script you show us. I guess it's from $_GET, so the previous line should be:
$stmt->bind_param('s', $_GET['category']);
Finally, you need to execute your statement, which contains the query:
$stmt->execute();
EDIT:
To fetch results, you don't need that getItem() function. Just remove it.
$result = $stmt->get_result();
Then you can loop over $result and fetch each row:
while ($item = $result->fetch_assoc()):
// do you stuff
endwhile;
Note that I use here the PHP control structure alternative syntax which is more clear in your case (endwhile is more explicit than just })
You're missing the prepare(). Look at the first example in the PHP manual page:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$city = "Amersfoort";
/* create a prepared statement */
$stmt = $mysqli->stmt_init();
if ($stmt->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Note that you must not quote binded parameters.
This question already has answers here:
How I can execute many queries in one page?
(2 answers)
Closed 6 years ago.
I use this code it run very good but the problem how I can execute the second query:
$query .= "SELECT * FROM `course` where id = 201102887;";
which is from another table.The first query work fine . Can you help me or advise me to another way to run many query .
<?php
$link = mysqli_connect("localhost", "root", "", "uoh");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM `student_record` where id = 201102887;";
$query .= "SELECT * FROM `course` where id = 201102887;";
/* execute multi query */
if (mysqli_multi_query($link, $query)) {
do {
/* store first result set */
if ($result = mysqli_store_result($link)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
printf("%s\n", $row[1]);
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($link)) {
printf("-----------------\n");
}
} while (mysqli_next_result($link));
}
/* close connection */
mysqli_close($link);
?>
Try UNION for this
<?php
$link = mysqli_connect("localhost", "root", "", "uoh");
$query = "SELECT * FROM `student_record` where id = 201102887 UNION SELECT * FROM `course` where id = 201102887";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_row($result))
{
print_r($row);
}
?>
This should print two arrays (one per row), one from the student_record table (assuming id is unique) and one from the course table assuming that id is unique.
So I am having a difficult time getting a variable using a mysql search command and then using it in the same script in an insert command. What am I doing wrong?
<?php
$usto= $_GET["usto"];
$itena= "item";
$sql = 'SELECT sname FROM login';
$hostname_Database = "blocked";
$database_Database = "blocked";
$username_Database = "blocked";
$password_Database = "blocked";
$mysqli = new mysqli($hostname_Database, $username_Database, $password_Database, $database_Database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli->query($sql);
if ($result) {
$row = $result->fetch_assoc();
$sql = "INSERT INTO pon(mis, take)
VALUES({$row['snake']}, '" . $usto . "')"; //Here, I am trying to use the result from the previous select statement for the variable
$result = $mysqli->query($sql);
if ($result) {
...etc.
}
}
?>
You are vulnerable to SQL injection attacks. Read up about those and fix your code FIRST.
After that, realize that ->query() calls return a result HANDLE, not the actual field(s) you'd requested in your query. You have to FETCH a row of data first:
$result = $mysqli->query($sql);
$row = $result->fetch_assoc();
$sql = ".... VALUES ({$row['name_of_field']} ...)";
Note that this is STILL vulnerable to SQL injection.. it's purely to illustrate the query/fetch/insert process.