dongweihuan8832 2013-03-08 11:42
浏览 33
已采纳

使用php变量连接mysql select查询?

I am trying to concatenate a MySQL SELECT query with PHP variable but got an error. My PHP statement which gives an error is:

 $result=mysql_query("SELECT user_id,username,add FROM users WHERE username =".$user."AND password=".$add);

and error as:

( ! ) Notice: Undefined variable: info in C:\wamp\www\pollBook\poll\login.php on line 18
Call Stack

I don't understand where I missed the code. When I write query without WHERE clause it works fine.

  • 写回答

5条回答 默认 最新

  • dongyue9864 2013-03-08 11:45
    关注

    The reason why your code isn't working

    You are attempting to use a variable, $info, that has not been defined. When you attempt to use an undefined variable, you're effectively concatenating nothing into a string, however because PHP is loosely typed, it declares the variable the second you reference it. That is why you're seeing a notice and not a fatal error. You should go through your code, and ensure that $info gets a value assigned to it, and that it is not overwritten at some point by another function. However, more importantly, read below.


    Stop what you are doing

    This is vulnerable to a type of attack called an SQL Injection. I'm not going to tell you how to concatenate SQL strings. It's terrible practice.

    You should NOT be using mysql functions in PHP. They are deprecated. Instead use the PHP PDO Object, with prepared statements. Here's a rather good tutorial.

    Example


    After you've read this tutorial, you'll be able to make a PDO Object, so I'll leave that bit for you.

    The next stage is to add your query, using the prepare method:

    $PDO->prepare("SELECT * FROM tbl WHERE `id` = :id");
    // Loads up the SQL statement. Notice the :id bit.
    $actualID = "this is an ID";
    $PDO->bindParam(':id', $actualID);
    // Bind the value to the parameter in the SQL String.
    $PDO->execute();
    // This will run the SQL Query for you.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了