Forum Moderators: coopster

Message Too Old, No Replies

Search php script for MySQL database

php, MySQL, database

         

kuruvi

9:04 am on May 5, 2011 (gmt 0)

10+ Year Member



I am a student and trying to make my own database in MySQL and use php to submit and retrieve data from MySQL. I want to do this all from a Web browser (OS: mac osx).

I am successful to submit data from a browser and also retrieve the submitted data from MySQL. Since I am a newbie, I have the following to problems to solve,

1. I can retrieve the data from MySQL and can view the results from the php file by opening it in a browser.

I don't know how to bring the php file output to a html page, so that I can view my MySQL data from a html page and I want to add more html codes to get better view of the results.

2. I want to add a search form in the html page, so that I can search the MySQL database and view the results back in html page.

3. I have a column named "tag" in my database and each row has several words on the tag column.

I want to have a link for each tag in my html page that can bring me the results of the corresponding tags.


Here's the script that I have done so far.

HTML form to submit data

<html><body>
<form enctype="multipart/form-data" action="randam_new.php" method="POST">
Title: <input type="text" name="title"><br>
Year: <input type="text" name = "year"><br>
Tags: <input type="text" name = "tag"><br>
DOI: <input type="text" name = "doi"><br>

<table>
<tr>
<td width="246">
Image: <input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table></form></body></html>

php script to write the submitted data into MySQL database

<?php
$uploadDir = 'images/';

$title=$_POST['title'];
$year=$_POST['year'];
$tag=$_POST['tag'];
$doi=$_POST['doi'];

if(isset($_POST['upload']))
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];


// get the file extension first
$ext = substr(strrchr($fileName, "."), 1);

// make the random file name
$randName = md5(rand() * time());


//$filePath = $uploadDir . $fileName;
$filePath = $randName . '.' . $ext;

$result = move_uploaded_file($tmpName, $uploadDir.$filePath);
if (!$result) {
echo "Error uploading file";
exit;
}

include '../library/config.php';
include '../library/opendb.php';

if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}


// Connects to your Database
mysql_connect("127.0.0.1", "Ramesh", "") or die(mysql_error()) ;
mysql_select_db("test") or die(mysql_error()) ;

$query = "INSERT INTO new2 (title, year, tag, doi, image ) ".
"VALUES ('$title', '$year', '$tag', '$doi', '$filePath')";

mysql_query($query) or die('Error, query failed : ' . mysql_error());

include '../library/closedb.php';

echo "<br>Files uploaded<br>";

}
?>


php script to retrieve the data from MySQL


<?php
// Connects to your Database
mysql_connect("127.0.0.1", "Ramesh", "") or die(mysql_error()) ;
mysql_select_db("test") or die(mysql_error()) ;

//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM new2") or die(mysql_error());
//Puts it into an array
while($info = mysql_fetch_array( $data ))

{
//Outputs the image and other data
Echo "<b>Title:</b> ".$info['title'] . "<br> ";
Echo "<b>Year:</b> ".$info['year'] . " <br>";
Echo "<b>Tag:</b> ".$info['tag'] . " <br>";
Echo "<b>DOI:</b> ".$info['doi'] . " <br>";
Echo "<img src=images/".$info['image'] ."> <hr>";
}
?>


Please assist me to get better coding.

topr8

12:14 pm on May 5, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



welcome to WebmasterWorld.

... i would like to wish you good luck with your studies.

the forum charter clearly states:
Fix my code/Do My Homework posts are not all that welcome

i apologise in advance if you are not working on a school project.

kuruvi

12:28 pm on May 5, 2011 (gmt 0)

10+ Year Member



It's for my own database and want to get overview of research stuffs. No school project and I'm completing my graduate at university.

rocknbil

4:33 pm on May 5, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member




1. I can retrieve the data from MySQL and can view the results from the php file by opening it in a browser.


You appear to be on your way with this one . . .

I don't know how to bring the php file output to a html page, so that I can view my MySQL data from a html page and I want to add more html codes to get better view of the results.


You don't put PHP in an HTML page. By default, PHP will only execute files with a PHP extension, however, you **can** configure your server to parse .htm(l) extensions as php. It's just not a great idea, PHP should stay php, htm(l) should stay HTML.

However, nearly all of what PHP does is output HTML to a browser.

You can use the echo or print command, or drop "in and out of PHP" - I prefer the former.

(Assuming you have executed mysql_fetch_array() or similar and stored results in $row...)

$some_content = "<p>" . $row['title'] . "</p>";
echo $some_content; // or print $some_content;

or

<p><?php echo $row['title']; ?></p>


2. I want to add a search form in the html page, so that I can search the MySQL database and view the results back in html page.


Looks like you're on your way with the forms. What you do is parse and cleanse input values from $_GET or $_POST which is determined by your form action. Then you use the submitted velues in a query. Like

// This is one example of cleansing - remove anything but letters, numbers, spaces, basic punctuation
// Not the greatest, but cleansing is condition-specific
$search = preg_replace('/[^a-z\d\'\"\s\.\,]+/i','',$_POST['search']);

$query = "select * from some_table where yourfield='. mysql_real_escape_string($search) . "'";

Learn it now, before bad habits start to form (and they will, they always do, for all of us:) the most important thing you can learn about programming is not what you can do with it, it's how to properly cleanse input.

3. I have a column named "tag" in my database and each row has several words on the tag column. ... I want to have a link for each tag in my html page that can bring me the results of the corresponding tags.


When you say "several words," what do you mean? Like, comma separated?

id|tag
1|this,that,the other thing

This is the beginning of a poor database design, and I'll tell you why. If you were to search on these terms, it becomes very unwieldy, very fast. You are limited to the LIKE operator or a regexp to search on these fields, both of which are fairly slow. You will likely be forced to do in programming what you can do with straight mysql select statements, which will make your programming unnecessarily complex.

The better solution is to use multiple tables and joins in what is callded database normalization. Consider . . .

products table
id|product
123|Widget

tags table
id|product_id|the_tag
12|123|green
13|123|blue
14|123|green

Here we have a product called Widget with three tags, red, blue, and green. Instead of like or regexp, we can use the equality operator and a join:

$query = "select products.product,tags.the_tag from products, tags where products.id=tags.product_id";

This will return three rows:

Widget|red
Widget|blue
Widget|green

It will be faster and more efficient. (A more common solution is to use inner, outer, right, or left join operators but the equality in the where works just as well.)

Look into database normalization and mysql joins. Many programmers cobble something together that works, but in doing so they begin to develop bad habits that don't scale and often have to be scrapped later. Investigate input cleansing and efficient usage of database queries while you're still learning it, you'll be glad you did.