duanlei4759 2014-12-10 13:19
浏览 40
已采纳

从mysql中选择Single Value

I'm trying to select a single value from mysql - but however it does not work:

public function doStuff($posted_name){    
    $result = mysql_query("SELECT id FROM people WHERE people_name = $posted_name");
    $singleValue = mysql_fetch_object($result);
}

posted_name, people_name is TEXT, id is INT

I am posting a $posted_name , this I let compare with column people_name from table people, and selecting the column "id" ...

this id i want to store as value , here I tried to store it in $singleValue... but however it does not work - is there any mistake?

Solved: see comments

EDIT:

I changed some code to mysqli for testing- but now I have some error:

my code looks like:

private $db;


    // constructor
    function __construct() {
        include_once './db_connect.php';
        // connecting to database
        $db = new DB_Connect();
          $this->db = $db->connect();
    }

. . . . .

$result = this->db->query("INSERT INTO.....

The error appears for the above line ... Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR)...

what I am doing wrong

my db_connect.php

class DB_CONNECT {

    private $db;

    // constructor
    function __construct() {
        // connecting to database
        $this->connect();
    }


    /**
     * Function to connect with database
     */
    function connect() {
        // import database db variables
        require_once __DIR__ . '/db_config.php';

        // Connecting to mysql database
       $this->db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD);

        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }
        // Selecing database

        // returing connection cursor
        return $this->db;
    }



}
  • 写回答

4条回答 默认 最新

  • drcx71276 2014-12-10 13:46
    关注

    You need to add single quote in $posted_name like this '$posted_name'. and you should know how mysql_fetch_object() works and what it return.

    mysql_fetch_object() fetches the result row as an object.It returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead.

    I have edited your code which looks like this ...

    public function doStuff($posted_name){    
        $result = mysql_query("SELECT id FROM people WHERE people_name = '$posted_name'");
        if($result){
             while ($row = mysql_fetch_object($result)){
                  $id =  $row->id;
                  echo $id;
              }
         }
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算