dongle19863 2016-01-14 02:17
浏览 38
已采纳

PHP查询到MySQL返回单值

I am very new to PHP and SQL. I am a java and XML developer for android. I'm having issues here because I simply need a single value returned and cant seem to get it out of the pdo prepared query. All I'm looking for is to be returned devId "device id" from one table and insert it into another. "user_id" is the auto incremented primary and represents different users. Each row has a "devId" varchar() column. Please help me out here. I need the value for "devId" for the "user_id" i passed through. Very simple you would think to return this single value.

$query = $pdo->prepare("SELECT devId FROM accounts WHERE user_id='{$user->user_id}'");
$query->execute();
$result = $query->fetchAll();
$pdo->exec("INSERT INTO devicesTable(devId) VALUES('{$result[0]}')");
  • 写回答

3条回答 默认 最新

  • dongmen1860 2016-01-14 02:40
    关注

    First, PDOStatement::fetchAll() returns a 2-dimensional array containing all the rows of the result set; second, that's not how you use a prepared statement.

    The idea behind prepared statements is that when you prepare it you insert place-holders, and then when you execute you bind the place-holders to specific values, and can execute the query repeatedly with different bound values without reparsing the query. Additionally, the prepared statement automagically handles details like type-matching, quoting and escaping for you.

    $stmtSel = $pdo->prepare("SELECT devId 
                            FROM accounts 
                            WHERE user_id=:id");
    
    $stmtSel->bindParam(':id', $user->user_id, PDO::PARAM_STR);
    
    $stmtSel->execute();
    
    $stmtSel->bindColumn('devId', $devId);
    $stmtSel->fetch(PDO::FETCH_BOUND)) 
    
    $stmtIns = $pdo->prepare('INSERT INTO devicesTable (devId) VALUES(:devId)')
    $pdo->execute(array(':devId' => $devId));
    

    (Note this is almost the same as RiggsFolly's solution, except that mine uses two prepared statements stored in separate variables so they can both be reused.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?