简体   繁体   English

如何在php中使用mysqli将数据插入数据库

[英]How to insert data into the database using mysqli in php

I really don't know what I'm doing wrong here. 我真的不知道我在做什么错。 For some reason the data won't insert into the database. 由于某种原因,数据不会插入数据库。 I think the problem is where I'm saving the data into local variables and escaping them for security. 我认为问题出在哪里,我将数据保存到局部变量中并转义以确保安全。 So, If I remove that set of local variables, then obviously I get an empty row in the database, and If I leave them there, then it won't do nothing at all, but I need to have that set of local variables to secure the data. 因此,如果我删除了那组局部变量,那么很明显,我在数据库中得到了一个空行,如果我将它们留在那儿,那么它根本什么也不做,但是我需要让那组局部变量保护数据。 I'm also validating data using PHP regex which I know that's not the problem. 我也正在使用PHP regex验证数据,我知道这不是问题。

If anybody can find the problem, please let me know. 如果有人可以找到问题,请告诉我。

PHP PHP
I know it doesn't look good, but that's the best I can do. 我知道它看起来不好,但这是我能做的最好的。

if(isset($_POST['submit'])){
    $errors = array();


   // Check name is valid
  if(empty($_POST['full_name'])):
      $errors['full_name'] = "";//"Please enter your name."
      echo "<script type='text/javascript'>$(document).ready(function(){ $('#full_name').addClass('input-error')});</script>";
   elseif(!preg_match('/\b([A-Z]{1}[a-z]{1,30}[- ]{0,1}|[A-Z]{1}[- \']{1}[A-Z]{0,1}[a-z]{1,30}[- ]{0,1}|[a-z]{1,2}[ -\']{1}[A-Z]{1}[a-z]{1,30}){2,5}/', $_POST['full_name'])):
    $errors['full_name'] = "";//"Please enter a valid name."
    echo "<script type='text/javascript'>$(document).ready(function(){ $('#full_name').addClass('input-error')});</script>";
  else: endif;

   // Check email is valid 
    if(empty($_POST['email'])):
      $errors['email'] = "";  //"Please enter your email.
      echo "<script type='text/javascript'>$(document).ready(function(){ $('#email').addClass('input-error')});</script>";         
    elseif (!filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL)): // validate the email *** REQUIRES PHP 5.2 ***
        $errors['email'] = "";//'Please enter a valid email.
    echo "<script type='text/javascript'>$(document).ready(function(){ $('#email').addClass('input-error')});</script>";            
    else: endif; 

if(!empty($_POST['phone'])){
  //Check phone is valid  Matches - 14165551212, 4165551212, (416)5551212, 416 555 1212, 416-555-1212, (416)-555-1212, (416) 555 1212, 1-900-888-1212
  if(!preg_match('/^(1?)(-| ?)(\()?([0-9]{3})(\)|-| |\)-|\) )?([0-9]{3})(-| )?([0-9]{4}|[0-9]{4})$/', $_POST['phone'])):
     $errors['phone'] = "";//"Please enter a valid phone number.    
    echo "<script type='text/javascript'>$(document).ready(function(){ $('#phone').addClass('input-error')});</script>";              
   else: endif;
}

   // Check subject is valid
  if(empty($_POST['subject'])):
      $errors['subject'] = "";//"Please enter your subject.
      echo "<script type='text/javascript'>$(document).ready(function(){ $('#subject').addClass('input-error')});</script>";          
   elseif(!preg_match("/^(([a-zA-Z])+\s)?[a-zA-Z]+$/", $_POST['subject'])):
    $errors['subject'] = "";//"Please enter a subject.
    echo "<script type='text/javascript'>$(document).ready(function(){ $('#subject').addClass('input-error')});</script>";      
  else: endif;

  // Check URL is valid  Matches - http://regexlib.com | http://www.google.com | ftp://teach.me.regex/checkpattern/o | http://www.google.com/search?hl=en&source=hp&q=asp.net | https://secure.mailserver.com | http://localhost/mypage.html | http://localhost:89783/mypage.aspx | http://go.com | http://forum.whoisyourdaddy.org/index.html?RegID=7449046&Daddy=dontknow&son=me
