【问题标题】:Why PHP PDO bindParam return null if include jQuery file如果包含 jQuery 文件,为什么 PHP PDO bindParam 返回 null
【发布时间】:2022-01-22 07:28:54
【问题描述】:

在每个页面上,我都有 jQuery 模式,其中包含一个联系表单,并且每个页面上都需要将数据发送到不同的电子邮件地址。提交表单后,我需要使用json_encode 显示成功响应。此外,在每个页面上,我都使用页面标识符作为$pages_id=1$pages_id=2 等,以识别提交的表单。但是,非常重要的是,没有 jQuery 文件,完成我的 PHP 代码,它可以正确执行,所有数据都成功插入到数据库中,在 Xdebug 中,我还可以在它成功执行的每一行上看到该代码。但是,如果我包含 jQuery 文件,那么在 Xdebug 中,$pages_id 的值将返回 null。我完全认为这行代码:

$query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM visitneum.owners_email INNER JOIN visitneum.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
$dbstmt = $pdo->prepare($query);
$dbstmt->bindParam(1,$pages_id);
$dbstmt->execute();

但是,下面是我完整的 PHP 代码:

<?php
// set error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL | E_STRICT);

$fname = $tel = $userMail = $userMessage = $email_address_id = "";
$fname_error = $tel_error = $userMail_error = $userMessage_error = "";
$error=false;
//Load the config file
$dbHost = "secret";
$dbUser = "secret";
$dbPassword = "secret";
$dbName = "secret";
$dbCharset = "utf8";
$pdo="";
try{
    $dsn = "mysql:host=" . $dbHost . ";dbName=" . $dbName . ";charset=" . $dbCharset;
    $pdo = new PDO($dsn, $dbUser, $dbPassword);
    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
    $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}catch(PDOException $e){
    echo "Connection error: " . $e->getMessage();
}
use PHPMailer\PHPMailer\PHPMailer;
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_POST['submitOwner'])){
    $fname = $_POST['fname'];
    $tel = $_POST['tel'];
    $userMail = $_POST['userMail'];
    $userMessage = $_POST['userMessage'];
if(empty($_POST['fname'])){
        $error=true;
        $fname_error = "Name and surname cannot be empty!";
    }else{
        $fname = $_POST['fname'];   
        if(!preg_match("/^[a-zšđčćžA-ZŠĐČĆŽ\s]*$/", $fname)){
            $fname_error = "Name and surname can only contain letters and spaces!";
        }
    }
    if(empty($_POST['tel'])) {
        $tel_error = "Phone number cannot be blank!";
    }else{
        $tel = $_POST['tel'];
        if(!preg_match('/^[\+]?[0-9]{9,15}$/', $tel)) {
            $tel_error = "The phone number should contain a minimum of 9 to 15 numbers!";
        }
    }
if(empty($_POST['userMail'])){
        $userMail_error = "Email cannot be blank!";
    }else{
        $userMail = $_POST['userMail'];
        if(!filter_var($userMail, FILTER_VALIDATE_EMAIL)) {
            $userMail_error = "Email address is incorrect!";
        }
    }
    if(empty($_POST['userMessage'])) {
        $userMessage_error = "The content of the message cannot be empty!";
    }else{
        $userMessage = $_POST['userMessage'];
        if(!preg_match("/^[a-zšđčćžA-ZŠĐČĆŽ0-9 ,.!?\'\"]*$/", $userMessage)){
            $userMessage_error = "The content of the message cannot be special characters!";
        }
    }
if($fname_error == '' && $tel_error == '' && $userMail_error == '' && $userMessage_error == ''){
    $mail = new PHPMailer(true);
    $mail->CharSet = "UTF-8";
    $mail->isSMTP();
    $mail->Host = 'secret';
    $mail->SMTPAuth = true;
    $mail->Username = 'secret';
    $mail->Password = 'secret';
    $mail->Port = 465; // 587
    $mail->SMTPSecure = 'ssl'; // tls
    $mail->WordWrap = 50;  
    $mail->setFrom('secret@secret.com');
    $mail->Subject = "New message from visit-neum.com";
    $mail->isHTML(true);
    $query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM visitneum.owners_email INNER JOIN visitneum.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
$dbstmt = $pdo->prepare($query);
$dbstmt->bindParam(1,$pages_id); 
$dbstmt->execute(); //in Xdebug this line of code return NULL for $pages_id if include jQuery file
$emails_other = $dbstmt->fetchAll(PDO::FETCH_ASSOC);
$jsonData=array();
    if(is_array($emails_other) && count($emails_other)>0){
      foreach($emails_other as $email_other){
        //var_dump($email_other['email_address']);
        $mail->addAddress($email_other['email_address']);
        $body_other = "<p>Dear {$email_other['owner_name']}, <br>" . "You just received a message from the site <a href='https://www.visit-neum.com'>visit-neum.com</a><br>Details of your message are below:</p><p><strong>From: </strong>" . ucwords($fname) . "<br><strong>Phone: </strong>" . $tel . "<br><strong>E-mail: </strong>" .strtolower($userMail)."<br><strong>Message: </strong>" . $userMessage . "</p>";
$mail->Body = $body_other;
if($mail->send()){
            
            $mail = "INSERT INTO visitneum.contact_owner(fname, tel, userMail, userMessage, email_address_id) VALUES(:fname, :tel, :userMail, :userMessage, :email_address_id)";
            $stmt = $pdo->prepare($mail);
            $stmt->execute(['fname' => $fname, 'tel' => $tel, 'userMail' => $userMail, 'userMessage' => $userMessage, 'email_address_id' => $email_other['email_address_id']]);

                // Load AJAX
                if($error==false){
                    $information['response'] = "success";
                    $information['content'] = "Thanks " . ucwords($fname) . "! Your message has been successfully sent to the owner of property! You will get an answer soon!";
                    $jsonData[] = $information;
                }
}//end if mail send         
else{   
    $information['response'] = "error";
    $information['content'] = "An error has occurred! Please try again..." . $mail->ErrorInfo;
    $jsonData[]=$information;  
}
echo(json_encode($jsonData));
} // end foreach($emails_other as $email_other)
} // end if(is_array($emails_other) && count($emails_other)>0)
} // end if validation
} // end submitOwner
} // end REQUEST METHOD = POST

