Good evening! There was a problem in the next case, there is a need to do for one site some kind of admin panel to manage users - display their list and fields of interest. All user data is stored in the mysql database. With the conclusion of the list, I managed, but with the editing somewhere, I got a cant get out :(

<?php if (isset($_GET['del_id'])) { //проверяем, есть ли переменная на удаление $sql = mysql_query('DELETE FROM `hyldia_users` WHERE `id` = '.$_GET['del_id']); //удаляем строку из таблицы } if (isset($_GET['red_id'])) { //Проверяем, передана ли переменная на редактирования if (isset($_POST['nick'])) { //Если новое имя предано, то обновляем и имя и цену $sql = mysql_query('UPDATE `hyldia_users` SET ' .'`nick` = "'.$_POST['nick'].'",' .'`money` = '.$_POST['money'].' ' .'WHERE `id` = '.$_GET['red_id']); } } ?> <?php $sql = mysql_query("SELECT * FROM `hyldia_users`", $link); while ($result = mysql_fetch_array($sql)) { echo '<tr><td>'.$result['id'].'</td>'. '<td>'.$result['nick'].'</td>'. '<td>'.$result['money'].' рублей</td>'. '<td><a href="?del_id='.$result['id'].'">Удалить</a></td>'. '<td><a href="?red_id='.$result['id'].'">Редактировать</a>. </td></tr>'; } ?> </table> <?php if (isset($_GET['red_id'])) { //Если передана переменная на редактирование //Достаем запсись из БД $sql = mysql_query("SELECT * FROM `hyldia_users` WHERE `id`=".$_GET['red_id'], $link); //запрос к БД $result = mysql_fetch_array($sql); //получение самой записи ?> <table> <form action="" method="post"> <tr> <td>Игрок:</td> <td><input type="text" name="nick" value="<?php echo ($result['nick']); ?>"></td> </tr> <tr> <td>Баланс:</td> <td><input type="text" name="money" size="3" value="<?php echo ($result['money']); ?>"> руб.</td> </tr> <tr> <td colspan="2"><input type="submit" value="OK"></td> </tr> </form> </table> <?php } ?> 

Closed due to the fact that the essence of the question is not clear by the participants Mikhail Vaysman , Dmitriy Simushev , user194374, rjhdby , D-side Mar 2 '17 at 11:28 .

Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • describe the problems. Describe what you do not understand. - Mikhail Vaysman
  • the table was rendered, but the edit buttons do not work, the redirect to the main page occurs. - Oleg Bogatyrev
  • try to make a minimal reproducible example - Mikhail Vaysman
  • I reduced the code, I am here for the first time, so if I do something wrong, I apologize - Oleg Bogatyrev

3 answers 3

The first and most obvious joint, though not directly related to the answer, is why in 2017 you use the MYSQL module and not the MYSQLi or PDO .

Example connection using mysqli:

 $mysqli = new mysqli("localhost", "user", "password", "database"); if ($mysqli->connect_errno) { echo "Не удалось подключиться к MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; } 

The second explicit jamb is the insertion of variables into queries directly. It is necessary to process variables before forming the request:

 if($_GET['del_id']){ $id = intval($_GET['del_id']);// ожидаем integer } 

The point is to check each input variable for the expected data type and the absence of "impurities". Then you can form a request:

 if (!$mysqli->query("DELETE FROM `hyldia_users` WHERE `id` = '.$id"){ echo " . $mysqli->erro . " " . $mysqli->error; } 

Data sampling and table formation (mysqli):

 $query = "SELECT * FROM `hyldia_users`"; if ($result = $mysqli->query($query)){ echo "<table>";//в своём примере вы не открыли таблицу /* извлечение ассоциативного массива */ while ($row = $result->fetch_assoc()) { echo "<tr><td>$row['id']"; ... ... ... echo "</td></tr>" } echo "</table>"; /* удаление выборки */ $result->free(); } 

Request to change data for the selected record (mysqli):

pass name as a parameter is not correct, correct id (a unique value). Therefore, it is better to form like this:

 <form action="" method="post"> <input type="hidden" name="id" value="<?php echo ($result['id']); ?>"> <input type="text" name="nick" value="<?php echo ($result['nick']); ?>"> <input type="text" name="money" size="3" value="<?php echo ($result['money']); ?>"> <input type="submit" value="OK"> </form> if($_POST){ $id = intval($_POST['id']); ... $money = intval($_POSt['money'])// intval только если money не может быть минусовым, иначе (int) $query = "UPDATE hyldia_users SET money = $money, nick = $nick ... WHERE id= $id"; $mysqli->query($query); } 

If you do not share logic and representation, i.e. you have everything happening in one file, then check $ _post and change operations (delete, change, add) first of all, at the very beginning of the file so that the subsequent sample of data into the table displays the actual data.

All examples are based on examples of using the mysqli module, I advise you to learn about it as well as try extensions

     "DELETE FROM `hyldia_users` WHERE `id` = '.$_GET['del_id'] 

    Such code is the surest way to SQL injection . Imagine what happens if the value of the del_id parameter is '0 OR TRUE'.

    Use the query call with parameters. See, for example, http://php.net/manual/ru/mysqli.prepare.php

    • GET request for deletion doesn't bother you here, as well as the use of the outdated mysql_* extension? PS: in fact this is not the answer to the question. - teran
    • Not the answer - yes, I know. Unfortunately, I do not have enough rights to comment on other people's answers. And I also could not pass by such an example, so I had to write as an answer. - Aleksei
    • Thanks for the advice, I will rewrite this part without fail, unfortunately not a professional far in php and wrote on the basis of the lesson found. But while I still want to see how to solve the problem with editing. - Oleg Bogatyrev

    I deployed your code and it works for me as required) You can try to do this in the following way - to transfer the data for editing to the form data completely, I think it will be logical to add a hidden field to the form <input type="hidden" name="red_id" value="<?php echo ($result['id']); ?> In the line if (isset($_GET['red_id'])) { //Проверяем, передана ли переменная на редактирования - replace GET with POST. In general, I highly recommend looking towards PDO.