如何在PHP函数里面的Mysql上工作?

时间:2013-11-15 10:59:52

标签: php mysql mysqli

我想知道如何在php函数中执行mysqli操作。我尝试使用mysqli_query(),mysqli_fetch_array()方法和提交按钮,它工作正常。但是在按钮类型=“按钮”我必须使用功能。这些函数不适用于这些方法。如何在php函数中执行这些mysql查询?

global $con;    
$con = mysqli_connect("localhost","root","");    
if(!$con)
  die("Error: ". mysqli_error());    
else
mysqli_select_db($con,"cityscape_content_management");

function delete_user()
{    
 include("PHP_Files/PHP_Form_Fields.php");    
   $id = $_POST["txtEmpID"];    
   $query_del = "delete from User_Register where emp_id = $id";

 if(mysqli_query($con,$query_del))
    echo "Record Deleted";    
 else
   echo "Error :".mysqli_error($con);
}

5 个答案:

答案 0 :(得分:0)

您必须将$con传递给该函数,否则它不会在那里定义。

答案 1 :(得分:0)

您可以将$ con和$ id变量作为函数参数传递:

$con = mysqli_connect("localhost","root","") or trigger_error(mysqli_error());    
mysqli_select_db($con,"cityscape_content_management") or trigger_error(mysqli_error($con));
delete_user($_POST["txtEmpID"], $con);

功能:

function delete_user($id, $con)
{    
   $id = intval($id);
   include("PHP_Files/PHP_Form_Fields.php");    
   $query_del = "delete from User_Register where emp_id = $id";

   if(mysqli_query($con, $query_del))
      echo "Record Deleted";    
   else
      echo "Error :" . mysqli_error($con);
}

答案 2 :(得分:0)

建议您使用PDO,它看起来非常友好且安全性很高

答案 3 :(得分:0)

button type =“button”不会将数据发布到服务器,因此您的功能不起作用, 要么保持type = submit,要么你想要type = button,那么你需要在点击事件上提交表单,如

1)onlick = 'document.getElementById("frm1").submit()';

其中frm1是您的表单ID 或

2)为您的按钮编码

 <button type="submit" formaction="delete.php" value="delete" />

答案 4 :(得分:-1)

使用全局内部函数,您已在外部使用它。

function delete_user()
    {
     global $con;
     include("PHP_Files/PHP_Form_Fields.php");

       $id = $_POST["txtEmpID"];

      $query_del = "delete from User_Register where emp_id = $id";

     if(mysqli_query($con,$query_del))
        echo "Record Deleted";

     else
       echo "Error :".mysqli_error($con);
    }