|
Posted by Jerry Stuckle on 08/27/07 00:40
stiki wrote:
> I can't seem to execute a DDL statement to create a table in my
> database.
>
> I'm able to connect to the database, because I tested if connection
> was created.
>
> I'm using fnRunSQL($sSQL) (see code below) to run the DDL command and
> the function returns false. Does anyone have any idea of what I could
> be doing wrong?
>
> $sSQL = "CREATE TABLE upload (
> id INT NOT NULL AUTO_INCREMENT,
> name VARCHAR(30) NOT NULL,
> type VARCHAR(30) NOT NULL,
> size INT NOT NULL,
> path VARCHAR(60) NOT NULL,
> PRIMARY KEY(id)
> )";
>
> function fnRunSQL($sSQL) {
> //Runs a SQL statement and returns
> // - TRUE if successful
> // - FALSE if it couldn't connect
> // - The MySQL error code if the SQL statement fails
> global $sDatabaseName, $sUn, $sPw;
>
> if (!$oConn = @mysql_connect($sDatabaseName, $sUn, $sPw)) {
> $bRetVal = FALSE;
> } else {
> if (!mysql_selectdb($sDatabaseName,$oConn)) {
> $bRetVal = FALSE;
> } else {
> if (!$result = mysql_query($sSQL, $oConn)) {
> $bRetVal = mysql_error();
> dbg("DATABASE ERROR: ".$bRetVal);
> } else {
> $bRetVal = TRUE;
> mysql_free_result($result);
> }
> }
> mysql_close($oConn);
> }
> return ($bRetVal);
>
> }
>
> Igor
>
Yep, lots of buggy code.
For one thing, you shouldn't use globals. If you need to pass a value
to the function, pass it. If you need to be able to change the original
value, pass it as a reference.
And you're checking the return value for the functions, but if they fail
you have no idea why.
And I don't see where you're actually calling the function fnRunSQL,
much less defined $sDatabaseName, $sUn or $sPw.
As a side note, I don't think Hungarian notation is really good for pHP.
Much better would be:
function RunSQL($hostName, $dbName, $userId, $pwd, $sql) {
//Runs a SQL statement and returns
// - TRUE if successful
// - FALSE if it couldn't connect
// - The MySQL error code if the SQL statement fails
$retval = true;
if (!$conn = mysql_connect($hostName, $uid, $pwd))
$retval mysql_error();
else {
if (!mysql_selectdb($dbName,$conn))
$retval = mysql_error();
else {
if (!$result = mysql_query($sql, $conn)) {
$retval = mysql_error();
}
}
mysql_close($oConn);
}
return ($retval);
}
$SQL = "CREATE TABLE upload (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
type VARCHAR(30) NOT NULL,
size INT NOT NULL,
path VARCHAR(60) NOT NULL,
PRIMARY KEY(id)
)";
// Put the actual host name, database name, user id and password in the
// next line
$val = RunSQL('hostname', 'dbname', 'userid', 'password', $sql);
if ($val !=== true) // If the call fails
echo $val;
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================
[Back to original message]
|