I had set a search button in my website. It works fine if there's a result but if there's none, it doesn't show the "no results.....".
What's wrong with my code?
<html !DOCTYPE HTML>
<body>
<?php
$title = "DenTEETH";
include('header.html');
//connect to database
$db = mysqli_connect("127.0.0.1", "root", "", "authentication");
if(isset($_GET['q']) && $_GET['q'] !== '')
{
$searchq = $_GET['q'];
$sql = "SELECT * FROM search WHERE keyword LIKE '%$searchq%' OR title LIKE '%$searchq%'";
$output='';
$results = mysqli_query($db, $sql);
if (count($results) == 0){
$output .= 'No search results for <b>"' . $searchq . '"</b>';
}
else{
while ($row = mysqli_fetch_array($results)){
$id = $row['search_id'];
$title = $row['title'];
$desc = $row['description'];
$link = $row['link'];
$img = '<img src="images/thumbnail/'.$row['search_id'].'.jpg" class="thumbnail">';
$output .= '<div class="search_thumb">
<p class="search_cap">' . $img . '<h3>' . $title . '</h3>' . $desc .
'<div class="clear"></div></p></div>';
}
}
}
else{
header("location: ./");
}
print($output);
?>
<div class="row">
</div>
<?php
include('footer.html');
?>
</body>
</html>
Use mysqli_num_rows() try this
<html !DOCTYPE HTML>
<body>
<?php
$title = "DenTEETH";
include('header.html');
//connect to database
$db = mysqli_connect("127.0.0.1", "root", "", "authentication");
if(isset($_GET['q']) && $_GET['q'] !== '')
{
$searchq = $_GET['q'];
$sql = "SELECT * FROM search WHERE keyword LIKE '%$searchq%' OR title LIKE '%$searchq%'";
$output='';
$results = mysqli_query($db, $sql);
if (mysqli_num_rows($results ) == 0){
$output .= 'No search results for <b>"' . $searchq . '"</b>';
}
else{
while ($row = mysqli_fetch_array($results)){
$id = $row['search_id'];
$title = $row['title'];
$desc = $row['description'];
$link = $row['link'];
$img = '<img src="images/thumbnail/'.$row['search_id'].'.jpg" class="thumbnail">';
$output .= '<div class="search_thumb">
<p class="search_cap">' . $img . '<h3>' . $title . '</h3>' . $desc .
'<div class="clear"></div></p></div>';
}
}
}
else{
header("location: ./");
}
print($output);
?>
<div class="row">
</div>
<?php
include('footer.html');
?>
</body>
</html>
Related
I've tried to make an small chat only with PHP, HTML and MySQL. The main problem with it is that when you're writing and the web refreshes, the text you're writing disappears. How can I solve it? Here is the code:
Chat (MySQL connection details have been removed):
<?php
$_POST['text'] = '';
session_start();
include 'status.php';
$_SESSION['status'] = status($_SESSION['nick']);
if(IsSet($_SESSION['nick']) && IsSet($_SESSION['pass'])){
?>
<link rel="stylesheet" href="/style.css">
<link rel="icon" href="/icon.ico">
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "15";
header("Refresh: $sec; url=$page");
$_SESSION['text'] = $_POST['text'];
$con = mysqli_connect("","","","");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<body>
<h4>Chat: </h4>
<form align="center" name="form" method="POST" action="/chat/speak.php">
<?php echo $_SESSION['nick'] . ': '; ?>
<input name='text' type='text' value="<?php echo $_SESSION['text']; ?>" style="width: 500px;"><br>
Person: <select id="so" name="private">
<?php
$result = mysqli_query($con,"SELECT * FROM users ORDER BY nick");
while($row = mysqli_fetch_array($result))
{
$nick = $row['nick'];
echo "<option value='$nick' selected='selected'>$nick</option>";
}
?>
<option value="public" selected="selected"> PUBLIC </option>
</select>
<input type="submit" value="Speak!"></form>
</body>
<?php
echo '<hr/>';
$result = mysqli_query($con,"SELECT * FROM chat ORDER BY time DESC");
echo "<div align='left' name='chat'>
<h2 align='center'><u>Conversation: </u></h2>";
echo '<hr/>';
echo "<ul style='list-style-type:none'>";
while($row = mysqli_fetch_array($result))
{
$author = $row['author'];
$message = $row['message'];
$color = $row['color'];
$p = $row['p'];
$destinatary = $row['PRIVATE'];
if($p == 1){
if($author == $_SESSION['nick'] || $destinatary == $_SESSION['nick']){
echo "<li align='left'>" . "<b><font color='$color'>Private from: $author</font></b>" . "<b><font color='$color'> - </font></b>" . "<font color='$color'>$message</font><hr>";}
}else{
echo "<li align='left'>" . "<b><font color='$color'>$author</font></b>" . "<b><font color='$color'> - </font></b>" . "<font color='$color'>$message</font><hr>";
}}
mysqli_close($con);
echo '</ul>';
echo '</div>';
}else{
echo 'You are not logged!';
}
?>
Where the main form goes (MySQL connection details have been removed):
<?php
session_start();
$conn = new mysqli('', '', '', '');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(IsSet($_POST['text']) && ($_POST['text']) != ''){
if($_POST['private'] == 'public'){
$nick = $_SESSION['nick'];
$text = $_POST['text'];
$time = date('c');
$color = $_SESSION['color'];
$text = mysqli_real_escape_string($conn,$text);
$sql = "INSERT INTO chat (author, message, time, color, p, PRIVATE)
VALUES ('$nick', '$text', '$time', '$color', '0', '')";
if ($conn->query($sql) === TRUE) {
header('Location: /chat/chat.php');
} else {
echo "Error";
}
$conn->close();
}else{
$nick = $_SESSION['nick'];
$text = $_POST['text'];
$time = date('c');
$color = $_SESSION['color'];
$destinatary = $_POST['private'];
$text = mysqli_real_escape_string($conn,$text);
$sql = "INSERT INTO chat (author, message, time, color, p, PRIVATE)
VALUES ('$nick', '$text', '$time', '$color', '1', '$destinatary')";
if ($conn->query($sql) === TRUE) {
header('Location: /chat/chat.php');
} else {
echo "Error";
}
$conn->close();
}}else{
header('Location: /chat/chat.php');
}
?>
Hello everyone I'm completely new to mysqli and PDO. I tried to convert my msqli code to PDO but I keep getting errors. Can someone please help me? the error is like when i click on post, nothing happens and I searched everywhere how to convert from msqli to pdo and I converted some of them but it still doesn't work
<?php
$databaseHost = 'localhost';
$databaseName = 'test';
$databaseUsername = 'test';
$databasePassword = 'pass';
try {
$dbConn = new PDO("mysql:host={$databaseHost};dbname={$databaseName}", $databaseUsername, $databasePassword);
$dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
}
if (isset($_POST['save'])) {
$name = $_POST['name'];
$comment = $_POST['comment'];
$sql = "INSERT INTO comments (name, comment) VALUES ('{$name}', '{$comment}')";
if ($result = $dbConn->query($sql)) {
$id = $link->insert_id;
$saved_comment = '<div class="comment_box">
<span class="delete" data-id="' . $id . '" >delete</span>
<span class="edit" data-id="' . $id . '">edit</span>
<div class="display_name">'. $name .'</div>
<div class="comment_text">'. $comment .'</div>
</div>';
echo $saved_comment;
}else {
echo "Error: ".($dbConn);
}
exit();
}
// delete comment fromd database
if (isset($_GET['delete'])) {
$id = $_GET['id'];
$sql = "DELETE FROM comments WHERE id=" . $id;
($dbConn->prepare($sql));
exit();
}
if (isset($_POST['update'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$sql = "UPDATE comments SET name='{$name}', comment='{$comment}' WHERE id=".$id;
if ($dbConn->prepare($sql)) {
$id =($dbConn);
$saved_comment = '<div class="comment_box">
<span class="delete" data-id="' . $id . '" >delete</span>
<span class="edit" data-id="' . $id . '">edit</span>
<div class="display_name">'. $name .'</div>
<div class="comment_text">'. $comment .'</div>
</div>';
echo $saved_comment;
}else {
echo "Error: ". ($dbConn);
}
exit();
}
// Retrieve comments from database
$sql = "SELECT * FROM comments";
$result = $dbConn->prepare($sql);
$comments = '<div id="display_area">';
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$comments .= '<div class="comment_box">
<span class="delete" data-id="' . $row['id'] . '" >delete</span>
<span class="edit" data-id="' . $row['id'] . '">edit</span>
<div class="display_name">'. $row['name'] .'</div>
<div class="comment_text">'. $row['comment'] .'</div>
</div>';
}
$comments .= '</div>';
?>
You used ->prepare(), but did not use ->execute().
Documentation:
http://php.net/manual/en/pdostatement.execute.php
I have created a simple search engine who gets data from a PHP table and post the results. But as of right now it posts the results in a single line and nothing to show that they're in fact 4 different columns. What I'm looking for is a way to create a table so it looks more presentable. I have the search engine divided into 2 .php files.
1st file:
<?php
error_reporting(1);
include('system_admin.inc.php');
$title = 'Leonard';
make_header($title,array('enable_ajax' => true));
?>
<html>
<head>
<title>Leonard</title>
<script type=text/javascript src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type=text/javascript ">
function searchq() {
var searchTxt = $("input[name='search']").val();
$.post("testsearch.php", {searchVal: searchTxt}, function(output) {
$("#output") .html(output);
});
}
</script>
</head>
<body>
<h1>Search</h1>
<form class="odd" action="leonard.php" method="post">
<input type="text" name="search" placeholder="Search" onkeyup="searchq();" />
<div id="output">
</div>
</form>
</body>
</html>
2nd file:
mysql_connect ("localhost","root","xxxxxx") or die ("Connectionissues");
mysql_select_db ("xxxxxx") or die("Can't find DB");
$output = '';
if(isset($_POST['searchVal'])) {
$searchq = $_POST['searchVal'];
$searchq = preg_replace ("#^0-9#"," ",$searchq);
$query = mysql_query("SELECT * FROM ds_OrderItem WHERE idProduct LIKE '%$searchq%' LIMIT 100") or die("Search invalid!");
$count = mysql_num_rows ($query);
if($count == 0){
$output = 'Order have never been made before';
}else{
while($row = mysql_fetch_array($query)) {
$idproduct = $row['idProduct'];
$idorder = $row['idOrder'];
$title = $row['title'];
$qty = $row['qty'];
$output .= '<div> '.$idproduct.' '.$idorder.' '.$title.' '.$qty.' </div>';
}
if($_POST['searchVal'] == NULL) {
$output = "";
}
}
}
I want these four columns to be displayed in a presentable manner:
$idproduct = $row['idProduct'];
$idorder = $row['idOrder'];
$title = $row['title'];
$qty = $row['qty'];
Can anyone help me with this? :-)
Thanks in advance for reading and any advice given!
Change this portion
while($row = mysql_fetch_array($query)) {
$idproduct = $row['idProduct'];
$idorder = $row['idOrder'];
$title = $row['title'];
$qty = $row['qty'];
$output .= '<div> '.$idproduct.' '.$idorder.' '.$title.' '.$qty.' </div>';
}
to
$output .='<table>';
while($row = mysql_fetch_array($query)) {
$output .= '<tr><td>'.$row['idProduct'].'</td><td>'.$row['idOrder'].'</td><td>'.$row['title'].'</td><td>'.$row['qty'].'</td></tr>';
}
$output .='</table>';
i've created a php script that connects to my database (mysql) this will be changed to a more secure enviorment.
But for now i want to change the bg color of my out come
'echo "<h2><a href='$Link'>$title</a></h2>
<b>$description</b><br /> ";
}
}
else
echo "Geen resultaat gevonden voor \"<b>$s</b>\""; '
im not sure how to do so with a while loop.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8" />
<title> Snuffelen</title>
</head>
<body>
<a href="index.php">
<img src="image/logo_klein.jpg" alt="Snuffelen logo" style="width:250px;height:75px;border:0;">
</a>
<form action='./search.php' method='get'>
<input type='text' name='s'size='50' value='<?php echo $_GET['s']; ?>' />
<input type='submit' value='Zoek'/>
</form>
<hr />
<?php
$s = $_GET['s'];
$terms = explode (" ", $s);
$query = "SELECT * FROM ID WHERE ";
foreach ($terms as $each){
$i++;
if ($i ==1)
$query .= "keywords LIKE '%$each%' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
//connect to database
mysql_connect("server", "user", "pw");
mysql_select_db("DB");
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if($numrows > 0){
while($row = mysql_fetch_assoc($query)){
$id = $row['id'];
$photo = $row['photo'];
$title = $row['title'];
$description = $row['description'];
$price = $row['price'];
$Link = $row['Link'];
$keywords = $row['keywords'];
$euro = $row['euro'];
$line = $row ["__________________________________________________________________________________________________"];
echo "<h2><a href='$Link'>$title</a></h2>
<b>$description</b><br /> ";
}
}
else
echo "Geen resultaat gevonden voor \"<b>$s</b>\"";
//disconect
mysql_close();
?>
</body>
</html>
i whould like to add to colors 1 light grey and 2 white and then the next one light grey white light grey etc etc
does anybody know how to do so??
Please try this
$bgColor = "style='background-color: green;'";
echo "<div ".$bgColor.">";
if($numrows > 0){
while($row = mysql_fetch_assoc($query)){
$id = $row['id'];
$photo = $row['photo'];
$title = $row['title'];
$description = $row['description'];
$price = $row['price'];
$Link = $row['Link'];
$keywords = $row['keywords'];
$euro = $row['euro'];
$line = $row ["__________________________________________________________________________________________________"];
echo "<h2><a href='$Link'>$title</a></h2>
<b>$description</b><br /> ";
}
}
else
echo "Geen resultaat gevonden voor \"<b>$s</b>\"";
echo "</div>";
Please try this
$bgColorGreen = "style='border: 1px solid green;'";
$bgColorBlue = "style='border: 1px solid blue;'";
if($numrows > 0){
$i = 0;
while($row = mysql_fetch_assoc($query)){
$id = $row['id'];
$photo = $row['photo'];
$title = $row['title'];
$description = $row['description'];
$price = $row['price'];
$Link = $row['Link'];
$keywords = $row['keywords'];
$euro = $row['euro'];
$line = $row ["__________________________________________________________________________________________________"];
if($i % 2 == 0){
echo "<hr ".$bgColorGreen.">";
}else{
echo "<hr ".$bgColorBlue.">";
}
echo "<h2><a href='$Link'>$title</a></h2>
<b>$description</b><br /> ";
$i++;
}
}
else
echo "Geen resultaat gevonden voor \"<b>$s</b>\"";
I have a search engine but the problem is the search engine don't show search results, the connections to the database are correct here is the code:
PHP :
if (isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
$query = mysql_query("SELECT * FROM tReference WHERE sReference LIKE '%$searchq%' OR sSearch LIKE '%$searchq%' OR sSort LIKE '%$searchq%'") or die("La Recherche est impossible");
$count = mysql_num_rows($query);
if ($count == 0) {
$output = "Aucun Résultat Pour Cette Recherche!";
//English Trans : No results have been Found!
}
else
{
$sReference = $count['sReference'];
$output.= '<div><ul><li><a target="_blanc" href="refrences.php?reference=' . $sReference . '" title="' . $sReference . '">' . $sReference . '</a></li></ul></div>';
}
}
HTML:
<div id="searchd">
<div class="searchc">
<form action="reference.php" method="post">
<input type="text" name="search" palceholder="Recherhcer...">
<input type="submit" Value="Ok">
<div class="clear"></div>
</form>
</div>
<div id="output">
<?php echo ($output); ?>
</div>
</div>
And Thanks to All in advance!
You were not actually processing the result of your query.
You have to fetch each row from the returned result set and then use the fields returned in your html output.
Try this:-
if (isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
$query = mysql_query(
"SELECT * FROM tReference
WHERE sReference LIKE '%$searchq%' OR
sSearch LIKE '%$searchq%' OR
sSort LIKE '%$searchq%'") or die("La Recherche est impossible");
if (mysql_num_rows($query) == 0) {
$output = "Aucun Résultat Pour Cette Recherche!";
//English Trans : No results have been Found!
} else {
$output .= '<div><ul>';
while ( $row = mysql_fetch_object($query) ) {
$output .= '<li>';
$output .= '<a target="_blanc" href="refrences.php?reference=' . $row->sReference . '" ';
$output .= '" title="' . $row->sReference . '">' . $row->sReference . '</a>';
$output .= '</li>';
}
$output .= '</ul></div>';
}
}
It's done Guys, Thanks to all here's the solution:
if (isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
$query = mysql_query(
"SELECT * FROM tReference
WHERE sReference LIKE '%$searchq%' OR
sSearch LIKE '%$searchq%' OR
sSort LIKE '%$searchq%'") or die("La Recherche est impossible");
if (mysql_num_rows($query) == 0) {
$output = "Aucun Résultat Pour Cette Recherche!";
} else {
$output .= '<div><ul>';
while ( $row = mysql_fetch_assoc($query) ) {
$sReference = $row['sReference'];
$output .= '<li>';
$output .= '<a target="_blanc" href="refrences.php?reference="' . $sReference . '" ';
$output .= '" title="' . $sReference . '">' . $sReference . '</a>';
$output .= '</li>';
}
$output .= '</ul></div>';
}
}
Thanks to #RiggsFolly, and Thanks to All of you.
Your code makes no sense. First I recommend that you use Object oriented PHP on a separate secure page. Then your code should look more like:
//secure.php
<?php
function db(){
return new mysqli('host', 'user', 'password', 'database');
}
?>
//reference.php
include 'secure.php'; $output = '';
if(isset($_POST['sub'])){
$db = db(); $searchq = $_POST['search'];
// What is this for? --->>> $searchq = preg_replace('/[^0-9a-z]/i', "", $searchq);
$query = $db->query("SELECT * FROM tReference WHERE sReference LIKE '%$searchq%' || sSearch LIKE '%$searchq%' || sSort LIKE '%$searchq%'");
if($query->num_rows < 1){
die('Aucun Résultat Pour Cette Recherche!');
}
else{
while($row = $query->fetch_assoc()){
$sref = $row['sReference'];
$output.= "<li><a target='_blank' href='refrences.php?reference=$sref' title='$sref '>$sref</a></li>";
}
$query->free(); $db->close();
}
<div id='searchd'>
<div class='searchc'>
<form action='reference.php' method='post'>
<input type='text' name='search' placeholder='Recherhcer...' />
<input type='submit' value='Ok' name='sub' />
<div class='clear'></div>
</form>
</div>
<ul id='output'><?php echo $output; ?></ul>
</div>