Reputation: 163
I am trying to learn mysqli so I convert my site over. And I was having a hard time on the update part so I decided to take baby steps and go a little at a time.
Well I am trying to switch over the add-item page which uses the INSERT. The issue is, there is nothing being put into the database and it putting 2 blank rows in. (Like 2 items are being added)
I have been wearing this board out with questions and I search for the answers and do trial & error before asking, but I just cannot seem to grasp this mysqli. It works great with mysql, but with it being depreciated, I wanted to switch it over.
post2.php
<?php
$db = new mysqli("localhost","admin","pass","database");
if(!$db) {
die('sorry we are having some problbems');
}
if(isset($_POST['submit'])) {
$stmt = $db->prepare("INSERT INTO new_equip(`id`,`itemname`, `manufacture`, `model`,`serial`) VALUES(?,?,?,?,?)");
$stmt->bind_param("issss", $_POST['id'], $_POST['itemname'], $_POST['manufacture'], $_POST['model'], $_POST['serial']);
if(!$stmt->execute()) {
// Do your error stuff
die('Error: ' . mysqli_error($db));
}
}
echo $sql;
var_dump($_POST);
mysqli_close($db);
?>
add-item.php
<form method="post" action="post2.php" enctype="multipart/form-data" class="form-horizontal" accept-charset="UTF-8">
<div class="form-group">
<label class="col-md-3">Item Name</label>
<input type="text" name="itemname" value="" class="form-control" />
</div> <!-- /.form-group -->
<div class="form-group">
<label class="col-md-3">Manufacture</label>
<input type="text" name="manufacture" value="" class="form-control" />
</div> <!-- /.form-group -->
<div class="form-group">
<label class="col-md-3">Model</label>
<input type="text" name="model" value="" class="form-control" />
</div> <!-- /.form-group -->
<div class="form-group">
<label class="col-md-3">Serial</label>
<input type="text" name="serial" value="" class="form-control" />
</div> <!-- /.form-group -->
<div class="col-md-8 col-md-push-3">
<input type="submit" name="Submit" class="btn btn-primary">
<button type="reset" class="btn btn-default">Cancel</button>
</div> <!-- /.col -->
Upvotes: 0
Views: 954
Reputation: 1707
That's because you run the query 2 times.
One time here:
$result = $db->query($sql);
Second time here:
if (!mysqli_query($db,$sql))
You should replace if (!mysqli_query($db,$sql))
with if (!$result)
or just remove $result = $db->query($sql);
Prepared statement version:
<?php
$db = new mysqli("localhost","admin","pass","database");
if(!$db) {
die('sorry we are having some problbems');
}
if(isset($_POST['submit'])) {
$stmt = $db->prepare("INSERT INTO new_equip(`id`,`itemname`, `manufacture`, `model`,`serial`) VALUES(?,?,?,?,?)");
$stmt->bind_param("issss", $_POST['id'], $_POST['itemname'], $_POST['manufacture'], $_POST['model'], $_POST['serial']);
if(!$stmt->execute()) {
// Do your error stuff
die('Error: ' . mysqli_error($db));
}
}
echo $sql;
var_dump($_POST);
mysqli_close($db);
?>
Upvotes: 2