duandi6531 2016-05-12 15:00
浏览 26

数组在php中没有按预期工作

I am running into a very strange issue.

I have a function which prints the columns name of a given database table from MySql.

function getColoumn() {

    //replace it with your host normally it could be localhost
    $hostname='localhost';
    //mysql user name
    $username='admin_datauser';
    //mysql user password
    $password='iCoq4KrJM8';
    //connect to the mysql server
    $ss = mysql_pconnect($hostname, $username, $password) or trigger_error(mysql_error(),E_USER_ERROR);
    //select a database on the mysql server
    //please change as you like the database name
    mysql_select_db('admin_data');

    //SHOW COLUMNS FROM TABLENAME
    $query=mysql_query('SHOW COLUMNS FROM user') or die(mysql_error());


    foreach($fields as $key=>$field){
    echo '"'.$field->Field.'", '; // print each field name

    }
}   

The output looks like below-

"id", "first_name", "last_name", "email", "address", "country", "city", "state", "phone_number", "fax", "image", "datecreated", "dateupdated", "Company", "token", 

I have another array variable where the current static values are like below-

$searchArray = array("first_name","last_name","email","address","country","city","state","phone_number","fax","image");

I need to use the function's variable in this $searchArray. I tried calling the variable in the arrya but it doesn't work in any way.

Any help please??

  • 写回答

1条回答 默认 最新

  • doupiao9318 2016-05-12 15:08
    关注

    first of all you shouldn't use mysql_ functions anymore since they are deprecated and prone to SQL injections. rather use PHP's own PDO or mysqli libraries.

    then it's much easier to directly add the elements to your array in the foreach loop:

    $searchArray = array();
    
    foreach($fields as $key=>$field){
        $searchArray[]= $field->Field;
    }
    

    note: the []= operator in PHP acts similar to the += operator. but instead of adding to a number value, it adds elements to an array.

    评论

报告相同问题?

悬赏问题

  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题