用mysqli编写PHP程序代码
I am less familiar with mysqli, and I write Procedure style, not Object orientated style. I know of some of the benefits of object orientated style but it trips my mind so I am slow to adjust with it. My policy is, if I cannot support it, I don't write it.
So... I have a simple function which contains the following:
mysqli_query( $DB, "CREATE TABLE $TABLE ( $SCHEMHA )" );
if (mysqli_connect_errno()) {
printf("Connect failed: %s
", mysqli_connect_error());
exit();
}
The query works when creating the table, so long as I don't have a bug in my schema. If my schema fails, my conditional statement does not trap the failure (thus the connect failed message never gets called).
Where am I going wrong?
My goal is to be able to exit/stop/end on selective errors. So for example, if a table already exists (errno 1050), I am comfortable ignoring that error, however if there is an error 1072 (Key column 'whatever' doesn't exist in table) I would like to stop processing.
All help appreciated...
我对mysqli不熟悉,而且我编写过程样式,而不是面向对象的样式。 我知道面向对象风格的一些好处,但它让我心烦意乱,所以我很难调整它。 我的政策是,如果我不能支持它,我就不会写它。 p>
所以...我有一个简单的函数,其中包含以下内容: p>
mysqli_query($ DB,“CREATE TABLE $ TABLE($ SCHEMHA)”);
if(mysqli_connect_errno()){
printf(“连接失败:%s
”,mysqli_connect_error() );
exit();
}
code> pre>
只要我的架构中没有错误,查询就会在创建表时起作用。 如果我的模式失败,我的条件语句不会捕获失败(因此连接失败的消息永远不会被调用)。 p>
我哪里出错? p>
我的目标是能够退出/停止/结束选择性错误。 因此,例如,如果一个表已经存在(错误1050),我很乐意忽略该错误,但是如果存在错误1072(表中不存在关键列'无论')我想停止处理。 p>
所有帮助表示赞赏...... p>
div>
- You'll want to examine the return value of
mysqli_query
to know whether the query succeeded or failed. - You can get the exact error code using
mysqli_errno
. - The
_connect_
functions you're using are irrelevant in this context, they give you information about errors which happened during a connection attempt.
if (!mysqli_query(..)) {
switch (mysqli_errno($DB)) {
case 1072:
...
}
}
I believe something like this would do:
$result = mysqli_query( $DB, "CREATE TABLE $TABLE ( $SCHEMHA )" );
if (!$result) {
switch(mysqli_connect_error()) {
// Key column 'whatever' doesn't exist in table
case 1072:
printf("Connect failed: %s
", mysqli_connect_error());
exit();
break;
// and so on...
}
}
The mysqli_connect_errno
returns the error from the connection. Your error is resulting in the query though so use mysqli_error.
if (mysqli_error($DB)) {
printf("Errormessage: %s
", mysqli_error($link));
}
If you just want to check the error code use http://php.net/manual/en/mysqli.errno.php.
printf("Errorcode: %d
", mysqli_errno($DB));
To check for specific codes you could do:
if(in_array(mysqli_errno($DB), array(1072, other codes)) {
exit('Bad Code');
} else {
echo 'Still processing...';
}
So for example, if a table already exists (errno 1050), I am comfortable ignoring that error,
CREATE TABLE IF NOT EXISTS $TABLE ...