PHP Echo results where input LIKE $_GET - php

I'm trying to implement a hashtag system into my website. I have it set so user input that has a hashtag gets converted into a link to hashtag.php?q=%23$1 that echo's "Results for '.$_GET["q"].':"; which works fine, but it doesn't actually display any posts.
For example, I have a post saying "This #website sucks" which is echoed out as
This #website sucks
But the following page only displays
Results for #website:
and the rest is blank. Here's my code for hashtag.php:
echo 'Results for '.$_GET["q"].':';
$connect = mysql_connect("localhost","root","");
mysql_select_db("database",$connect);
$mysql = "SELECT * FROM table WHERE input LIKE '".$_GET['q']."' ";
$myData = mysql_query($mysql, $connect);
while ($record = mysql_fetch_array($myData)){
echo $record['input'];
}
I'm working on using mysqli before I make the site public by the way.

Try putting % percentage signs on either side of the $_GET["p"] in your query. Don't forget to escape the $_GET["q"] as well. That'd be more important than using mysqli ;)
$mysql = "SELECT * FROM table WHERE input LIKE '%".mysql_real_escape_string($_GET['q'])."%' ";

Related

Unique page for each row in database with PHP

I have been trying to create a unique page for each row in my database. My plan is to create a dictionary.php?word=title url, where I can display the description and title of that specific ID. My datbase is contains id, term_title and term_description.
I'm fresh outta the owen when it comes to PHP, but I've managed to atleast do this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Cannot connect to database." . mysqli_connect_error());
}
if (isset($_GET['id']))
{
$id = (int) $_GET['id'];
$sql = 'SELECT * FROM dbname WHERE id = $id LIMIT 1 ';
}
$sql = "SELECT * FROM terms";
$result = $conn->query($sql);
mysqli_close($conn);
?>
I'm really stuck and I dont know what the next step is, I've added the <a href='dictionary.php?=".$row["id"]."'> to each word I want to be linked, and this is properly displayed in the main index.php file (where all my words are listed with <li>. This is my code for this:
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<a href='dictionary.php?=".$row["id"]."'><li class='term'><h4 class='term-title'>" . $row["term_title"]. "</h4></li></a>";
} else {
echo "No words in database.";
}
?>
How do I create this unique page, only displaying title and description for that id? How do I add ?word= to the url?
Thanks for taking your time to help me.
Update from years later: Please, please use parameters when composing your SQL queries. See Tim Morton's comment.
You're on the right track, and ajhanna88's comment is right, too: you want to be sure to include the right key ("word" in this case) in the URL. Otherwise, you're sending a value without telling the page what that value's for.
I do see a couple other issues:
When you click on one of the links you created, you're sending along $_GET["word"] to dictionary.php. In your dictionary.php code, however, you're searching for your word by "id" instead of by "word". I'm guessing you expect users to search your dictionary for something like "celestial" and not "1598", so try this instead:
if (isset($_GET['word'])) {
$word = $_GET['word'];
$sql = 'SELECT * FROM dbname WHERE word = $word LIMIT 1 ';
}
BUT! Also be aware of a security problem: you were letting the user put whatever they want into your query. Take a look at the classic illustration of SQL injection. To fix that, change the second line above to this:
`$word = $conn->real_escape_string($_GET['word']);`
Another problem? You're looking for the word exactly. Instead, you'll probably want to make it case insensitive, so "Semaphore" still brings up "semaphore". There are plenty of ways to do that. The simplest way in my experience is just changing everything to lowercase before you compare them. So that $word assignment should now look like this:
`$word = $conn->real_escape_string(strtolower($_GET["word"]));`
And your query should look something like this:
`$sql = "SELECT * FROM dbname WHERE word = LOWER('$word') LIMIT 1 ";`
Next! Further down, you overwrite your $sql variable with SELECT * FROM terms, which totally undoes your work. It looks like you're trying to show all the words if the user doesn't provide a word to look up. If that's what you're trying to do, put that line in an else statement.
Your $result looks fine. Now you just have to use it. The first step there is to do just like you did when you tested the connection query (if(!$conn)...) and check to see that it came back with results.
Once you have those results (or that one result, since you have LIMIT 1 in your query), you'll want to display them. This process is exactly what you did when printing the links. It's just that this time, you'll expect to have only one result.
Here's a real basic page I came up with from your code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";
$conn=new mysqli($servername,$username,$password,$dbname);
if($conn->connect_errno){
die("Can't connect: ".$conn->connect_error);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Dictionary!</title>
</head>
<body>
<?php
if(isset($_GET["word"])){
$word = $conn->real_escape_string(strtolower($_GET["word"]));
$sql = $conn->query("SELECT * FROM dictionary WHERE word=LOWER('".$word."') LIMIT 1");
if(!$sql){
echo "Sorry, something went wrong: ".$conn->error_get_last();
} else {
while($row=$sql->fetch_assoc()){
echo "<h2>".$row["word"]."</h2>";
echo "<p>".$row["definition"]."</p>";
}
}
} else {
$sql = $conn->query("SELECT word FROM dictionary");
if(!$sql){
echo "Sorry, something went wrong: ".$conn->error_get_last();
} else {
echo "<p>Here are all our words:</p><ul>";
while($row=$sql->fetch_assoc()){
echo "<li>".$row["word"]."</li>";
}
}
echo "</ul>";
}
?>
</body>
</html>
You should also take care to be consistent in your terminology. For this, my MySQL table had three columns: id, word, and definition. I dropped term since your URLs were using word. In my experience, it's best to keep the same terminology. It avoids confusion when your application gets more complicated.
Lastly, to answer your question about creating separate pages, you can see there that for a simple page like this, you may not need a separate page to display the definitions and the links -- just an if/else statement. If you want to expand what's in those if/else blocks, I'd suggest looking at PHP's include function.
You have a great start. Keep at it!

retrieving data from a mysql database

I have a sign up page that has input boxes where you would enter your name, email address and password. After submitting that form there is a sign in page where it checks to see if you are in the database by SELECT * FROM users WHERE name = '$_POST[name]' AND email = '[email]'. This all works fine, but when you actually get into the site on your account i want to have a message at the top that says 'Welcome back (name from database). To do this i used $name = mysql_query("SELECT first_name FROM users WHERE email = $email"); and had <?php echo $name ?> at the top. This won't work though. Why?
"mysql_query" has been deprecated, you want to use "mysqli_query" now. See here: http://php.net/manual/en/function.mysql-query.php
To answer your question, performing the query creates an array, you need to followup on that by fetching from the array.
If you are doing this in a procedural style then the final code should look something like this:
$link = mysqli_connect("localhost", "my_user", "my_password"); // connect to the database
$query="SELECT first_name FROM users WHERE email = '".$email."'"; // create the query. Note the quotes arounds the email variable.
$result=mysqli_query($link, $query); // run the query
$row=mysqli_fetch_array($result); // fetch the array that is returned from the query
$name=$row['first_name']; // assign the first_name field to the $name variable
echo "Hello ".$name.","; // output the variable

Retrieving information on a certain user PHP MySQL

I have created a booking system which uses a clients username from their log in to auto populate a user name field when making a booking. I am not sure of how to get other information like their full name and ID from the database into these fields. Below is the code I have used to verify log in and store their username:
<?php
// Start up your PHP Session
session_start();
// If the user is not logged in send him/her to the login form
if ($_SESSION["Login"] != "YES_client") {
header("Location: login.php");
}
$username = $_SESSION["username"];
?>
I have also implemented the user name in the field using the following code:
echo "<input type='text' name='name' class='form-control' id='FullInputName' value=" . $username . ">"
Is there something simple I am missing? I have tried various methods to display the full data like using $row["Client_ID"] etc but could not get this to work for only the client who is logged into the system. My SQL statement is as follows:
"SELECT * FROM client WHERE Client_username= $username"
I would like to use the Client_ID in the select statement also to make it Unique. I have tried but got various errors.
Any help would be much appreciated!
EDIT
This is the code I have now tried to implement:
$query = "SELECT * FROM client WHERE Client_username='$username'";
echo $query;
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
echo $row['Client_username'];
}
But it is not working correctly - I am receiving this error:
mysql_fetch_array() expects parameter 1 to be resource, boolean given
Starting with your query i think is not correct.
If you are selecting a row and the type is a VARCHAR you need to add single quotes like this:
"SELECT * FROM client WHERE Client_username= '$username'"
Later you can read the results like
(pseudocode) while($row = mysqli_fetch_array) $row['Client_username']
something like that.
Tell me if this works for you

