提前为使用 mySQL 而不是另一个扩展而道歉。;-)
<?php // RAY_temp_rowan.php
error_reporting(E_ALL);
echo "<pre>";
// CONNECTION AND SELECTION VARIABLES FOR THE DATABASE
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??"; // GET THESE FROM YOUR HOSTING COMPANY
$db_user = "??";
$db_word = "??";
// OPEN A CONNECTION TO THE DATA BASE SERVER
// MAN PAGE: http://php.net/manual/en/function.mysql-connect.php
if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
{
$errmsg = mysql_errno() . ' ' . mysql_error();
echo "<br/>NO DB CONNECTION: ";
echo "<br/> $errmsg <br/>";
}
// SELECT THE MYSQL DATA BASE
// MAN PAGE: http://php.net/manual/en/function.mysql-select-db.php
if (!$db_sel = mysql_select_db($db_name, $db_connection))
{
$errmsg = mysql_errno() . ' ' . mysql_error();
echo "<br/>NO DB SELECTION: ";
echo "<br/> $errmsg <br/>";
die('NO DATA BASE');
}
// IF WE GOT THIS FAR WE CAN DO QUERIES
// CREATING A TABLE
$sql = "CREATE TEMPORARY TABLE my_table (
_key INT NOT NULL AUTO_INCREMENT,
shift INT NOT NULL DEFAULT 0,
line INT NOT NULL DEFAULT 0,
products INT NOT NULL DEFAULT 0,
week INT NOT NULL DEFAULT 0,
PRIMARY KEY(_key) )";
$res = mysql_query($sql);
// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
$errmsg = mysql_errno() . ' ' . mysql_error();
echo "<br/>QUERY FAIL: ";
echo "<br/>$sql <br/>";
die($errmsg);
}
// LOAD UP THE TABLE
mysql_query('INSERT INTO my_table (shift, line, products, week) VALUES (1,2,4000, 1)') or die(mysql_error());
mysql_query('INSERT INTO my_table (shift, line, products, week) VALUES (1,4,4000, 1)') or die(mysql_error());
mysql_query('INSERT INTO my_table (shift, line, products, week) VALUES (1,2,4000, 2)') or die(mysql_error());
mysql_query('INSERT INTO my_table (shift, line, products, week) VALUES (1,4,5000, 2)') or die(mysql_error());
mysql_query('INSERT INTO my_table (shift, line, products, week) VALUES (1,2,4000, 3)') or die(mysql_error());
mysql_query('INSERT INTO my_table (shift, line, products, week) VALUES (1,4,6000, 3)') or die(mysql_error());
// MAKING A SELECT QUERY AND TESTING THE RESULTS
$sql = "SELECT week, SUM(products) as sump FROM my_table GROUP BY week ORDER BY week ASC";
$res = mysql_query($sql);
// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
$errmsg = mysql_errno() . ' ' . mysql_error();
echo "<br/>QUERY FAIL: ";
echo "<br/>$sql <br/>";
die($errmsg);
} // IF WE GET THIS FAR, THE QUERY SUCCEEDED AND WE HAVE A RESOURCE-ID IN $res SO WE CAN NOW USE $res IN OTHER MYSQL FUNCTIONS
// ITERATE OVER THE RESULTS SET TO SHOW WHAT WE SELECTED
while ($row = mysql_fetch_assoc($res))
{
$out[$row["week"]] = $row["sump"];
}
var_dump($out);