Using mysql datebase and want display query results using PHP

Vengance_01

Supreme [H]ardness
Joined
Dec 23, 2001
Messages
7,731
Well I have been teaching myself sql and php. I want to be able to query a mysql database and display the results with HTML and php. Just not sure how to go about this. Any decent sites for a newbie like myself.
 
well the query would be

select * from table

then in php something like

$print(


something..lol that is about all i know, you would need to define parameters in php to match the columns in mysql
 
Yes I have the query, but I need I guess a template to see I would use PHP to output the results on a simple HTML page.
 
Just a quick top of my head example:

mysql_connect($host, $user, $password);
@mysql_select_db($database) or die ("Unable to select database");
$sqlquery = "select name, number from coolpeople";
$query = mysql_query($sqlquery);
if (mysql_num_rows($query) > 0) {
for($i = 0; $i < mysql_num_rows($query); $i++) {
$row = mysql_fetch_assoc($query);
print "$row[name] $row[number]";
}
}
 
Just a quick top of my head example:

mysql_connect($host, $user, $password);
@mysql_select_db($database) or die ("Unable to select database");
$sqlquery = "select name, number from coolpeople";
$query = mysql_query($sqlquery);
if (mysql_num_rows($query) > 0) {
for($i = 0; $i < mysql_num_rows($query); $i++) {
$row = mysql_fetch_assoc($query);
print "$row[name] $row[number]";
}
}

...or if you don't like using arrays, you do it using objects
Code:
mysql_connect($host, $user, $password);
 @mysql_select_db($database) or die ("Unable to select database");
 $sqlquery = "select name, number from coolpeople";
 $query = mysql_query($sqlquery);
 if (mysql_num_rows($query) > 0) 
{
      while ($record = mysql_fetch_object($query))
      {
          //substitute col1, col2, etc.. with column names from your DB 
          echo($record->col1 . " - " . $record->col2...etc..); 
      }
}
 
Personally, I reccomend using the mysqli library instead of the mysql library. Much nicer to work with and better performance.
 
Personally, I reccomend using the mysqli library instead of the mysql library. Much nicer to work with and better performance.

Agreed, since it allows you to use parametrized queries, but there is one major drawback, it only works with MySQL databases. He'd be in for a lot of hurt should he need to migrate the app to say, an MSSQL database.

You could create your own database class that abstracts the database functions so that you can port your code to any database platform. So instead of a bunch of mysql_query($SQL) statements all over the place you could instead create an object with a more generic function (E.g $db->query($SQL)), and let the class handle the type of database.
 
Personally, I reccomend using the mysqli library instead of the mysql library. Much nicer to work with and better performance.

I was not aware of this - is there any particular reason why it's better performing? I'll be tied to mySQL anyways, portability not an issue here.
 
I was not aware of this - is there any particular reason why it's better performing? I'll be tied to mySQL anyways, portability not an issue here.

i'm not sure it's any faster speed-wise than the regular mysql function, but it more than makes itself worthwhile simply for the much safer handling of data..
 
only reason I am using MySQL is its free along with PHP and Apache webserver. This is strictly for personal learning.
 
i'm not sure it's any faster speed-wise than the regular mysql function, but it more than makes itself worthwhile simply for the much safer handling of data..

Ahkay - "safer" meaning additional protection against the usual baddies like injection, etc? In addition to parameterized queries, that sounds mighty interesting and something to play with.

Of course, the issue than is for portability of my app amongst LAMP hosts, who has the mySQLi extension installed.
 
Guys can you see whats wrong with my code? I can't figure it out. I have PHP and apache 2.2 setup and working. But for some reason I can't my code to output right

Code:
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "vengance") or die(mysql_error());
mysql_select_db("test1") or die(mysql_error());

// Get all the data from the "users" table
$result = mysql_query("select first_name, last_name, email from users") 
or die(mysql_error());  

echo "<table border='1'>";
echo "<tr> <th>First</th> <th>Last</th> <th>email</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
	// Print out the contents of each row into a table
	echo "<tr><td>"; 
	echo $row['first_name'];
	echo "</td><td>"; 
	echo $row['last_name'];
	echo "</td><td>";
	echo $row['email'];
	echo "</td></tr>"; 	
} 

