Trying to understand php code

Hi I’m trying to understand the code below to see if I could adapt it to my current project

$output = ‘’;
if(isset($_POST[‘btnsearch’]))
{
$searchq = $_POST[‘search’];
/$searchq = preg_replace(“#[^0-9a-z]#i”,“”,$searchq);/

$query = mysql_query(“SELECT * FROM user WHERE initial LIKE ‘%$searchq%’ OR lname LIKE ‘%$searchq%’”) or die (“could not search”);
$count = mysql_num_rows($query);

if($count == FALSE)

What should I put in instead of btnsearch (is this the query?), and could you explain what this line says/means?

> $query = mysql_query("SELECT * FROM user WHERE initial LIKE '%$searchq%' OR lname             LIKE '%$searchq%'") or die ("could not search");

Thank you

Yes, you should definitely use something other than isset($_POST['btnsearch'])). You should actually use if($_SERVER['REQUEST_METHOD'] == 'POST'). And as we have said in your earlier topic, switch to mysqli_* or PDO.

The query line SELECT * FROM user WHERE initial LIKE '%$searchq%' OR lname LIKE '%$searchq%' basically means search through the table user with the search phrase and see if there’s any matches or any phrase that are similar to it.

So if someone’s last name starts with smith, it’ll give you the results of smith, smiths, smithz, smith5 since they all start with smith.

Another note to take is don’t use the * (asterisk) wildcard when selecting data. You should be specifying what you need.

Hi

I’m afraid at this stage and just for this little exercise I am trying to cling to something half done rather than learn a new language that will not be of much future use.This is a hobby in my old age…

Thanks. I will change a few things around in the script that I have and see what happens.

I will, in the end update the code. At the moment the important thing is that it works: i.e. I can connect. Now I am tring to see how I could retrieve information with this script I found online.

EDIT

You say I should substitute this

if(isset($_POST[‘btnsearch’]))

for this
if($_SERVER['REQUEST_METHOD'] == 'POST')

leaving for the moment the rest of the code. But wHAt about the “btnsearch”? What is it exactly? The query, or the file connected to the query?

It is highly recommended that you switch while you are attempting to understand the code. With something that “works” like that, it’ll break if you insist on using the old mysql_* functions. If you are going to be changing a few things around in the script, why not just update it right then? If you are waiting on something to work, the code will never work because it’ll end up breaking sooner or later. I hope it is later than sooner.

As for the btnsearch thing, it’s just to check if the form was submitted. Most amateurs (newbies) use isset($_POST['submit']) or isset($_POST['btnsearch']) or event isset($_POST). Usually these type of people tend to use the old mysql_* functions as well and don’t intend to switch over. Not saying you, but I see it in a lot of amateur work.

if($_SERVER['REQUEST_METHOD'] == 'POST') is the proper way of checking if the form was submitted. In certain browsers, using isset($_POST['btnsearch']) will fail. Mostly I’ve heard it was in IE.

What happens when you use isset($_POST['btnsearch']) is when a user types something into the text field and hit enter in that exact text field or in another text field, the form is submitted, but the btnsearch was not clicked on. Forcing the user to have to re-enter in everything.

With if($_SERVER['REQUEST_METHOD'] == 'POST'), you don’t have that problem because you are actually checking to see if the form was submitted. isset($_POST['btnsearch']) checks to see if the form was submitted using the button btnsearch which is flawed.

MySQLi is not a new language, it’s been around for 11 years now according to this post from @felgall - Acessing Databases from PHP. MySQLi may be a bit different in the way it’s accessed than the older version, but it does not lack for information on how to use it out on the internet.

This might seem harsh, but in this instance, I’d actually argue that support on the site for a depreciated technology, should itself be depreciated. People are doing there best here to try and help out with best practice in what is a current technology, only to have that help turned down. At some point the help will begin to dry up if it’s not being heeded.

Here endeth the lesson…

Hi chrissofarabia

I understand and apologize

The apology isn’t necessary. I’m just pointing out how things tend to work on forums of any type really. No one is saying you can’t use the older tech if that’s really what you want to do, but you may find you’re going to end up on your own with learning it. All I’m asking is that you think about what people are saying, and why they are saying it.

From what I’ve seen, you’ve only just started to look at PHP code, and I’m guessing that your knowledge is on no different a level than my own. The cost of switching over to MySQLi now is going to be a far low cost than trying to do it later, once the depreciated techniques have taken root.

1 Like

Hi

In my poor attempts at html/css I was told repeatedly not to use fixed heights, or popups, or lots of other things. We are all different and our brains (and personal experience) find it easier to go a different way. And in my case, the different way is to get things working and then sort out the mess: there are no longer fixed heights, there are no longer popups, etc.

I know absolutely nothing about php, in the same way I knwew nothing about html or css 2 years ago. I read your posts and do not dismiss them. Right now, I want to see if what I am trying to do is feasable and how it could be done. I started with a webpage using tooltips and after much work had to give it up as not practicable. Maybe this I am trying to do now will not work and I will just forget it too. So, my priority now is to see if the thing works, and like a scupltor I want to see if the stone can be shaped into roughly what I want to do; then I will put the finishing touches, which include all the advice I got from you and felgall in other threads.

Many thanks

There is no need for apologies. We are here to help in any way we can. I hope I helped you with the explanation I gave you earlier. This line

$query = mysql_query("SELECT * FROM user WHERE initial LIKE '%$searchq%' OR lname             LIKE '%$searchq%'") or die ("could not search");

is your query.

I don’t know why $output is there, but it doesn’t look like it’s being used. I don’t want to give you the mysql_* version, but I can definitely give you the mysqli_* version if you want. I’ll have to see the whole code first though.

Hi spaceshiptrooper

You have been very, very helpful and I appreciate it

Let me tell you what I dreamed up yesterday morning and have been trying to see if it can be done within my limits (with a lot of help…):

I want to search the database to see which hotel chains have hotels in specific cities.
I managed to create a database with 6 fields:Chain. Country. City. Top, Medium, Low

I also managed to connect to the database with a small script (not this one) and to upload a bunch of records to make sure things were working properly

Then, yesterday I looked for ways of placing a search box (or 2) in one of the pages and came up with this, which tells me that with some changes will be the way to go
http://pintotours.net/TEMP/TEST/search.html?q=andorra

Then, having convinced myself that that part is feasible, and realizing that the script we are talking about now, will start by validating the query in that box,I looked around to se how incredibly difficult it might turn out to be, and came to the conclusion that it easier than I thought.

This script that I found online serves only to tell me if the idea can be brought into practice with just this code altered to comply with my requirements:

If it can, then it will be time to put the final touches without forgetting, for instance, what i have been hearing for the past couple of days, in this and other threads, that “my” code is obsolete. But if it works tomorrow is good enough for me. When the time comes to publish, it will have been updated.

<!--

<input type="text" name="search" placeholder="Search...">
<input type= 'submit' name= 'btnsearch' value= 'search' id= 'btnsearch' onclick=         'this.form.action'/>
<input type = 'submit' name = 'download' value = 'save to excel'/>
-->

<?php

 $user_name = "pintotou_****";
 $password = "v*****";
 $database = "pintotou_search";
 $server = "localhost";


mysql_connect("localhost","pintotou_****","*****") or die ("could not connect");
mysql_select_db("pintotou_search") or die ("could not find db");


$output = '';
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$searchq = $_POST['search'];
/*$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);*/

$query = mysql_query("SELECT * FROM Chains WHERE Country LIKE '%$searchq%' OR City LIKE '%$searchq%'") or die ("could not search");
$count = mysql_num_rows($query);

if($count == FALSE)

{

$output = 'There was no search results!';

}
else

{ 
while($row = mysql_fetch_array($query)){
$id = $row['ID'];

$Chain = $row['Chain'];
$Country = $row['Country'];
$City = $row['City'];
$Top = $row['Top'];
$Medium = $row['Medium'];
$Low = $row['Low'];


$output .= 'ID : '.$ID.'<br> 
Chain : '.$Chain.'<br> 
Country : '.$Country.' <br> 
City : '.$City.' <br> 
Top : '.$Top.'<br> 
Medium : '.$Medium.'<br> 
Low : '.$Low.'<br> 


-------------------------------------<br>';

}

}

print "$output";
}
?>

