I know theres a better way to PHP/MySql this...
Posted by: ddefesse
Posted on: 2005-10-18 22:22:00
Hi. I was hoping I could get some help. I'm not very good with PHP or MySql, and I'm self taught, so my scripts are very ugly. This is my first time making a database driven website. If you read this snippet you'll understand whats going on and what I'm trying to do. I know that I shouldnt be using a php switch: it's not OOP. I just don't know how to cross that gap.
<?php
// $limit="20"; // Define them here?
switch ($by)
{
case ("band"):
$sql = "Select
List.name, // all of this should be variable, but I can't make variables work here
List.band,
List.disk,
List.cost,
List.shipping,
List.note
From
List
Where
List.cost <> 'null' // also want this to be user variable
Order By // all of it should be vars...
List.band Desc,
Limit
20 // but don't know how.
" ;
$result = mysql_query($sql);
if (!$result) {
echo 'Band query failed, exiting.';
exit;
}
echo "Band order.";
echo "<table>n";
echo <<<END
<tr>
<td>Name</td>
<td>Band</td>
<td>Disk</td>
<td>Cost</td>
<td>Shipping</td>
<td>Notes</td>
</tr>
END;
break;
case ("cost"):
$sql = "Select
require 'axe.php' // contains connect()
<head><meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>index</title>
</head>
<body>
<?php
ini_set('error_reporting', E_ALL);
// connect() function connects us to the default database automagically.
connect();
// supposed to list all data on the active table
$by = ('band'); // using the switch
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { // filling rows and columns...
echo "t<tr>n";
foreach ($line as $col_value) {
echo "tt<td>$col_value</td>n";
}
echo "t</tr>n";
} // filled.
echo "</table>n";
mysql_free_result($result); // something to do with performance
// mysql_close($link);
?>
</body>
</html>
And there it is. The closest I can get to what I need without breaking everything is:
<?php
$state = $_GET['State'];
print($state); //to make sure you're getting what you wanted
$query = SELECT * ";
$query .= "FROM db ";
$query .= "WHERE State = '" . $state . "'
//the above method of coding the query is for neatness only
print($query); //so that you can see the query
//do the query and return errors if not right
if(!($dbquery = mysql_query($query, $dbconnect))){
print("MySQL reports this error: " . mysql_error());
exit;
}
?>
That code does what I am looking for (partially). It explains how to inject variables into SELECT... FROM... WHERE... but only three examples. What is ".=" What are the rules for '" "' and "' '" (single/double quote)? Somehow I feel that if the $_GET example had 4 variables instead of 3 I might wrap my head around it. I've been making no headway for 3 days straight. Someone please show me how easy this is. Thanks.
-John