我是Php的新手,我主要在vb.net做过项目,现在我想在php上尝试一下,我的问题是如何编写一个接受字符串并执行sql查询的函数,如删除,更新和插入,就像下面的例子我在vb.net上做的那样
Public Function ExecuteSQLQuery(ByVal SQLInsertString As String) As Boolean
Dim err As Boolean = True
Dim SqlConn As New SqlClient.SqlConnection
Dim Sqlcmmd As New SqlClient.SqlCommand
Try
SqlConn.ConnectionString = ConnectionStrinG
SqlConn.Open()
Sqlcmmd.Connection = SqlConn
Sqlcmmd.CommandText = SQLInsertString
Sqlcmmd.CommandType = CommandType.Text
Sqlcmmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
err = False
Finally
SqlConn.Close()
SqlConn.Dispose()
Sqlcmmd.Connection = Nothing
End Try
Return err
End Function
答案 0 :(得分:0)
我为此使用了泛型类。这是我使用的功能。您需要提供conenctions的参数。例如:
function OpenLink()
{ // Method : begin
$this->link = @mysql_connect($this->host,$this->user,$this->password) or die (print "Class Database: Error while connecting to DB (link)");
} // Method : end
function SelectDB()
{ // Method : begin
@mysql_select_db($this->database,$this->link) or die (print "Class Database: Error while selecting DB");
} // Method : end
function CloseDB()
{ // Method : begin
mysql_close();
} // Method : end
function Query($query)
{ // Method : begin
$this->OpenLink();
$this->SelectDB();
$this->query = $query;
$this->result = mysql_query($query,$this->link) ;//or die (print "Class Database: Error while executing Query");
// $rows=mysql_affected_rows();
if(ereg("SELECT",$query))
{
$this->rows = mysql_num_rows($this->result);
}
$this->CloseDB();
} // Method : end
此功能也适用于选择。你可以传递任何SQL文本。您可以选择如何使用它,打开连接的位置。我在查询功能中打开一个关闭。但如果需要,你可以改变它。