<?php 

I’ve tested the script with echo statements and it connects to the server, but obviously it does not print “$output” because it does not know where to find the query.

That would be, I think, the first thing to do: connect the html in the page to the script.

Thank you again

I’ve just replied, but Akismet has withdrawn my post (temporarily I hope!) It’s back, above!

Hi

I found and adapted something else that seems simpler and is working already

<!DOCTYPE html>
<html>
<body>

<?php
$servername = "localhost";
$username = "pintotou_****";
$password = *****t";
$dbname = "pintotou_search";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT Chain, Country, City FROM Chains";
$result = $conn->query($sql);

if ($result->num_rows > 0) {

// output data of each row
while($row = $result->fetch_assoc()) {
echo "
Chain: ". $row[“Chain”]. " Country: ". $row[“Country”]. " City " . $row[“City”] . “
”;
}
} else {
echo “0 results”;
}

$conn->close();
?>  

</body>
</html>

At this stage what I need help with is to connect http://pintotours.net/TEMP/TEST/search.html
with the above php script.

Thanks

Hopefully that’s not your real password - if it is, get it changed now!

Done!

May I ask an additional question?

Once I get all this working. i.e. link the search box to the script and obtaining the results, how can I have these results displayed in a template webpage?. I take that is possible, otherwise it’s all been a waste of time…

