doulongdan2264 2015-01-08 15:44
浏览 88
已采纳

如何使用关联数组将数据插入MySql

I am now having a problem inserting data in associative array with its key as fields in the table and the values to be inserted into MySql database. Here is my code.

<?php
$table = 'articles';

$data = array(
        'title' => 'Header',
        'content' => 'This is content',
        'author' => 'James');

$keys = implode(', ', array_keys($data));
$values = implode(', ', array_values($data));

$sql = 'insert into '.$table.'('.$keys.') values ('.$values.')';

$db = new mysqli('localhost', 'root', 'root', 'blog');
$db->query($sql);
?>

With this code, I wasn't able to insert the data into the database so I try to echo the query string out and I got something like this :

insert into articles(title, content, author) values (Header, This is content, James)

However, if I use the single quote in each value like this

insert into articles(title, content, author) values ('Header', 'This is content', 'James')

I can successfully insert the data into the database.

So I don't know what's wrong here. Is it a problem with the quote sign or not because when I use the single quote, this seems to work.

So please help me find the proper solution for this...

  • 写回答

3条回答 默认 最新

  • douyuan4825 2015-01-08 16:02
    关注

    For the query you need to enclose each value in quotes. To do that you can change your implode statement to include the quotes to around the values -

    $values = "'" .implode("','", array_values($data)) . "'";
    

    You should also be checking for errors.

    Replace $db->query($sql);

    with

    if(!$result = $db->query($sql)){ 
    
    die('There was an error running the query [' . $db->error . ']'); 
    
    }
    
    else{
    echo "Data inserted.";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 elasticsearch
  • ¥30 python ttk 获取下拉框问题
  • ¥15 uniapp的uni-datetime-picker组件在ios端不适配
  • ¥15 前端 uniapp App端在离线状态如何使用modbus 连接手机蓝牙进行读写操控机器?
  • ¥15 SQL语句根据字段自动生成行
  • ¥500 “掌声响起来”软件(不确定性人工智能)
  • ¥500 我要找大模型一体机产品手册和应用案例
  • ¥20 关于游戏c++语言代码问题
  • ¥15 如何制作永久二维码,最好是微信也可以扫开的。(相关搜索:管理系统)
  • ¥15 delphi indy cookie 有效期