我遇到了數組結果在我的PHP的麻煩。我的第一個問題是這樣的:PHP插入多個複選框和文本框數組到MySQL數據庫
這表明即使複選框未選中的一切。我的第二個問題是,即使它連接到數據庫,它也不會將值插入到數據庫中(正如您在前面的屏幕截圖中看到的,它表示「連接成功」)。
這是我的HTML表單:
<form method="POST">
<input type="hidden" name="item[]" value="cupcake">
<input type="text" name="items" value="cupcake" readonly><br>
<b>Price :</b> <span name="price" value="3.00">$17.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[]" type="checkbox" value="17" /><span>Add to Cart</span></label></div></div></td><br>
<input type="hidden" name="item[]" value="cake">
<input type="text" name="items" value="cake" readonly><br>
<b>Price :</b> <span name="price" value="20.00">$20.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[]" type="checkbox" value="20" /><span>Add to Cart</span></label></div></div></td><br>
<input type="submit" name="insertBT"><br>
</form>
PHP:
if(isset($_POST['insertBT']))
{
class db_conn
{
public function create_conn($servername, $username, $password, $db)
{
global $conn;
$conn = new mysqli ($servername, $username, $password, $db);
}
public function check_conn()
{
global $conn;
if($conn->connect_error)
{
die ("Connection Failed : " . $conn->connect_error);
}
else
{
echo ("Connected Successfully <br>");
}
}
public function insert()
{
if(isset($_POST['checkbox'])) {
foreach($_POST['checkbox'] as $check) {
$check = implode(',', $_POST['checkbox']);
$name = implode(',', $_POST['item']);
$quantity = implode(',', $_POST['quantity']);
}
echo $check . "<br>";
echo $name . "<br>";
echo $quantity . "<br>";
mysql_query("INSERT INTO purchases(Product, Quantity, Price) VALUES('$name', '$quantity','$check')");
}
}
}
$obj1 = new db_conn;
$obj1->create_conn("localhost","root","", "dbtest");
$obj1->check_conn();
$obj1->insert();
}
對不起,但我沒有問如何將php文件連接到數據庫,我已經知道如何使用面向對象編程連接它。我正在問一個完全不同的問題。 – Raios
爲什麼使用全局變量'$ conn'而不是類屬性? – Barmar
既然你正在循環複選框,爲什麼你還在循環內部執行'implode(',',$ _POST ['checkbox'])'? – Barmar