我已经尝试了几天了。我想发展我的PHP和数据库安全知识,我希望使用OOPHP和参数化查询。我想我将从简单地连接到数据库并执行选择并显示结果开始。我知道参数化查询可以自己工作,但是当我把它放在一个类中并调用它时,它不会获取结果并显示它们。这是我的代码,我一直在工作:
<?php
class connect
{
public static function run()
{
$mysqli = new mysqli("*****", "*****", "*****");
$db = "sales";
mysqli_select_db($db);
if(!$mysqli)
{
printf("Connection Failed: %s'n", mysqli_connect_error());
}
else
{
echo("MariaDB Connection Successfull!!!");
}
}
}
//call_user_func(array($className, 'run'));
class contacts
{
public function select()
{
if($stmt = $mysqli->prepare("SELECT CON_ID, CON_FNAME, CON_LNAME, CON_EMAIL FROM contacts"))
{
$stmt->execute();
$stmt->bind_result($id,$fname,$lname,$email);
echo("<table align='center' width='40%'");
echo("<tr>");
echo("<td align='center' width='25%'>Contact ID</td>");
echo("<td align='center' width='25%'>First Name</td>");
echo("<td align='center' width='25%'>Last Name</td>");
echo("<td align='center' width='25%'>Email Address</td>");
echo("</tr>");
while($stmt->fetch())
{
echo("<tr>");
echo("<td align='center' width='25%'>");
printf("%s",$this->$id);
echo("</td>");
echo("<td align='center' width='25%'>");
printf("%s",$this->$fname);
echo("</td>");
echo("<td align='center' width='25%'>");
printf("%s",$this->$lname);
echo("</td>");
echo("<td align='center' width='25%'>");
printf("%s",$this->$email);
echo("</td>");
echo("</tr>");
}
printf("</table>");
$stmt->close();
}
else
{
printf("Prepared Statement Error: %s'n", $mysqli->error());
}
}
}
$connect = "connect";
$connect::run();
$contact = "contacts";
$contact::select();
?>
当我运行页面时,我收到的唯一输出是"MariaDB连接成功!!",但它似乎没有在类"contacts"中运行select()。我正在寻找学习更好的PHP编码方式,所以如果有更好的方法,我很乐意学习它!
我将非常感激任何人能给予的任何帮助。
你的代码有两个主要问题
- 你正在使用mysqli而不是PDO,使你的目标更难达到
- 你想一次做所有的事情。这不是一条好路。试着让自己熟悉API,使用纯文本代码运行一些查询。然后将这些代码组合成函数。然后才开始上课。