Answer the question
In order to leave comments, you need to log in
How to do database editing through PHP?
Hello, I wrote the code, it gives an error like (Error: Unknown column 'Nikolai' in 'field list'), we display the entire database in a table (output), I want it to be possible to edit the database and save by the "Save" button back to the db.
Here is my code, what is wrong?
<?php
session_start();
$servername = "localhost";
$username = "valeragol_bd";
$password = "password";
$dbname = "valeragol_bd";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// =======
if(!empty($_POST)) {
$query = "INSERT INTO `users` (id,first_name,last_name,login) VALUES";
for($i = 0, $len = count($_POST['id']); $i < $len; $i++) {
$query .= ($i > 0 ? ',' : ' ').
"({$_POST['id'][$i]},{$_POST['first_name'][$i]},{$_POST['last_name'][$i]},{$_POST['login'][$i]})";
}
$query .= " ON DUPLICATE KEY UPDATE first_name = VALUES(first_name), last_name = VALUES(last_name), login = VALUES(login)";
if(!mysqli_query($conn, $query)) echo "Ошибка:".mysqli_error($conn);
}
// =======
$sql = "SELECT * FROM `users`";
$result = mysqli_query($conn, $sql);
?>
<form class="form-admin" method="POST">
<div class="admin-content">
<div class="table-sql">
<table border="1">
<thead>
<tr>
<td>id</td>
<td>first_name</td>
<td>last_name</td>
<td>login</td>
</tr>
</thead>
<tbody>
<?php while($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td aria-label="id"><input name="id[]" readonly type="text" value="<?php echo $row["id"] ?>"></td>
<td aria-label="first_name"><div class="input-edit"></div><input name="first_name[]" readonly type="text" value="<?php echo $row["first_name"] ?>"></td>
<td aria-label="last_name"><div class="input-edit"></div><input name="last_name[]" readonly type="text" value="<?php echo $row["last_name"] ?>"></td>
<td aria-label="login"><div class="input-edit"></div><input name="login[]" readonly type="text" value="<?php echo $row["login"] ?>"></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
<div class="admin-button-wrapper"><button name="button_save" class="button button-primary admin-button">Сохранить</button></div>
</form>
Answer the question
In order to leave comments, you need to log in
text values must be surrounded by apostrophes, for example: ... VALUES (142,'Nikolai','Kiselev','erwrerew') ...
In the above code, $query is formed without apostrophes, which causes an error on the database side:
... VALUES (142, Nikolay, Kiselyov, erwrerew) ...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question