PHP UPDATE prepared statement

前端 未结 3 2138
南旧
南旧 2020-11-27 07:28

I\'m trying to learn the proper way to use prepared statements to avoid SQL injections etc.

When I execute the script I get a message from my script saying 0 Rows I

3条回答
  •  广开言路
    2020-11-27 08:18

    I want to clean up Bill Karwin's awesome code

    $stmt = $this->mysqli->prepare("UPDATE datadump SET content=? WHERE id=?") or die ($this->mysqli->error);
    
    $id = 1;
    
    // Bind our params
    // BK: variables must be bound in the same order as the params in your SQL.
    // Some people prefer PDO because it supports named parameter.
    $stmt->bind_param('si', $content, $id) or die ($stmt->error);
    
    // Set our params
    // BK: No need to use escaping when using parameters, in fact, you must not, 
    // because you'll get literal '\' characters in your content. */
    $content = (string)$_POST['content'] ?: '';
    
    /* Execute the prepared Statement */
    $status = $stmt->execute() or die ($stmt->error);
    
    
    printf("%d Row inserted.\n", $stmt->affected_rows);
    

    I recommend using "or die" instead of if clause I recommend forcing a variable type to take values:

    // If id brings value: '12abc', PHP automatically stops it at 12
    $id = (int)$_ POST ["id"];
    

提交回复
热议问题