patternphpMinor
Connecting to a database
Viewed 0 times
databaseconnectingstackoverflow
Problem
I'm working on a web application that I inherited from a colleague long gone. To connect to the MySQL database I use the following classes:
statement.php
result.php
connection.php
named.php
To have a connection I can use the following script:
```
$connection = createNamedConnection("dbalias1");
$statement = $connection->createStatement();
$query = "SELECT *
FROM tContent c
WHERE c.cID > 100";
$result = $statement->query($query);
while(($row = $resul
statement.php
m_connection = $connection;
}
function query($query)
{
$connection = $this->m_connection;
$handle = $connection->getHandle();
$result = mysql_query($query,$handle);
if ($result === FALSE)
throw new Exception(mysql_error());
$instance = new Result($this);
$instance->setHandle($result);
return $instance;
}
}
//}
?>result.php
m_statement = $statement;
}
function setHandle($handle)
{
$this->m_handle = $handle;
}
function fetch()
{
$handle = $this->m_handle;
$row = mysql_fetch_array($handle);
return $row;
}
}
//}
?>connection.php
m_handle = $handle;
}
function __destruct()
{
$handle = $this->m_handle;
@mysql_close($handle);
}
function createStatement()
{
return new Statement($this);
}
function getHandle()
{
return $this->m_handle;
}
}
//}
?>named.php
createStatement();
$statement->query("USE db1");
return $connection;
}
if ($name == "dbalias2")
{
$connection = new Connection("second.host.com","user2","nouse");
$statement = $connection->createStatement();
$statement->query("USE db2");
return $connection;
}
return null;
}
?>To have a connection I can use the following script:
```
$connection = createNamedConnection("dbalias1");
$statement = $connection->createStatement();
$query = "SELECT *
FROM tContent c
WHERE c.cID > 100";
$result = $statement->query($query);
while(($row = $resul
Solution
Consider using mysqli instead of mysql:
mysqli
Mysqli (the "i" stands for "improved") is more OO-friendly and has better security. It also seems like the standard mysql functions are being deprecated (some of them anyway).
mysqli
Mysqli (the "i" stands for "improved") is more OO-friendly and has better security. It also seems like the standard mysql functions are being deprecated (some of them anyway).
Context
StackExchange Code Review Q#601, answer score: 4
Revisions (0)
No revisions yet.