CMS homepage in php

I am working on something it has 2 pages. One is index.php and another one is admin.php.I am making CMS page where you can edit information on the page yourself. Then it will go to the database, where the information is stored. I also have to have it where the user can update the information on the page. I am getting a little bit confused here.For instance here I am calling the database and I am starting a function called get_content:
<?php
function dbConnect(){
$hostname="localhost";
$database="blank";
$mysql_login="blank";
$mysql_password="blank";
if(!($db=mysql_connect($hostname, $mysql_login, $mysql_password))){
echo"error on connect";
}
else{
if(!(mysql_select_db($database,$db))){
echo mysql_error();
echo "<br />error on database connection. Check your settings.";
}
else{
return $db;
}
}
function get_content(){
$sql = "Select PageID,PageHeading,SubHeading,PageTitle,MetaDescription,MetaKeywords From tblContent ";
$query = mysql_query($sql) or die(mysql_error());
while ($row =mysql_fetch_assoc($query,MYSQL_ASSOC)){
$title =$row['PageID'[;
$PageHeading =$row['PageHeading'];
$SubHeading = $row['SubHeading'];
$PageTitle = $row['PageTitle'];
$MetaDescription =$row['MetaDescription'];
$MetaKeywords = $row['MetaKeywords'];
?>
And then on the index page and I am going to echo it out in the spot that someone can change:
<h2><?php echo mysql_result($row,0,"SubHeading");?>A Valid XHTML and CSS Web Design by WG.</h2>
I do know that the function is not finished I am still working on that part. What I am wondering is am I echoing it out right or I am way off. This is my first time messing with CMS in php and I am still learning it. I am working with navicat and text pad on this, yes I know it is old school but that is what I am being shown with. But my index is a form not a blog. I have seen many of CMS pages for blogs not to many to be used with forms. Any input will be considered thanks for reading my question.
Your question is a bit confusing and your code very incomplete. I'ts hard to say if you do it the right way since I don't see the rest of the script. You need to connect to the database there as well and get your data. The $row variable only exists in the while statement inside you function get_content() though.
You could complete the get_content() and use it in the index.php as well. Remember that the variables you define inside a function only is available there though. If you need the data outside that function you need to return the values you need and save them to some other variable there. Put if you do the same as you've started doing in the get_content() function in index.php, then you just have to echo the variables you define. Like this:
<h2><?php echo $SubHeading; ?></h2>
or you could also do it like this somewhere inside the php tags:
echo '<h2>{$SubHeading}</h2>';
I hope that answers your question.
EDIT:
What you need in the index.php page is exactly what you seem to be doing in the admin file. You need to connect to db using mysql_connect() and select db with mysql_select_db(). You then need to select the data from the db using the appropriate query with $query = mysql_query($sql). If it's more then one row you want to display you need to put it in a while loop otherwise (which seems to be the case here) you just need to do one $row = mysql_fetch_assoc($query). After that you can get the data using $row['column_name']. If you have more than one row you can just use $row['column_name'] in side the while loop to get each consecutive row's data.
Here is an example index.php:
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password') or
die('Could not connect: ' . mysql_error());
mysql_select_db('database_name')) or die('Could not select database: ' .
mysql_error());
$sql = "SELECT SubHeading FROM tblContent WHERE PageID='1' LIMIT 1;";
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
echo '<h2>{$row[\'SubHeading\']}</h2>';
mysql_close();
?>
This is just what you need to display the SubHeading from you database. You probably also need to handle your form and save the submitted data to the database in your admin.php file.

PHP site URL ID please Help!

Please could someone help im building my first website that pulls info from a MySQL table, so far ive successfully managed to connect to the database and pull the information i need.
my website is set up to display a single record from the table, which it is doing however i need some way of changing the URL for each record, so i can link pages to specific records. i have seen on websites like facebook everyones profile ends with a unique number. e.g. http://www.facebook.com/profile.php?id=793636552
Id like to base my ID on the primary key on my table e.g. location_id
ive included my php code so far,
<?php
require "connect.php";
$query = "select * from location limit 1";
$result = #mysql_query($query, $connection)
or die ("Unable to perform query<br>$query");
?>
<?php
while($row= mysql_fetch_array($result))
{
?>
<?php echo $row['image'] ?>
<?php
}
?>
Thanks
Use $_GET to retrieve things from the script's query (aka command line, in a way):
<?php
$id = (intval)$_GET['id']; // force this query parameter to be treated as an integer
$query = "SELECT * FROM location WHERE id={$id};";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) == 0) {
echo 'nothing found';
} else {
$row = mysql_fetch_assoc($result);
echo $row['image'];
}
There are many things to consider if this is your first foray into MsSQL development.
SQL Injection
Someone might INSERT / DELETE, etc things via using your id from your url (be careful!, clean your input)
Leaking data
Someone might request id = 1234924 and you expected id = 12134 (so some sensitive data could be shown, etc;).
Use a light framework
If you haven't looked before, I would suggest something like a framework (CodeIgniter, or CakePHP), mysql calls, connections, validations are all boilerplate code (always have to do them). Best to save time and get into making your app rather than re-inventing the wheel.
Once you have selected the record from the database, you can redirect the user to a different url using the header() function. Example:
header('Location: http://yoursite.com/page.php?id=123');
You would need to create a link to the same (or a new page) with the URL as you desire, and then logic to check for the parameter to pull a certain image...
if you're listing all of them, you could:
echo "" . $row['name'] . ""
This would make the link.. now when they click it, in samepage.php you would want to look for it:
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
//query the db and pull that image..
}
What you are looking for is the query string or get variables. You can access a get variable through php with $_GET['name']. For example:
http://www.facebook.com/profile.php?id=793636552
everything after the ? is the query string. The name of the variable is id, so to access it through your php you would use $_GET['id']. You can build onto these this an & in between the variables. For example:
http://www.facebook.com/profile.php?id=793636552&photo=12345
And here we have $_GET['id'] and $_GET['photo'].
variables can be pulled out of URL's very easily:
www.site.com/index.php?id=12345
we can access the number after id with $_GET['id']
echo $_GET['id'];
outputs:
12345
so if you had a list of records (or images, in your case), you can link to them even easier:
$query = mysql_query(...);
$numrows = mysql_num_rows($query);
for ($num=0;$num<=$numrows;$num++) {
$array = mysql_fetch_array($query);
echo "<a href=\"./index.php?id=". $row['id'] ."\" />Image #". $row['id'] ."</a>";
}
that will display all of your records like so:
Image #1 (links to: http://www.site.com/index.php?id=1)
Image #2 (links to: http://www.site.com/index.php?id=2)
Image #3 (links to: http://www.site.com/index.php?id=3)
...

Categories