Forum Moderators: coopster
Here is what I have already
<?
$db_server ="mysql.domain.com";
$db_name = "db_name";
$username = "user";
$password = "pass";
$dbh = @mysql_connect($db_server,$username,$password) or die
("Connection to $db_server with login '$username'/'$password' failed.");
$db = @mysql_select_db($db_name) or die
("Connection made. But database '$db_name' was not found.");
$query="SELECT col_2 FROM `my_table` WHERE id='4'";
$result=mysql_query($query);
echo "$result";
?>
I get "Resource id #2"
I'm pretty sure the select statement is right. It works from the control panel where I can run SQL.
you can put the result in an object: $object = mysql_fetch_object($result)
Access your column with:
$object->col_2
or you can fetch an array: $array = mysql_fetch_array($result)
or, in your case, the easiest way might be:
echo mysql_result($result, 0, "col_2");
<edit>Some Links:
[us4.php.net...]
[us4.php.net...]
[us4.php.net...]
</edit>
[edited by: sned at 7:23 pm (utc) on July 7, 2004]
$row=mysql_fetch_row($result);
echo $row;
Check out the mysql [php.net] part of the PHP manual.
$dbh = @mysql_connect($db_server,$username,$password) or die
("Connection to $db_server with login '$username'/'$password' failed.");
It means that if you are unable to connect then a message will be displayed showing your username and password. Beyond debugging I can't think of any reason do this. In fact it's a compromise to your security. I'd suggest replacing it with just a simple message like "Failed to connect to server".
Typically it's good practice to put your db info and connection in a separate file which you can include into whatever page your gonna use that database.
So put this in a file called db.php
<?php
$db_server ="mysql.domain.com";
$db_name = "db_name";
$username = "user";
$password = "pass";
$dbh = @mysql_connect($db_server,$username,$password) or die
("Failed to connect to server.");
$db = @mysql_select_db($db_name) or die
("Failed to select database.");
?>
Now back in the page you're working on put this at the very top to relace the code above:
<?php
include("db.php");
?>
Now when it comes to your title you can do it this way:
<html>
<head>
<title>
<?php
$query="SELECT col_2 FROM `my_table` WHERE id='4'";
$result=mysql_query($query);
$row=mysql_fetch_assoc($result);
echo $row['col_2'];
?>
</title>
<link rel="STYLESHEET" type="text/css" href="format.css">
</head>
Here is the Query that I think should work.
$query="SELECT * FROM 'myTable' WHERE myCol LIKE '$myVar'";
Right now I have
echo $row['price'];
But this only shows the first record because there is only one. I want to search the results and find which one has the lowest price and show that one.
$query="SELECT * FROM 'myTable' WHERE myCol LIKE '%$myVar%'" ORDER BY price DESC LIMIT 1;
This will only work if your price field is numeric rather than a string like $13.99.
[Note: in the LIKE clause you need to surround your search string with %'s - as in the example above]