本文通过一个例子说明了bind_param()函数在php中的用法。分享给大家参考,如下:
从字面上看,不难理解,约束参数;让我用一个绑定参数的例子来谈谈它:
例如:
bind_param('sss ',firstname,lastname,$ email);
1.这个函数绑定SQL的参数,并告诉数据库参数的值。“sss”参数列处理其余参数的数据类型。s字符告诉数据库该参数是一个字符串。
有四种类型的参数:
I-整数(整数)d-双精度(双精度浮点类型)s-字符串(字符串)b-BLOB(布尔值)
每个参数都需要指定一个类型。
通过告知数据库参数的数据类型,可以降低SQL注入风险。
2.上面的firstname,lastname,$email是引用,不能直接写成php5.3之后的字符串,为了验证这个结论,我在这里写了一个测试,如下:
$ servername=' localhost$ username=' root$ password=' admin$ dbname=' test$ conn=new MySQL($ servername,$username,$password,$ dbname);if($ conn-connect _ error){ die(' connected failed : '。$ conn-connect _ error);} $ SQL=' INSERT INTO user(user _ first,user_last,age)VALUES(?)';$ stmt=$ conn-prepare($ SQL);$stmt-bind_param('sss ',' xiao ',' hong ',22);$ stmt-execute();回声“新闻记录创建成功!”;$ stmt-close();$ conn-close();上面我写了一个测试程序,直接把参数写成字符串,运行后弹出:
最后,我将程序改写如下:
$ servername=' localhost$ username=' root$ password=' password$ dbname=' test$ conn=new MySQL($ servername,$username,$password,$ dbname);if($ conn-Connect _ error){ die(' Connect failed : '。$ conn-connect _ error);} $ SQL=' INSERT INTO user(user _ first,user_last,age)VALUES(?)';$ stmt=$ conn-prepare($ SQL);$stmt-bind_param('sss ',$user_first,$user_last,$ age);$ user _ first=' xiao$ user _ last=' hong$ age=12$ stmt-execute();回声“新闻记录创建成功!”;$ stmt-close();$ conn-close();并且上述程序可以正常执行。
PS:在这里,我们会给大家提供一个相关的php函数表,供大家参考:
Php在线函数参考表:http://tools.jb51.net/table/php_fun_table
更多对PHP相关内容感兴趣的读者可以查看本网站专题:《php字符串(string)用法总结》、《php常用函数与技巧总结》、《PHP数据结构与算法教程》、《php程序设计算法总结》、《PHP数组(Array)操作技巧大全》、《php常见数据库操作技巧汇总》、0103010
希望本文对PHP编程有所帮助。