如何将PHP中的字符串数据插入到MySql表中

时间:2013-07-31 12:58:21

标签: php mysql

如何将这些字符串数据从PHP插入到MySQL表中,我可以运行代码但不插入数据库。

php代码:

<?php

//mysql connection
$connect_error = 'Sorry, the database server is down. Please try again later.';
mysql_connect('xxxxxxxxx.com', 'xxxxxxx', 'xxxxxxxxx') or die($connect_error);
mysql_select_db('checkbox_test') or die($connect_error);

if (isset($_POST['submit'])) {
    if (isset($_POST['subject'])) {
        $strsubject = implode(",", ($_POST['subject']));
    } else {
        $strsubject = "";
    }

    echo $strsubject;
}

mysql_query("INSERT INTO levels (level_1, level_2, level_3, level_4, level_5, level_6) VALUES ($strsubject");
?>

html:

<form action="" method="post" name="form_subject" id="form_subject">

    <input type="checkbox" name="subject[]" value="level_1"><label>Level 1</label><p>    
    <input type="checkbox" name="subject[]" value="level_2"></label>Level 2</label><p>  
    <input type="checkbox" name="subject[]" value="level_3"></label>Level 3</label><p>   
    <input type="checkbox" name="subject[]" value="level_4"><label>Level 4</label><p>    
    <input type="checkbox" name="subject[]" value="level_5"></label>Level 5</label><p>       
    <input type="checkbox" name="subject[]" value="level_6"></label>Level 6</label><p>

    <input type="submit" action= "" name="submit"  value="Submit" />

</form>

数据库表有7列,1表示id(设置为A_I),其余为每个级别命名。 我是网络开发的新手,谢谢你们

2 个答案:

答案 0 :(得分:0)

您在INSERT声明中,$strsubject之后和"之前错过了右括号:

mysql_query("INSERT INTO levels (level_1, level_2, level_3, level_4, level_5, level_6) 
                    VALUES ($strsubject")

这可能不是唯一的问题。

答案 1 :(得分:-1)

  1. 在PHP中,就像在JS,C ++和Java中一样,人们不会简单地将变量放入另一个变量中。使用正确的concat字符.
  2. $what      = "lazr!";
    $variable1 = "firin " . $what;
    
    $sql = "....SET column1='" . $data1 . "')";
    

    1. 请勿使用mysql_*个功能。

    2. 在PDO中使用预准备语句: http://php.net/manual/de/pdo.prepare.php

    3. <?php
      /* Execute a prepared statement by passing an array of values */
      $sth = $dbh->prepare('SELECT name, colour, calories
          FROM fruit
          WHERE calories < ? AND colour = ?');
      $sth->execute(array(150, 'red'));
      $red = $sth->fetchAll();
      $sth->execute(array(175, 'yellow'));
      $yellow = $sth->fetchAll();
      
      1. $strsubject = implode(",", ($_POST['subject']));应该是:
      2. $strsubject = "'" . implode("', '", ($_POST['subject'])) . "'";