
May 28th, 2006
05:04 AM
Neverside Newbie
Status: Offline!
Simple mySQL Query
I am new to php and I've manage to setup a database and connect to it but still cant find a good tutorial on how to query my database.
My database is called "practice" my table is called "contacts" and I have the following fields "ID, FIRST, LAST"
I want to show the ID FIRST and LAST of every entry where FIRST="Stephen"
Do I need to set any variables before hand?

May 28th, 2006
07:04 AM
http://www.cpphp.com/function.mysql-query.html
<?php
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
http://www.cpphp.com/function.mysql-connect.html
<?php
//variant 1: ommit localhost
$link = mysql_connect('/tmp/mysql', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
http://www.cpphp.com/function.mysql-select-db.html
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
?>
___________________
I code alot.

May 28th, 2006
11:58 AM
Neversidian
Status: Offline!
Try this, just put in your mysql username and password details.
<?php
// Connect to MySQL
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Select the DB
$db_selected = mysql_select_db('practise', $link);
if (!$db_selected) {
die ('Can\'t select db: ' . mysql_error());
}
$name = "Stephen";
$query = mysql_query("SELECT id, first, last FROM contacts WHERE first = '".$name."'");
while($r = mysql_fetch_array($query)) {
echo $r['id'] . "<br>" . $r['first'] . "<br>" . $r['last'] . "<br><br>";
}
mysql_close($link);
?>