串联mysql select查询与php变量? [英] concatenate mysql select query with php variable?

查看:153
本文介绍了串联mysql select查询与php变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图连接MySQL SELECT 查询与PHP变量,但有一个错误。
我的PHP语句产生错误是:

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

且错误为:

 (!)注意:未定义的变量:在第18行的C:\wamp\www\pollBook\poll\login.php中的信息
调用堆栈

我不明白我在哪里错过了代码。
当我编写查询不带 WHERE 子句时,它工作正常。

解决方案

您的代码无效的原因



您正尝试使用变量 $ info ,尚未定义。当你尝试使用未定义的变量时,你实际上没有将任何内容连接到字符串中,但是因为PHP是松散键入的,所以它声明变量是第二个引用它的变量。这就是为什么你会看到通知,而不是致命错误。你应该通过你的代码,并确保 $ info 获得一个赋值给它的值,并且它在某个时候不被另一个函数覆盖。但是,更重要的是,请阅读下文。





停止您正在做的事






这很容易受到一种叫做 SQL注入。我不会告诉你如何连接SQL字符串。这是可怕的做法。



您应该在PHP中使用mysql函数。它们已被弃用。而是使用PHP PDO对象,使用预准备语句。这是一个相当不错的教程



http://www.php.net/manual/en/pdo.connections.phprel =nofollow>本教程,您将能够创建一个PDO对象,所以我将离开位为您。



下一步是使用 prepare 方法添加您的查询:

  $ PDO-> prepare(SELECT * FROM tbl WHERE`id` =:id); 
//加载SQL语句。注意:id位。
$ actualID =this is a ID;
$ PDO-> bindParam(':id',$ actualID);
//将值绑定到SQL字符串中的参数。
$ PDO-> execute();
//这将为你运行SQL查询。


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.

解决方案

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.

这篇关于串联mysql select查询与php变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