if(!empty($_POST['url'])){    
   if(!preg_match("/^(ht|f)tp(s?)\:\/\/(([a-zA-Z0-9\-\._]+(\.[a-zA-Z0-9\-\._]+)+)|localhost)(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?([\d\w\.\/\%\+\-\=\&amp;\?\:\\\&quot;\'\,\|\~\;]*)$/", $_POST['url'])):
    $errors['url'] = "";    //"Please enter a valid URL address.
    echo "<script type='text/javascript'>$(document).ready(function(){ $('#url').addClass('input-error')});</script>";      
  else: endif; 
}

   // Check message is valid
  if(empty($_POST['message'])):
      $errors['message'] = "";//"Please enter your message.
      echo "<script type='text/javascript'>$(document).ready(function(){ $('#message').addClass('input-error')});</script>";          
   elseif(!preg_match("/^(([a-zA-Z])+\s)?[a-zA-Z]+$/", $_POST['message'])):
    //$errors['message'] = "Please enter a minimum or more than 50 characters.";
    //echo "<script type='text/javascript'>$(document).ready(function(){ $('#message').addClass('input-error')});"; 
  else: endif;  





    if ( (strlen( $message ) >= 50) && (strlen( $message ) <= 1500)) {
    } else {
    //$errors['message'] = "Please enter from 50 to 1500 characters.";
    echo "<script type='text/javascript'>$(document).ready(function(){ $('#message').addClass('input-error')});</script>";      
    }


  // If no validation errors
   if(0!==count($errors)) {

     echo "<script type='text/javascript'>$(document).ready(function(){ $('.error-container').show()});</script></strong>"; 
  }
  elseif(0===count($errors)){   


            include_once('admin/includes/database.php');
            $conn = db_connect();
            // Save data into local variables and escape them for security  
            $name = mysqli_real_escape_string($conn,$_POST['full_name']);                           
            $email = mysqli_real_escape_string($conn,$_POST['email']);                          
            $phone = mysqli_real_escape_string($conn,$_POST['phone']);                          
            $subject = mysqli_real_escape_string($conn,$_POST['subject']);                          
            $url = mysqli_real_escape_string($conn,$_POST['url']);                          
            $message = mysqli_real_escape_string($conn,$_POST['message']);  

         // An insertion query. $result will be `true` if successful
          $insertSQL = "insert into users (fullname,email,phone,subject,url,message) VALUES ('$name','$email','$phone','$subject','$url','$message')";  


          $run_insertion = mysqli_query($conn, $insertSQL);

          if ($run_insertion === false) {
                $error = db_error();
          } else {

             echo "<script>alert('Your submisision was successfully sent!')</script>";

          }                
  } 

} }

HTML HTML

                    <form action="contact.php" method="post" id="form1" name="form1">
                <div class="error-container">
                    <div class="error-content">
                        <div class="error-header">
                            <div class="error-icon"></div>
                            <div class="error-title">Oops, it looks like something wasn't right.</div>                               
                        </div> <!-- END OF error-header -->
                        <div class="error-message-content">Mistakes are marked below. <br>Correct the errors and resubmit the form.</div> <!-- END OF error-message-content -->
                    </div> <!-- END OF error-content -->
                </div> <!-- END OF error-container -->                    
                   <div class="form-element"><label for="name"><b>Name <div>*</div></b></label><br>
                       <div class="input-wrapper <?php echo form_row_class("full_name") ?>"><input type="text" class="input" name="full_name" placeholder="Full name" id="full_name" value="<?php echo h($_POST['full_name']); ?>" /><font color="red"><?php  echo error_for('full_name') ?></font></div>
                    </div>
                   <div class="form-element">
                      <label for="email"><b>Email <div>*</div></b></label><br>
                      <div class="input-wrapper <?php echo form_row_class("email") ?>"><input type="text" id="email" class="input" name="email" placeholder="jhon@example.com" value="<?php echo h($_POST['email']); ?>" /><font color="red"><?php  echo error_for('email') ?></font></div>
                   </div>
                   <div class="form-element">
                      <label for="phone">Phone</label><br>
                      <div class="input-wrapper <?php echo form_row_class("phone") ?>"><input type="text" id="phone" class="input" name="phone" placeholder="1 800 000 0000"  value="<?php echo h($_POST['phone']); ?>"/><font color="red"><?php  echo error_for('phone') ?></font></div>
                   </div>
                   <div class="form-element">
                      <label for="subject"><b>Subject <div>*</div></b></label><br>
                      <div class="input-wrapper <?php echo form_row_class("subject") ?>"><input type="text" id="subject" class="input" name="subject" placeholder="Subject" value="<?php echo h($_POST['subject']); ?>" /><font color="red"><?php  echo error_for('subject') ?></font></div>
                   </div>
                   <div class="form-element">
                      <label for="company">URL</label><br>
                      <div class="input-wrapper <?php echo form_row_class("url") ?>"><input type="text" id="url" class="input" name="url" placeholder="URL" value="<?php echo h($_POST['url']); ?>" /><font color="red"><?php  echo error_for('url') ?></font></div>
                   </div>
                   <div class="form-textarea">
                      <label for="message"><b>Your Message <div>*</div></b></label><br>
                      <div class="textarea-wrapper <?php echo form_row_class("message") ?>"><textarea class="textarea" id="message" name="message" placeholder="Your message" ><?php echo h($_POST['message']); ?></textarea><font color="red"><?php  echo error_for('message') ?></font></div>
                   </div>
                   <div class="submit-element">
                       <input type="submit" class="submit" name="submit" value="Submit" />
                   </div>

                </form>

As Nikos said, you should be connecting with $link = mysqli_connect. 正如Nikos所说,您应该使用$ link = mysqli_connect进行连接。

To check your errors, 要检查您的错误,

if ($run_insertion) {
  echo "<script>alert('Your submisision was successfully sent!') /script>";

}else{
       echo ("Could not insert data : " . mysqli_error($link) . " " . mysqli_errno($link));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM