I am trying to create a search facility for a website. the website contains text posts so the database has a table post_record with field post_id, post_title, post_href and post_content.
now the working is when a user enters any search keyword in search field, that keyword is being tested against all the post titles and post contents and where it matches it should return all those rows. Following is the code for it. the issue is its returning only the last row of the databse.
<table class="s_table">
<?php
require_once'config.php';
if(isset($_POST['search_btn']))
{
$mes = " ";
$search_key =" ";
$search_key = ($_POST['search_field']);
try
{
if(empty($search_key) && $search_key != " ")
{
echo $mes = "Enter the keyword you want to search.";
}
else
{
$result = $conn->prepare("SELECT * FROM post_record WHERE post_title LIKE '%".$search_key."%' OR post_content LIKE '%".$search_key."%'");
$result->execute();
$count=$result->rowCount();
$datas = $result->fetchAll();
if(!$count)
{
echo $mes = "No Result found. Try another keyword for search.";
}
else
{
foreach ($datas as $data)
{
echo "
<tr><td><b><u><a href='".$data['post_href']."'>".$data['post_title']."</a></b></u></td></tr><br>
<tr><td class='s_cont'>".$data['post_content']."</tr></td><br><br>";
}
}
}
}
catch(PDOException $e)
{
$mes = "Something Went Wrong! try again";
header("location:index.php");
}
}
$conn = null;
?>
Everything is working fine except the thing that it is displaying only last row of the database.
Right now database has 3 posts and for testing purpose i tried a keyword that i know is common in all the post contents but its not working. only last row the database is being fetched and tested.
if(empty($search_key) && $search_key != " ") this condition is wrong
Both are different things which wont get true ever.
you are testing if its empty and then u r testing if its not empty
Both in same if condition
I usually use procedual functions but I encounter a problem like this with the mysqi_fetch_array(), so your problem might be that fetchAll() is moving the cursor to the last record. Try to remove that function or use mysql_data_seek($datas , 0) before the foreach() .
Related
I've got 3 different tables and I want to update the 4th table with some specific column from each of the 3 tables, they all have a common key. I can do this from the phpmyadmin, but I want to do it using a php script.
This is what I tried but it didn't work
if (isset($_GET)) {
$update = '';
$count="SELECT * FROM test2 ";
foreach ($connect->query($count) as $row) {
$term_total1=$row['english'];
$sql = "UPDATE total set `f_test` ='$term_total1' ";
foreach ($connect->query($count) as $row) {
echo "success<br>" . $term_total1;
}
}
}else{
echo "try another method" . mysqli_error($connect);
}
Have been trying for days now.
Repeated the same code for the other two tables but it won't work.
Is it possible to do it in a single query? If Yes, then how
I'm pretty sure your method of using foreach to loop the result set is incorrect. In your updated code you've also not got a unique identifier so your code is just going to mass update your table. Here's your current code fixed up so hopefully you can understand how to loop the dataset from mysqli
$count="SELECT * FROM test2";
if($res = $connect->query($count)){
while($row = $res->fetch_assoc()){
$term_total1 = $row['english'];
$sql = "UPDATE total set `f_test` = '{$term_total1}'";
if($res2 =$connect->query($sql)){
echo "success<br>" . $term_total1;
}else{
print_r($connect->error());
}
}
}else{
print_r($connect->error());
}
I am having some trouble with displaying some SQL query results.
Goal: I want to display the Helper 'name' in the table that is being generated if there is a helper signed up in the 'signup' table for that event 'eid' (event id).. If (1)there is no helper then display 'waiting for help', (2) there is a helper then display 'name -- awaiting approval..' and (3) else just display the name of helper..
Tried running the SQL query in phpMyAdmin with hard coded values and I get the results that I want so I know it is not my query. Have a suspicion that it is just the print out of the info into the table that is wrong somewhere. The table will display the data up until the ZIP from the address and then the next column which is the 'Helper' column does not display anything at all. So it makes me think I have a simple typo somewhere based on my if() statement logic BUT also find it interesting also that when I do the line:
echo "testing method -> ".getHelperIdOrName(2, 80)."<br>";
I cant get the table to print out at all. Not sure if this is related to my exact issue but it seems it could be. After I put this function in stuff stopped working so it seems like it could be culprit. The return of the function should either return an ID (int), a name "string", or just a generic value X (string)..
Any and all help is appreciated!
function getHelperIdOrName($x, $eid){
//Get the helper name first
$helperName = "";
$helperId = 0;
$sql = "SELECT id, first FROM users WHERE id IN (SELECT helper FROM signup WHERE gner = '".$userId."' AND eid = '".$eid."')";
$result = mysqli_query($db,$sql);
$row = $result->fetch_assoc();
if ($x == 2){
$helperName = $row["first"];
return $helperName;
}
else if ($x == 1){
$helperId = $row["id"];
return $helperId;
}
else {
return "X";
}
}
echo "testing method -> ".getHelperIdOrName(2, 80)."<br>";
//look for calendar and/or business approved events (approved=1) to display on page
$sql = "SELECT s.gner, s.helper, s.eid, s.approved, e.name, e.date, e.summary, e.street, e.city, e.state, e.zip
FROM signup s
INNER JOIN events e ON e.id = s.eid
INNER JOIN users u ON u.id = s.gner
WHERE s.gner = '".$userId."'";
$result = mysqli_query($db,$sql);
echo "<h3 class=\"text-center\">Events I'm Going To</h3>";
echo "<table class=\"table table-hover\"><tr><th>Event Name</th><th>Date</th><th>Summary</th><th>Location</th><th>Helper</th><th>Remove</th></tr>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["name"]."</td><td>".$row["date"]."</td><td>".$row["summary"]."</td><td>".$row["street"].", "
.$row["city"].", ".$row["state"]." ".$row["zip"]."</td>";
$tmp_eid = $row["eid"];
if (getHelperIdOrName(2, $temp_eid) == "X"){
echo "<td>Waiting for help..</td>";
}
else if ($row["approved"] == 0){
echo "<td>".getHelperIdOrName(2, $temp_eid)." -- Awaiting Approval (see below)</td>";
}
else {
echo "<td>".getHelperIdOrName(2, $temp_eid)."</td>";
}
echo "<td><form method=\"post\" action=\"remove.php\">
<button type=\"submit\" name=\"remove\" value=\"".$row["eid"]."\">Not Going</button></form></td></table>";
}
}
else echo "</table><br><p class=\"text-center\">You are not signed up for any events. Click here to sign up for events near you!</p>";
Thanks for that Jeff. The issue was that inside of the function it indeed did not know what $userId was even though I had the include statement at the top of my php file. I had to add this line into my function at the top..
global $db; //is part of my db my connection info in my config.php file
and then I also passed the $userId to the function as a parameter
these lines are what I used to help me see the errors:
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
i also had some ending < /table > tags inside some if logic so that fixed the funky displays I was getting (2nd row of table being outside of the table)
This is my first post. on to the point
I am trying to make a bulk update in a MySQL table using a php if statement.but since i have no clue of mysql apart to connect to a database and update things 1 by 1.
So basically i am trying to use this if statement that is loooking for the word Casio in the name and avoids all prodcuts that have Bulgarian letters in the name on its own the code works,i just have 0 idea how to impliment it for MySQL would love some help to how to start.
<?php
require("words.php");
$product = "CASIO EF-513D-5AV MTP Chronograph";
if (strstr($product,"CASIO",0)) {
/*Watches for men*/
if (strstr($product,$gs,0) || strstr($product,$edifice,0) || strstr($product,$mtp,0) || strstr($product,$mrw,0)) {
if ($product == substr($avoid[0],0) || $product == substr($avoid[1],0) || $product == substr($avoid[2],0)) {
echo $product;
}
elseif(strstr($product,$gs,0)) {
echo str_replace($gs,$gsW,$product);
}
elseif(strstr($product,$edifice,0)) {
echo str_replace($edifice,$edificeW,$product);
}
elseif(strstr($product,$mtp,0)) {
echo str_replace($mtp,$mtpW,$product);
}
elseif(strstr($product,$mrw,0)) {
echo str_replace($mrw,$mrwW,$product);
}
}
}
/*Watches for women*/
elseif (condition) {
# code...
}
else{
}
?>
all the variables that the if statement above contains
<?php
/*Real words that we have*/
$gs = "G-SHOCK";
$casio = "CASIO";
$edifice = "EDIFICE";
$mtp = "MTP";
$mrw = "MRW";
/*Words that will be added*/
$gsW = "Мъжки спортен G-SHOCK";
$casioW = "часовник CASIO";
$edificeW = "Мъжки часовник EDIFICE";
$mtpW = "Мъжки часовник MTP";
$mrwW = "Мъжки часовник MRW";
/*Avoid words*/
$avoid = array("Мъжки","часовник","спортен")
?>
update:My idea is to target a table "product" and access the sub table "name" and which ever name has the word Casio in it,to start doing the if statement for it
Ok so far i've been searching far and wide and the only thing that i am missing is and If else statement
I've figure out how to search inside a table for a string with
$sql = "UPDATE product_description SET name = REPLACE(name, 'CASIO', 'Мъжки часовник CASIO')";
I Just don't how to to tell the code If you see $avoid don't do anything to those names but for the rest add which ever thing i specify
I think you just need to limit the SELECT by using a suitable WHERE clause.
WHERE name NOT LIKE '%Мъжки%' AND name NOT LIKE '%часовник%' AND name NOT LIKE '%спортен%'
You can construct the where clause in PHP along the lines of...
$where = "name NOT LIKE '%".implode("%' AND name NOT LIKE '%",$avoid).%'"
HTH
Make a backup of the original $product string.
<?php
$originalProduct = $product;
// Then your changes are to be made here
// Having finished modifying
$connection = mysqli_connect("localhost", "root", "", "database", 3306);
if($connection->connect_error)
{
// error occured while trying to connect to the database
}
else
{
$query = $connection->query("UPDATE `tablename` SET productName = '$product' WHERE productName = '$originalProduct' LIMIT 1;");
if($query)
{
// Successfully modified record
}
else
{
// error occured while trying to modify
}
}
?>
I think i found an answer to my own question
I could just use several of
$sql = "UPDATE product_description SET name = REPLACE(name, 'EDIFICE', 'Мъжки часовник EDIFICE');";
I am just not sure if it's a good idea to use several of those Replace statements
I have the following code.
When a user enters the a term... sometimes the totalRows_titles returns more than the records displayed on the page. (I think I am echoing the wrong values, but I guess I stared at this too long).
You can see an example here (It will say 5 results found, but only displays 4):
http://libapps.libraries.uc.edu/main/databases/database-results.php?search=naxos&go=Go
The missing fifth item is the one we expect to see, and is called "Naxos Music Library".
It shows as a result, for example, on this search, so it is in the database:
http://libapps.libraries.uc.edu/main/databases/database-results.php?search=naxos+music&go=Go
Here is the code:
$search = $_GET['search'];
if(isset($_GET['search']))
{
if ( $titles = mysql_query("SELECT * FROM arti WHERE MATCH(name, description, url) AGAINST('$search')ORDER BY name ASC"))
{
$row_titles = mysql_fetch_assoc($titles);
$totalRows_titles = mysql_num_rows($titles);
echo '<h4 >'. $totalRows_titles . ' titles were found matching the entry <em>'. $search .'</em></h4>';
while($row = mysql_fetch_assoc($titles))
{
echo '<p><b>'. $row['name'].'</b></br>'.$row['description'].'</br>Connect</p>';
}
}
else
{
echo "mysql:".(mysql_error ());
}
}
?>
I'm using the Tutorial to create a search engine. However I want the user to be allowed to keep typing in the search but make the search ignore anything after a certain amount of text has been entered.
I see right here
include_once ('database_connection.php');//Including our DB Connection file
if(isset($_GET['keyword'])){//IF the url contains the parameter "keyword"
$keyword = trim($_GET['keyword']) ;//Remove any extra space
$keyword = mysqli_real_escape_string($dbc, $keyword);//Some validation
$query = "select topictitle,topicdescription from topics where topictitle like '%$keyword%' or topicdescription like '%$keyword%'";
//The SQL Query that will search for the word typed by the user .
$result = mysqli_query($dbc,$query);//Run the Query
if($result){//If query successfull
if(mysqli_affected_rows($dbc)!=0){//and if atleast one record is found
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ //Display the record
echo '<p> <b>'.$row['topictitle'].'</b> '.$row['topicdescription'].'</p>' ;
}
}else {
echo 'No Results for :"'.$_GET['keyword'].'"';//No Match found in the Database
}
}
}else {
echo 'Parameter Missing in the URL';//If URL is invalid
}
But I don't know how I can make it so after the user has typed 7 charactors let the user keep typing but ignore anything after the 7th charactor. Any help?
Try this
$keyword = trim($_GET['keyword']) ;//Remove any extra space
$keyword = mysqli_real_escape_string($dbc, $keyword);//Some validation
if(strlen($keyword) > 7){
$keyword = substr($keyword,0,7);//This will give you first 7 characters if the user input is greater than seven characters in length.
}
<?php
include_once ('database_connection.php');//Including our DB Connection file
if(isset($_GET['keyword'])){//IF the url contains the parameter "keyword"
$keyword=$_GET['keyword'];
if(strlen($_GET['keyword'])>7)
{
$keyword= substr($_GET['keyword'],0,7);
}
$keyword = trim($keyword) ;//Remove any extra space
$keyword = mysqli_real_escape_string($dbc, $keyword);//Some validation
$query = "select topictitle,topicdescription from topics where topictitle like '%$keyword%' or topicdescription like '%$keyword%'";
//The SQL Query that will search for the word typed by the user .
$result = mysqli_query($dbc,$query);//Run the Query
if($result){//If query successfull
if(mysqli_affected_rows($dbc)!=0){//and if atleast one record is found
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ //Display the record
echo '<p> <b>'.$row['topictitle'].'</b> '.$row['topicdescription'].'</p>' ;
}
}
else {
echo 'No Results for :"'.$_GET['keyword'].'"';//No Match found in the Database
}
}
}
else {
echo 'Parameter Missing in the URL';//If URL is invalid
}
?>