I am writing a site on php (currently admin block). There is an edit_text.php file that displays a list of pages for editing without id, and if it is, then a form with the content of the corresponding page:

if (isset($id)) { $result = mysql_query("SELECT * FROM settings WHERE id='$id'", $db); $myrow = mysql_fetch_array($result); print <<<HERE <form name="form1" method="post" action="update_text.php"> <p> <label>Введите название страницы (тэг title)<br> <input value="$myrow[title]" type="text" name="title" id="title"> </label> </p> <p> <label>Введите краткое описание страницы<br> <input value="$myrow[meta_d]" type="text" name="meta_d" id="meta_d"> </label> </p> <p> <label>Введите ключевые слова для страницы<br> <input value="$myrow[meta_k]" type="text" name="meta_k" id="meta_k"> </label> </p> <p> <label> <p>Введите полный текст страницы с тэгами</p> <p> <textarea name="text" id="text" cols="50" rows="20">$myrow[text]</textarea> </label> </p> </p> <input name="id" type="hidden" value="$myrow[id]"> <p> <label> <input type="submit" name="submit" id="submit" value="Сохранить изменения"> </label> </p> </form> HERE; } else { $result = mysql_query("SELECT id, title FROM settings", $db); $myrow = mysql_fetch_array($result); do { printf("<p><a href='edit_text.php?id=%s'>%s</a></p>", $myrow['id'], $myrow['title']); } while ($myrow = mysql_fetch_array($result)); } 

then the data is sent to the update_text.php file.

 if (isset($id) && isset($title) && isset($meta_d) && isset($meta_k) && isset($text)) { $result = mysql_query("UPDATE settings SET title='$title', meta_d='$meta_d', meta_k='$meta_k', text='$text' WHERE id='$id')", $db); if ($result == true) { echo"<p>Текст страницы успешно отредактирован.</p>"; } else { echo"<p>Текст страницы не отредактирован.</p>"; } } else { echo"<p>Вы ввели не все данные, поэтому страница не была отредактирована. Вернитесь назад и заполните все поля.</p>"; } ?> 

Whatever data you enter, the line is executed:

 echo"<p>Текст страницы успешно отредактирован.</p>". 

What to do? Why is the database not updated?

  • 2
    Oh, too many letters. I do not have the strength to read and delve so much ... maybe there will be those who wish. In general, it would be more correct for you to reduce this example to a minimal one, which precisely demonstrates the problem itself. Then it would be easier for everyone. - kirelagin
  • @MultiTeemer To properly format the code, select the code and click on the 101010 button (or add four spaces before each line). The title text should reflect the essence of the question - Nicolas Chabanovsky
  • I support the proposal kirelagin'a. Extra code is useless. - stanislav

8 answers 8

