<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检测连接 if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // prepare and bind $stmt = $conn->prepare("INSERT INTO MyGuests VALUES(?, ?, ?)"); $stmt->bind_param("sss", $firstname, $lastname, $email); // 设置参数并执行 $firstname = "John"; $lastname = "Doe"; $email = "[email protected]"; $stmt->execute(); $firstname = "Mary"; $lastname = "Moe"; $email = "[email protected]"; $stmt->execute(); $firstname = "Julie"; $lastname = "Dooley"; $email = "[email protected]"; $stmt->execute(); echo "New records created successfully"; $stmt->close(); $conn->close(); ?>
运行时报错:
Call to a member function bind_param() on a non-object 原因:bind_param 的第二个参数是起引用传递的直接写成字符串,这是在 php 5.3 及以后是不允许的
解决方法:将 $stmt = $conn->prepare("INSERT INTO myguests VALUES(?,?,?)");改成$stmt = $conn->prepare("INSERT INTO myguests(firstname, lastname, email) VALUES(?,?,?)");
时间: 2024-10-12 20:37:45