I am trying to create an "explore" page on a site I am developing at the minute. Here are images of the page and the database for visual reference.
Database: http://gyazo.com/a48eb00458d3a93845bc666af23775c1
Webpage: http://gyazo.com/69d0889c77d784d12448827b603891be
Here is my current PHP Script:
$connect = mysql_connect("localhost","root","root");
if (!$connect) {
die('lel' . mysql_error());
}
$search = $_GET['make'];
mysql_select_db("dapper");
$query = mysql_query("SELECT * FROM posts WHERE make = '$search'");
while ($rows = mysql_fetch_array($query)) {
$id = $rows['id'];
$photographer = $rows['photographer'];
$carowner = $rows['car-owner'];
$make = $rows['make'];
$event = $rows['event'];
$author = $rows['author'];
$date = $rows['date'];
echo "
<article>
<img src='uploads/$id.jpg'>
</article>";
}
fclose($connect);
?>
And here is my HTML markup for searching:
<ul>
<h4>Make</h4>
<li>Vw</li>
<li>Audi</li>
</ul>
<ul>
<h4>Event</h4>
<li>H20i</li>
<li>Titanic Dubs</i></li>
<li>Dubshed</li>
<li>Players Show</i></li>
</ul>
As you can see from the webpage image the user should be able to search for events, makes and photographers. However I have only managed to get the script to successfully search for one thing. I feel I haven't explained this the best but I am NOT trying to allow the user to search for eg: photographers and events in the same search.
Thanks in advance.
Jamie McArdle,
PHP Noob
As per OP to close the question:
$search2 = $_GET['event']; - WHERE make = '$search' OR event = '$search2' or by replacing OR with AND if your rows match what you have in your present rows for those criterias.
A suggestion:
You may be best using dropdown menus or radio buttons, then using the values instead of multiple href's.
That way, your page won't be filled with links, should the criterias grow larger over time.
Footnotes:
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
I suggest you look into mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Edit:
For results or not:
if($query){
while ($rows = mysql_fetch_array($query)) {
$id = $rows['id'];
$photographer = $rows['photographer'];
$carowner = $rows['car-owner'];
$make = $rows['make'];
$event = $rows['event'];
$author = $rows['author'];
$date = $rows['date'];
echo "
<article>
<img src='uploads/$id.jpg'>
</article>";
}
}
else{
echo "No results.";
}
Related
Here's my code:
<?php
//recently added
$result = mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");
if ($result == 1){
?>
<script>
jQuery(document).ready(function(){
jQuery(".eltdf-psc-slide").addClass("no-background");
});
</script>
<?php
}
//=============
?>
Basically what I'm trying to do is checking and see if the value stored in the $shadowless_background_table "DB" is == 1 and I only want that column (background). I have browse the web, but what I see are examples with while loops which I was wondering if I could do something like this instead.
If you want to fetch a single record based on a condition you can do this -
$result = mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");
if (mysql_num_rows($result)>0){
$fetchedColum = mysql_result($result, 0, 'COLUMN_NAME');
}
There are couple of issues with your code.The first thing that i have noticed is that you are using mysql API instead of PDO.I don't blame you since the internet is full of old tutorials and you probably didn't have a chance to get some guidance.
MySql is getting old It doesn't support modern SQL database concepts such as prepared statements, stored procs, transactions etc... and it's method for escaping parameters with mysql_real_escape_string and concatenating into SQL strings is error prone and old fashioned.
Organize your project better.
As i have seen from this example you probably have a poor project organization.You should consider reading about PSR Standards
And to go back to your question ,and to update it a bit.
Instead of doing
mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");
I would do it this way:
<?php
$host = "localhost";
$username = "user name of db";
$password = "password of db";
$dbname = "database name ";
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//your data
$id = 1; // id
$stmt = $conn->prepare("SELECT background FROM database_name WHERE id=:id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$data = $stmt->fetchAll();
foreach ($data as $row) {
echo $row["row_name"];
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
Go read more about PHP in general ,it will help you out a lot.The biggest problem is that there are so much wrong tutorials and references or they are just old.And people learn from wrong sources.
I had the same problem ,but thanks to right people on this site i have managed to learn more.
My suggestion is that you read about PSR,PDO and PHP in general!!!
Also a thing you should consider reading about is security in php.
Good luck mate :D
I need some help with populating a dropdown list, I have been searching around to find solution with some trial and errors but I must admit, I never touch PHP. I have the following code but it does not display anything, I assume my problem is with the connection, so my question is how to build such a connection:
<?php
$sql = mysql_query("SELECT ProvinceNameFR FROM Province");
while ($row1 = mysql_fetch_array($sql)) {
echo "<option value='".$row1['value']."'>".$row1['value']."
</option>";
}
?>
Where do I go from that? I am involved in a project that someone else developed.
Thanks
You've got some work ahead of you. First, use MySQLi or PDO instead of MySQL. MySQL is deprecated and will eventually be removed in future versions. http://php.net/manual/en/book.mysqli.php
Some obvious mistakes. You're query is SELECT ProvinceNameFR FROM Province but you're trying to get $row1['value'] when you should be using $row1['ProvinceNameFR'] because that's the column you selected.
You also need to wrap your <option>'s with the actual <select> tag. You may already be doing that, I just don't see it here.
so
<?php
$sql = mysql_query("SELECT ProvinceNameFR FROM Province");
echo "<select>";
while ($row1 = mysql_fetch_array($sql)) {
echo "<option value='".$row1['ProvinceNameFR']."'>".$row1['ProvinceNameFR']."
</option>";
}
echo "</select>";
?>
This is assuming everything is working database side. If not try adding var_dump(mysql_error()); at the end. That should print out the latest error and help you find out what's going wrong.
I would recommend using PDO to connect to a MySQL db as the older mysql_query, mysql_connect systems are depreciated.
A very basic way to get started would be:
$db = new PDO('mysql:host=HOST;dbname=DATABASENAME', USERNAME, PASSWORD);
$query = "SELECT * FROM Province";
$stmt = $db->query($query);
$results['data'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<select>';
foreach ($results['data'] as $row){
echo "<option value='".$row['ProvinceId']."'>".$row['ProvinceNameFR']."</option>";
}
echo '</select>';
You also need the <select> html wrappers around the options. And your field names need to be set to match the what is in the table. I have also assumed that there should be an ID in the value field.
I created a phonebook in HTML, PHP and MySQL. All it does is:
Add Contact
Delete Contact
View all contacts
This works perfectly on my local machine within XAMPP. I transferred everything online to my godaddy hosting account. I had to create new connection details to the database and everything worked well except...
now -> Delete Contact is not working. It outputs 'Contact deleted' but nothing is deleted.
Here is the source code below, can someone assist?
<?php
require 'database/connect.php';
if(isset($_POST['firstname'])) {
$name = $_POST['firstname'];
$name = mysql_real_escape_string($name);
$query = "DELETE FROM contacts WHERE first_name='{$name}'";
$result = $db->query($query);
if($result) {
print 'Contact deleted';
} else {
print 'Error: '. $db->errno;
}
} else {
print 'Nothing is set';
}
$db->close();
print '<br>';
print '<form action="index.html" action="GET">';
print '<input type="submit" value="Main Screen">';
print '</form>';
?>
You are mixing MySQL APIs usng mysql_real_escape_string() which should be its mysqli_ equivalent mysqli_real_escape_string().
Those different APIs do not intermix with each other.
While passing the DB connection parameter to it:
Procedural style
$name = mysqli_real_escape_string($db,$name);
or as Object oriented style:
$name = $db->real_escape_string($name);
From the manual: http://php.net/manual/en/mysqli.real-escape-string.php
Object oriented style
string mysqli::escape_string ( string $escapestr )
Procedural style
string mysqli_real_escape_string ( mysqli $link , string $escapestr )
$query = "DELETE FROM contacts WHERE first_name='{$name}'";
maybe if you write it like:
$query = "DELETE FROM contacts WHERE first_name='$name'";
without the "{}" because the query is looking for something like : "{some people}" including the "{}"
you are getting the "Contact deleted" because is deleted the term where found {some people} or it delete 0 items and it's a valid query with 0 rows affected.
Sorry for the bad english... :( i hope the answer can help you...
Ok, I'm following a youtube guide on how to create a very simple blogging system using PHP/MySQL as I'd like to get to learn these 2 languages a bit more. I'm creating this in my localhost, permissions set-up correctly.
The problem is, when I go onto localhost/tables.php, it comes up as white screen which it's supposed to, but it's not creating the relevant tables within the database?
Here's the code I'm using:
mysql.php
<?php
mysql_connect('localhost','username','password'); //where localhost is the host, username is the relevant username and password is the relevant password.
mysql_select_db('database'); //where database is the chosen database in which to drop the tables.
?>
tables.php
<?php
include "mysql.php";
$table = "ENTRIES";
mysql_query ("CREATE TABLE IF NOT EXISTS `$table` (`ID` INT NOT NULL AUTO_INCREMENT , PRIMARY KEY ( `id` ) )");
mysql_query ("ALTER TABLE `$table` ADD `TITLE` TEXT NOT NULL");
mysql_query ("ALTER TABLE `$table` ADD `SUMMARY` TEXT NOT NULL");
mysql_query ("ALTER TABLE `$table` ADD `CONTENT` TEXT NOT NULL");
?>
Nothing is appearing in the error log which is frustrating and not helping me diagnose the problem.
Any help would be much appreciated! Thanks.
As you have no errors run this code to show if you have created created the table ENTRIES.
<?php
include "mysql.php";
$result = mysql_query("SHOW COLUMNS FROM `ENTRIES`");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
}
?>
NOTE As you are starting with MySQL you would be advised to use PDO in place of the deprecated mysql_.
Here is a good tutorial
EDIT
Following comments the following code lists databases and tables on server(Note uses deprecated mysql_ function).
Ensure that the proper parameters replace "XXX".
<?php
$host= "localhost";
$username="XXX";
$password="XXX";
$database="XXX";
$link = mysql_connect($host,$username,$password); //where localhost is the host, username is the relevant username and password is the relevant password.
$db_list = mysql_list_dbs($link);
while ($row = mysql_fetch_object($db_list)) {
echo $row->Database . "\n";
echo "<BR>";
}
echo "<BR>";
$result = mysql_list_tables($database);
$num_rows = mysql_num_rows($result);
for ($i = 0; $i < $num_rows; $i++) {
echo "Table: ", mysql_tablename($result, $i), "\n";
echo "<BR>";
}
?>
Nothing is appearing in the error log which is frustrating and not helping me diagnose the problem
So your first poblem is to find out why it's not logging any errors. BTW it would also be a good idea to inject some echo / print statements to find out where it's failing.
Forget about the MySQL stuff and try:
<?php
trigger_error("Testing", E_USER_WARNING);
?>
Even though (once you've got the error reporting sorted out) you should get an error logged it will likely only contain a limited amount of information. Any time you call a mysql function, be via mysql_, mysqli or PDO, you should poll the return value and handle any error - even if it's just to echo the value to the screen.
It's saying that I haven't selected a database
Possibly the user account you are connecting as does not have permission to access the database.
I am brand new to php/mysql, so please excuse my level of knowledge here, and feel free to direct me in a better direction, if what I am doing is out of date.
I am pulling in information from a database to fill in a landing page. The layout starts with an image on the left and a headline to the right. Here, I am using the query to retrieve a page headline text:
<?php
$result = mysql_query("SELECT banner_headline FROM low_engagement WHERE thread_segment = 'a3'", $connection);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo $row["banner_headline"];
}
?>
This works great, but now I want to duplicate that headline text inside the img alt tag. What is the best way to duplicate this queries information inside the alt tag? Is there any abbreviated code I can use for this, or is it better to just copy this code inside the alt tag and run it twice?
Thanks for any insight!
You are, as the comment says, using deprecated functions, but to answer your question, you should declare a variable to hold the value once your retrieve it from the database so that you can use it whenever your want.
<?php
$result = mysql_query("SELECT banner_headline FROM low_engagement WHERE thread_segment = 'a3'", $connection);
if(!$result) {
die("Database query failed: " . mysql_error());
}
$bannerHeadline = "";
while ($row = mysql_fetch_array($result)) {
$bannerHeadline = $row["banner_headline"];
}
echo $bannerHeadline; //use this wherever you want
?>
It is hard to help without knowing more. You are pumping the results into an array, are you expecting to only return one result or many banner_headline results? If you will only ever get one result then all you need to do is something like this:
PHP:
$result = mysql_query("
SELECT `banner_headline`
FROM `low_engagement`
WHERE `thread_segment` = 'a3'", $connection) or die(mysql_error());
// This will get the zero index, meaning first result only
$alt = mysql_result($result,0,"banner_headline");
HTML:
<html>
<body>
<!--- Rest of code -->
<img src="" alt="<?php echo $alt ?>">
On a side note, you should stop using mysql-* functions, they are deprecated.
You should look into PDO or mysqli