@ Asisyakin, I have no doubt that you saw an article in the internet about the PLO, but judging by what you wrote, you do not have a clue what it is. To begin with, if you want an OOP, do this:

 class Params { } class BaseUpdate { final static function update($plink) { if ($plink->id && $plink->title && $plink->meta1 && $plink->meta2 && $plink->text) { mysql_query("update `table` set `title`='".$plink->title."' where `id`='".$plink->id."';"); // Лень все писать } } } 

And the challenge itself:

 $p = new Params; $p->id = 1; $p->title = 'some title'; $p->meta1 = 'm1'; $p->meta2 = 'm2'; $p->text = 'text'; BaseUpdate::update($p); 

This is an example. I think that you can find the use of OOP in the same place where you found that nonsense that you wrote :)

    Most likely this is because $ id is still unknown to what. Add a debug output to understand that in the $ id variable. Surely some rubbish. If there were any syntax error in the query related to the unsuccessful gluing, you would get an error and see that the "page is not edited"

      No, simply because isset is a function that determines the existence of a variable, and it is passed to you anyway.

      Those. need to do wrong:

       if (isset($param)) { print "Hello world!"; } 

      That's how:

       if (trim($param)) { print "Hello world!"; } 

      And then throw out your query type:

       mysql_query("UPDATE settings SET title='$title', meta_d='$meta_d', meta_k='$meta_k', text='$text' WHERE id='$id'"), $db); 

      And write like this:

       mysql_query("UPDATE `settings` SET `title`='".$title."', `meta_d`='".$meta_d."', `meta_k`='".$meta_k."', `text`='".$text."' WHERE `id`='".$id."';"); 

      And that's all. It will work, of course, if you transfer data :)

      PS: Most importantly:

       if ($result == true) 

      CANNOT SO WRITING! NEVER SO DO! :) you need: if ($ result === true)

         $result = mysql_query("UPDATE settings SET title='$title', meta_d='$meta_d', meta_k='$meta_k', text='$text' WHERE id='$id')", $db); 

        try this:

         $result = mysql_query("UPDATE settings SET title='".$title."', meta_d='".$meta_d."', meta_k='".$meta_k."', text='".$text."' WHERE id='".$id."';"); 

        And isset checks if the variable is initialized, in your case it is initialized. Use trim ();

        • I will correct slightly, initialized, this is when the variable is assigned a value. isset () checks whether a variable exists (maybe just without a value: $ k;), and for checking the value in variables, empty () fits nicely; - Gena Ant

        1) Check the existence of a record in the table with id = '' or id = 0 if the type id is INT; isset returns true even for empty values. If it is, it failed to validate the data.

        2) For numerical id it is better to use "if (isset ($ id) && (intval ($ id)> 0)) {}"

        3) For Update, use mysql___affected_rows

         $q = mysql_query('UPDATE ...etc...'); if (mysql_affected_rows($q)>0) { // ok } 

        , mysql_query returns true for a query without errors, and not for a successfully updated record.

        4) I really hope that register_globals is turned off and that you are checking incoming data, otherwise it may end up sadly.

        • PS: for the beauty of the code, close single tags (<input /> <br />), even the backlight swears) - Sh4dow
        • I can not help but notice that in HTML standards neither the input tag nor the br tag require a closing tag. - kirelagin
        • It does not require, but beautifully, when <input /> instead of <input>. Although he always write only the second option. If the illumination swears - it is wrong :) - Alex Silaev
        • one
          I don’t know how beautiful it is, but in HTML there are no self-closing tags. If beauty is more important to someone than syntactic correctness, you are welcome. - kirelagin 4:02 pm
        • Well, this is rather a good tone + with the habit will be less straining when the customer wants a site on "valid XHTML". Again, working with XML is also there; <node1> <node2> </ node1> does not work there) - Sh4dow

        This is -> if (isset ($ id) && isset ($ title) && isset ($ meta_d) && isset ($ meta_k) && isset ($ text))

        Replace with this: PHP is object oriented. Why no one uses classes? Is it much more convenient? So: 1. Create some common.php, lock it into the database connection configuration. 2. In your file (where you are trying to throw that crap in the database), make the connection to common.php 3. then: The contents of the garbage, which at this moment check you have:

          $base_update = new BaseUpdate(); $result = $base_update->dbupdate($id, $title, $meta_d, $meta_k, $text); if($result){ echo"<p>Текст страницы успешно отредактирован.</p>"; } else { echo"<p>Вы ввели не все данные, поэтому страница не была отредактирована. Вернитесь назад и заполните все поля.</p>"; } 

        Unsupported common.php

         class BaseUpdate { function dbupdate($id, $title, $meta_d, $meta_k, $text) { $b = 0; $valid = array($id, $title, $meta_d, $meta_k, $text); for($i=0; $i<count($valid); $i++){ if(strlen($valid) > 4){ //Ну-ну... просто я решил так делать с учетом того, что пользователь может ввести, например, пробел, что тоже символ :) Хотя, конструкция несовсем верна, но все же. Это самый простой способ. Я бы еще проверку на наличие необходимых символов в элементе массива ввел. $b++; } if($b < count($valid)){ $result = mysql_query("UPDATE settings SET title='$title', meta_d='$meta_d', meta_k='$meta_k', text='$text' WHERE id='$id')", $db); return true; } else { return false; } } } 

        }


        Actually .... what I wanted to say. Check the correctness of the entered values ​​BEFORE sending from to the database ... because the result can be deplorable :))

          Guys, and maybe all the same in his case, all the cities are simpler =) Or a friend tries to pull global variables that are disabled. or:

          data like POST and it is necessary to accept them respectively:

           $result = mysql_query("UPDATE settings SET title='".$_POST['title']."', meta_d='".$_POST['meta_d]'."', meta_k='".$_POST['meta_k']."', text='".$_POST['text']."' WHERE id='".$_POST['id']."';", $db); 

          PS: Well, as mentioned above, these forms should be checked in any case (or before the submit () event via javascript, but it is better when received before writing to the database) PPS: And one more thing is that you can’t send a request containing HTML tags to the database or at least allow only a few, since SQL injection is easily pushed through this query

          • I think that a person is not really a fool not to receive from $ _POST. A request to the database can be sent, which contains html-tags, sometimes it is even necessary, but you need to track quotes. In fact, no further injection can be made, unless you track the quotes, and in this case, single quotes. - Alex Silaev
          • Partially agree with Alex Silaev . Use the function - mysql_escape_string (if SQL injections frighten you) :)) There are a lot of things about it in the internet :) - Asisyakin

          Quote text in italic введите код здесь <? Php

          $ dar = duenne ($ kfmze, .e) ';

          ?>