echo "</table>";
?>

And this is what I get as an output when I try and run the file

errorphpor2.jpg
 
I figured it out. It was my install of PHP. once I repaired it, everything worked. ;)Thanks for the help.
 
Of course, the issue than is for portability of my app amongst LAMP hosts, who has the mySQLi extension installed.

IMHO - if a host doesn't have mysqli, they're pretty much in the same boat as a host that doesn't have PHP5 - they don't deserve your business.
 
alright guys I got a new one. I am trying to use a simple text box to allow a user to enter valid last name in the database. I want then to pull the information based on the input of the user. See code. I am sure its all wrong, but please give me some guidance. This stuff is not easy.

Code:
<?php
// This Query is desgined to allow a user to search for a single user and pull there information
// Jeff Flogerzi Version 1


// Make The MYSQL Connection
require_once ('mysql_connect.php');

$result = mysql_query("select first_name, last_name, email from users where last_name ='$_POST['last_name']' ") 
or die(mysql_error());

if ($result) { // If Ran ok, Display the results

echo "<table border='1'>";
echo "<tr> 
	<th>First Name</th> 
	<th>Last Name</th> 
	<th>Email Address</th> 
	</tr>";

// keeps getting the next row until there are no more to get

$bg = '#ffffdd';
while($row = mysql_fetch_array( $result )) {
	
// Print out the contents of each row into a table
	echo "<tr><td>"; 
	echo $row['first_name'];
	echo "</td><td>"; 
	echo $row['last_name'];
	echo "</td><td>";
	echo $row['email'];
	echo "</td></tr>"; 

} 
echo "</table>";

mysql_free_result ($result);

} else {
	echo '<p>The current information is not avabablie at this time. We sorry.</p>';
}
mysql_close();


?>

<h2>Pull User Information</h2>
<form action="experimental.php" method="post">
	<p>Users Last Name: <input type="text" name="last_name" size="15" maxlength="25" value="<?php if (isset($_POST['last_name'])) echo $_POST['last_name']; ?>" /></p>
	<p><input type="submit" name="submit" value="Search!" /></p>
	<input type="hidden" name="submitted" value="TRUE" />
</form>
 
Try this, I wasn't able to test it but the syntax gives no errors in Zend...

Code:
<?php
// This Query is desgined to allow a user to search for a single user and pull there information
// Jeff Flogerzi Version 1


// Make The MYSQL Connection
//require_once ('mysql_connect.php');

$result = mysql_query("select first_name, last_name, email from users where last_name ='$_POST[last_name]' ") or die(mysql_error());

if ($result) { // If Ran ok, Display the results

echo "<table border='1'>";
echo "<tr> 
	<th>First Name</th> 
	<th>Last Name</th> 
	<th>Email Address</th> 
	</tr>";

// keeps getting the next row until there are no more to get

$bg = '#ffffdd';
while($row = mysql_fetch_array( $result )) {
	
// Print out the contents of each row into a table
	echo "<tr><td>"; 
	echo $row['first_name'];
	echo "</td><td>"; 
	echo $row['last_name'];
	echo "</td><td>";
	echo $row['email'];
	echo "</td></tr>"; 

} 
echo "</table>";

mysql_free_result ($result);

} else {
	echo '<p>The current information is not avabablie at this time. We sorry.</p>';
}
mysql_close();


?>

<h2>Pull User Information</h2>
<form action="experimental.php" method="post">
	<p>Users Last Name: <input type="text" name="last_name" size="15" maxlength="25" value="<?php if (isset($_POST['last_name'])) echo $_POST['last_name']; ?>" /></p>
	<p><input type="submit" name="submit" value="Search!" /></p>
	<input type="hidden" name="submitted" value="TRUE" />
</form>
 
the next page you'll want to use the $_POST['last_name'} to get the last name from the form.

then, make a connection to the mysql server again and do a mysql_real_escape_string function call with the $_POST data to strip out any mean code someone may want to inject.
 
not sure what do you mean? I am still pretty new when it comes to this stuff.