It’s definitely possible, but that also exceeds my level of knowledge. In principle though, you need to take the results of the search and loop through them one at a time, using PHP to render them out as HTML.

Hi

I’ve progressed a little, but it is time to stop and sort out the mess…

in http://pintotours.net/TEMP/TEST/test1.html

I connected the search box to the old script and it is working! I can’t believe it…

So, it’s time to clean up and look to the next stage: I need the results of the query to end up in a webpage template which I would like to start on but need to know how the data is going to arrive there.

Well, as i got stuck I decide to replace the mysql deprecated code. I don’t know if I did right but I am still stuck on
$query = mysql_query("SELECT * FROM Chains WHERE Country LIKE '%$searchq%' OR City LIKE '%$searchq%'") or die ("could not search");

......
$output = '';
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$searchq = $_POST['keyword'];
/*$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);*/
$query = mysql_query("SELECT * FROM Chains WHERE Country LIKE '%$searchq%' OR City LIKE '%$searchq%'") or die ("could not search");
$count = mysqli_result::$num_rows($query);
if($count == FALSE)

{
$output = 'There was no search results!';
}
else
{
while($row = mysqli_fetch_array($query)) {
echo <<<EOD
<table>
<tr>
<td>Chain : {$row['Chain']}</td>
<td>Country : {$row['Country']}</td>
<td>City : {$row['City']}</td>
<td>Top : {$row['Top']}</td>
<td>Medium : {$row['Medium']}</td>
<td>Low : {$row['Low']}</td>
</tr>
</table>
EOD;
// The above must be on a line by itself with no leading space of any kind

}
}

 echo "<p><a href='End.php?page=post&&post=$post_Chain'>$post_City</a></p></ br>";

}
?>

Could you help, please?

You have to replace ALL the mysql_ calls and not just some of them.

Hi felgall

I replaced all…except that one, but of course, I may have made some mistakes. It is not very clear how you are supposed to change them. I spent all day (that’s nearly 11 hours) searching and searching…

You left it as mysql. Is that how it should remain?

All help appreciated, before I lose all my remaining hairs!

No - you must change it. I was just showing you that you hadn’t.