您可以在下面看到我的 jQuery 文件的 submitHandler 导致我出现问题:

 submitHandler: function(form){  
      var formData=jQuery("#contactOwner").serialize();
      console.log(formData);
      jQuery.ajax({
        url: "/inc/FormProcess.php",
        type: "post",
        dataType: "json",
        data: formData,
      success:function(jsonData) {
         jQuery("#responseOwner").text(jsonData.content);
         console.log(jsonData);
      error: function (jqXHR, textStatus, errorThrown) {
                    console.log(JSON.stringify(jqXHR));
                    console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
                  }
      }); // Code for AJAX Ends
// Clear all data after submit
      var resetForm = document.getElementById('contactOwner').reset();
      return false;
    } // end submitHandler

包含联系表格的页面如下:

<?php
include_once './inc/FormProcess.php';
?>
<form  spellcheck="false" autocomplete="off" autocorrect="off" id='contactOwner' class='form' name='contactOwner' action='' method='POST'>
<h4 id="responseOwner" class="success">
<!-- This will hold response from the server --></h4>
  <fieldset>
    <legend>Vaši podaci</legend>
        <div class="form-control halb InputIconBg"><input minlength="6" type="text" class="input username" name="fname" placeholder="Your name and surname ..." value="<?php echo Input::get('fname'); ?>"><i class="fas fa-user" aria-hidden="true"></i><span class="error"><?=$fname_error; ?></span></div><!-- end .form-control -->
            
        <div class="form-control halb InputIconBg"><input minlength="9" type="text" class="input phone" name="tel" placeholder="Your phone number..." value="<?php echo Input::get('tel'); ?>"><i class="fas fa-phone-alt" aria-hidden="true"></i><span class="error"><?=$tel_error; ?></span></div><!-- end .form-control -->

        <div class="form-control single InputIconBg"><input type="text" class="input mail" name="userMail" placeholder="Your e-mail..." value="<?php echo Input::get('userMail'); ?>" autocomplete="email"><i id="" class="fas fa-envelope owner_icon" aria-hidden="true"></i><span class="error"><?=$userMail_error; ?></span></div><!-- end .form-control --> 
            
        <div class="form-control InputIconBg"><textarea maxlength="1000" name="userMessage" class="textinput message" cols="46" rows="8" placeholder="Your message..."><?php echo Input::get('userMessage'); ?></textarea><i class="fas fa-pencil-alt owner_icon" aria-hidden="true"></i><span class="error"><?=$userMessage_error; ?></span></div><!-- end .form-control -->
            
    </fieldset>
    <input type="submit" class="btn_submit" id="submitOwner" name="submitOwner" value="SENT"/>
</form>
<script defer src="/JS/validateOwner.js"></script>

所以,我无法弄清楚问题是什么以及为什么 $pages_id 在包含 jQuery 文件时返回 null。另外,我忘了提到if(is_array($emails_other) &amp;&amp; count($emails_other)&gt;0){ 行内的代码返回数字0,因此不执行完整的后续代码,但这当然是正常的,因为$pages_id 为空。但是,我希望有人了解问题所在,因此,在此先感谢您提供的任何帮助。

【问题讨论】:

    标签: php jquery json ajax


    【解决方案1】:

    page_id 在您的脚本中为空,因为您没有在脚本中设置它。

    那么为什么不在你的 froms 中添加一个隐藏的输入字段和页面 id,然后在你的 PHP 代码中

    $page_id = $_POST['pageId'];


    我认为你没有理解 ajax correclty。如果您将数据发布到 /inc/FormProcess.php 它不像之前的包含,您可以先创建变量然后包含它。 AJax 就像对脚本的子调用。就像您只打开 URL 中提供的这个脚本一样。所以此时你没有你的变量。

    您需要获取变量或将您的 ajax 请求发送到 /inc/FormProcess.php,而不是发送到您定义变量的脚本

    【讨论】:

    • 我在每个页面的顶部都设置了 $pages_id,这让我非常困惑的是,如果我不包含 jQuery 文件,我的 PHP 代码会成功执行。也许,所有数据都正确插入到数据库中,每个页面上都有不同的 pages_id 与页面的 $pages_id 匹配。但是,以防万一我包含 jQuery 文件然后 bindParam for $pages_id 返回 null
    • @MirnesGlamočić 是的,但是在这里你通过 ajax 调用只是 inc/FormProcess.php 并且在这个文件中,你没有设置 pages_id。如果您通过 ajax 调用脚本,就像您只在新的浏览器选项卡中打开脚本一样。试试吧。在你的标签页中打开 /inc/FormProcess.php 你会看到 $pages_id 是空的
    • Ajax URLs 就像在后台打开新标签页。
    • 非常感谢,一切都让我明白,只是无法理解如何编写隐藏在 /inc/FormProcess.php 中的输入类型,因为我的网站就像预订一样,我的网站有多个页面可以在每个页面上联系不同属性的所有者,所以我只在每个页面上包含 /inc/FormProcess.php 作为contactOwner.php 联系表单作为 validateOwner.js 在哪里是 jQuery 验证和这个 submitHandler 与 Ajax 调用。
    • @MirnesGlamočić 如果你能找到你当前拥有的页面 ID,你可以在 ajax 处理程序中设置它 var formData=jQuery("#contactOwner").serialize(); formData['page_id'] =1;然后在您的 PHP 代码中 $page_id =$_POST['page_id']
    【解决方案2】:

    我忘了回答我的问题。所以解决方案非常简单。您所要做的就是在表单末尾添加隐藏的输入类型,所以我的正确表单应该是这样的:

    <form  spellcheck="false" autocomplete="off" autocorrect="off" id='contactOwner' class='form ajax' name='contactOwner' action='' method='POST'>
    <h4 id="responseOwner" class="success">
    <!-- This will hold response from the server --></h4>
      <fieldset>
        <legend>Vaši podaci</legend>
            <div class="form-control halb InputIconBg"><input minlength="6" type="text" class="input username" name="fname" placeholder="Vaše ime i prezime..." value="<?php echo Input::get('fname'); ?>"><i class="fas fa-user" aria-hidden="true"></i><span class="error"><?=$fname_error; ?></span></div><!-- end .form-control -->
                
            <div class="form-control halb InputIconBg"><input minlength="9" type="text" class="input phone" name="tel" placeholder="Vaš broj telefona..." value="<?php echo Input::get('tel'); ?>"><i class="fas fa-phone-alt" aria-hidden="true"></i><span class="error"><?=$tel_error; ?></span></div><!-- end .form-control -->
    
            <div class="form-control single InputIconBg"><input type="text" class="input mail" name="userMail" placeholder="Vaš e-mail..." value="<?php echo Input::get('userMail'); ?>" autocomplete="email"><i id="" class="fas fa-envelope" aria-hidden="true"></i><span class="error"><?=$userMail_error; ?></span></div><!-- end .form-control --> 
                
            <div class="form-control InputIconBg"><textarea maxlength="1000" name="userMessage" class="textinput message" cols="46" rows="8" placeholder="Vaša poruka..."><?php echo Input::get('userMessage'); ?></textarea><i class="fas fa-pencil-alt owner_icon" aria-hidden="true"></i><span class="error"><?=$userMessage_error; ?></span></div><!-- end .form-control -->
                
        </fieldset>
        <input type="hidden" name="pages_id" value="<?=$pages_id?>">
        <input type="submit" class="btn_submit" id="submitOwner" name="submitOwner" value="POŠALJI"/>
    </form>
    

    我希望这个答案也能对某人有所帮助,所以如果这个答案也解决了您的问题,请通过单击答案旁边的复选标记将其标记为已接受。提前致谢。

    【讨论】:

      猜你喜欢
      • 2012-05-03
      • 1970-01-01
      • 2013-03-29
      • 2011-12-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-27
      • 1970-01-01
      相关资源
      最近更新 更多