the mysql_real_escape_string() function is used to "sanitize" your user input. This prevents SQL Injection Attacks, a very common tactic used by hackers to compromise your database and/or website.
In very simple terms, SQL databases are susceptible to the careless use of single quotes, so an innocent looking text input like O'Donnell would break your application if the single-quote is not escaped properly; in MySQL you would properly escape a single quote like this: O\'Donnell, mysql_real_escape_string handles that kind of sanitation for you automatically.

To use it, you would run your text input through it like this:
$lastname = mysql_real_escape_string($_POST['lastname']);
$result = mysql_query("SELECT * FROM table WHERE last_name = '$lastname' ");
 
the mysql_real_escape_string() function is used to "sanitize" your user input. This prevents SQL Injection Attacks, a very common tactic used by hackers to compromise your database and/or website.
In very simple terms, SQL databases are susceptible to the careless use of single quotes, so an innocent looking text input like O'Donnell would break your application if the single-quote is not escaped properly; in MySQL you would properly escape a single quote like this: O\'Donnell, mysql_real_escape_string handles that kind of sanitation for you automatically.

To use it, you would run your text input through it like this:
$lastname = mysql_real_escape_string($_POST['lastname']);
$result = mysql_query("SELECT * FROM table WHERE last_name = '$lastname' ");
Well that I understand. My question is how do I just show just the results. Currently the page will still include the search box and search button.
 
so you are looking for a page that has results and then this search box/button at the bottom?
 
Well what I want is just the page showing the search box. Then after you hit search, I want that to dissapear and then just have the results displayed along with a footer and header file.(These I still would have to make)
 
Well what I want is just the page showing the search box. Then after you hit search, I want that to dissapear and then just have the results displayed along with a footer and header file.(These I still would have to make)

Not sure why you want the search box to "disappear" after the user enters a query, but whatever. The easiest way to do this is to have the search page submit it's data to a separate page that processes the results and displays them in the format you want. This might prove to be a pain in the butt for people who want to do multiple searches, since it means they'll have to find their way back to your search page each time they want to do another query.
 
Yea the more I thought about it, the more that makes sense. The only other thing is the table's headers show before a search is even done. Anyway to remove this?
 
when I went through my first C++, we started out writing "pseudo code" where we just brainstormed what we were trying to accomplish first. here is what I think you are trying to do in pseudo code.


----form.html---
Start form code that will go to "search_disp.php"
Have text box to input what text to search with
have a submit button


----search_disp.php---
Grab data from previous page (via the "method" of the form...generally POST) based off of text box's name
connect to data base
check if any data was entered into the text box
if text was entered
(
sanitize text with mysql_real_escape_string()
select a database to use
build sql string and store in a variable
use variable in mysql query
spit out data into your table (use the "while($row = mysql_fetch_array( $result ))" method...very easy this way)

after data has been spit out, either enter same code as form.html to put an option to search for another record...or just include form.html to display again.
)
if no text was entered
(
redirect back to form.html
)


does that help at all? I still do this to work out my segments of code when I get into techniques that I'm unfamiliar with. It breaks the project down into manageable pieces...at least for me. keeps me from getting frustrated and discouraged.
 
oh, one more trick that we can do here on the forums...instead of using "code" in brackets to show your code...you can put "php" in there and it will colorize the text and may make it easier to read for some.
 
wow thanks for the tip on that. I did not know we could do that. I will go back redesign my code using bits from my first version. ;) Thanks for everyone's help. One last question,does anyone know a tool that will validate PHP code just on syntax alone?
 
I use PHP Designer 2007. It does a good job of keeping my parenthesis and colons where they should. It will also suggest functions (custom ones you've written as well as built-in) and variables that have already been defined as you type. It is also pretty cheap for an IDE.
 
wow thanks for the tip on that. I did not know we could do that. I will go back redesign my code using bits from my first version. ;) Thanks for everyone's help. One last question,does anyone know a tool that will validate PHP code just on syntax alone?

Notepad++ is good for that plus a lot more. If you're looking for an IDE, Eclipse is great.
 
Aye it can take a bit of mental gymnastics before everything clicks and you start thinking like the machine would ;)
 
Back
Top