PHP Variable in Select Statement

前端 未结 7 526
滥情空心
滥情空心 2021-01-13 17:50

I\'ve written this PHP-Script which is working, and now I want to change the row name into a variable to (not sure if row is correct), I mean the \"name\" from the selec

相关标签:
7条回答
  • 2021-01-13 18:06

    This is much easier isn't it?

    $sql_insert = 
    "INSERT INTO customers (        
    `name`,
    `address`,
    `email`,
    `phone`
    ) 
    VALUES (        
    '$name',
    '$address',     
    '$email',
    '$phone'
    )";
    
    0 讨论(0)
  • 2021-01-13 18:06

    Wouldn't this work?

    $result = mysql_fetch_array($query);
    
    echo trim($result['name']);
    
    0 讨论(0)
  • 2021-01-13 18:17

    You should never put a variable into field list.
    If want a variable field name, select * and then use your variable to fetch particular field

    <?php
    require_once 'config.php';
    
    $id = mysql_real_escape_string($_GET["id"]); //ID DES DERZEITIGEN KONTAKTES
    $user = $_GET["user"];  //ID DES DERZEITIGEN USERS
    
    $query  = "SELECT * FROM contacts WHERE contact_id='$id' and user_id='1'";
    $result = mysql_query($query) or trigger_error(mysql_error().$query);
    
    $row = mysql_fetch_array($result);
    
    //and finally
    $fieldname = "name";
    $retval = $row[$fieldname];
    
    echo $retval;
    ?>
    
    0 讨论(0)
  • 2021-01-13 18:19

    I believe you are confusing matters (unintentionally) due to your use of the word 'row'. Judging by your example you mean field/column. It sounds like you wish to specify the fields to select using a variable which can be done by any of these methods...

    $fields = "name, age";
    
    $sql = "SELECT $fields FROM table";
    $sql = "SELECT {$fields} FROM table";
    $sql = "SELECT ".$fields." FROM table";
    

    NB it is important that you have secure date in the $fields element, I would suggest using a whitelist of allowed values i.e.

    // assuming $_POST['fields'] looks something like array('name','age','hack');
    $allowed = array('name', 'age');
    $fields = array();
    
    foreach ($_POST['fields'] as $field) {
       if (in_array($field, $allowed)) {
          $fields[] = $field;
       }
    $fields = implode(', ', $fields);
    
    0 讨论(0)
  • 2021-01-13 18:21
    • Please post in English. Everyone else does.
    • Try using a different fetch method - fetch an associative array, then use the dynamic parameter to retrieve whatever column it is you need.
    • Have you considered using PDO?
    0 讨论(0)
  • 2021-01-13 18:23

    Is it this you're looking for? Even your question in German isn't that clear to me :

    $field = 'name';
    $query = mysql_query("SELECT $field FROM contacts WHERE contact_id='". mysql_real_escape_string( $id ) ."' and user_id='1';");
    $retval = mysql_fetch_object($query)->$field;
    
    0 讨论(0)
提交回复
热议问题