PHP旧语法问题

时间:2015-04-15 16:37:56

标签: php mysql

我从一个研究所学习PHP,但他们教会了我将PHP插入数据库的旧语法和技术。当我在网上搜索它时发现它已被弃用,并且在将来的PHP版本中不再可用。我想学习将数据插入数据库的新技术。我举例说明我现在正在做什么,它对我来说工作正常,但我想使用预备语句和所有可能的技术插入数据。

HTML:

    <form method="post" action="do_submit.php"/>
    Name:<input type="text" name="name" id="name"/>
    Class:<input type="text" name="class" id="class"/>
    Section:<input type="text" name="section" id="section"/>
    Roll Number:<input type="text" name="roll" id="roll"/>
    Registration Number:<input type="text" name="reg" id="reg"/>
    <input type="submit"/>
    </form>

do_submit.php:

        <?php

    include 'dbconnect.php';

    $name=$_POST['name'];
    $class=$_POST['class'];
    $section=$_POST['section'];
    $roll=$_POST['roll'];
    $reg=$_POST['reg'];


    $sql = mysql_query("INSERT INTO `school`.`students` (`Name`, `Class`, `Section`,`Roll_No`, `Reg_No`) 
    VALUES ('$name', '$class', '$section', '$roll','$reg');") or die("SELECT Error: ".mysql_error());
            if($sql) 

            {
                $myURL = 'success.php?sType=insert';
                header('Location: '.$myURL);
                exit;
            }

     else 
             echo "Try again!";


    ?>

任何人都可以用示例代码向我指导,以便我学习更加安全的新技术。

2 个答案:

答案 0 :(得分:0)

<?php

// create connection
$conn = new mysqli($servername, $username, $password, $dbname);

$name=$_POST['name'];
$class=$_POST['class'];
$section=$_POST['section'];
$roll=$_POST['roll'];
$reg=$_POST['reg'];

$stmt = $conn->prepare("INSERT INTO `school`.`students` (`Name`, `Class`, `Section`,`Roll_No`, `Reg_No`) 
VALUES (?, ?, ?, ?, ?);");
$stmt->bind_param("sssss", $name, $class, $section, $roll, $reg);
        if($stmt->execute() === true) 

        {
            $myURL = 'success.php?sType=insert';
            header('Location: '.$myURL);
            exit;
        }

 else 
         echo "Try again!";


?>

答案 1 :(得分:0)

这是一个基本概要:

// 2. Prepare
$sql = "SELECT id, familyname FROM familymembers WHERE familyname = ?";

$stmt = $conn->prepare($sql);

if(!$stmt) {
    die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
} else  {
    echo ("<p>Prepare succeeded</p>");
}

// 3. Bind params
// s = string
// i = integer
// d = double (float)
// b = blob (binary data)

$bind_result = $stmt->bind_param("sssss", $name, $class, $section, $roll,$reg);

if(!$bind_result) {
    echo "Binding failed: (" . $stmt->errno . ") " . $stmt->error;
} else  {
    echo ("<p>Binding succeeded</p>");
}

// 4. Execute
$execute_result = $stmt->execute();

if(!$execute_result) {
  echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
} else  {
    echo ("<p>Execute succeeded </p>");
}

// 7. Free results
$stmt->free_result();

// 8. Close statment
$stmt->close();

// 9. Close MySQL connection
$conn->close();