duanfei7508 2010-11-27 04:40
浏览 49
已采纳

将数据表的元素存储到数组中

I have a database table made in phpmyadmin. I want the elements of the table to be stored row-wise in an array. I have three columns named edge_id, vertexA and VertexB. I want the elements of these three columns to be stored into an array.

I don't know those commands for PHP. Please help me out.

  • 写回答

3条回答 默认 最新

  • douxing5598 2010-11-27 04:52
    关注

    i have columns in my table named "vertexa" and "vertexb",i want to store the colums in two separate arrays ...how can i do it??

    The simplest way would be:

    $db = new PDO('mysql:host=localhost;dbname=your_db_name;', $user, $password);
    $vertices_a = array();
    $vertices_b = array();
    
    foreach($db->query('SELECT * from your_table_name') as $row){
      $id = $row['edge_id'];
    
      // add them to the proper array using the edge_id as the index - 
      // this assumes edge_id is unique
      $vertices_a[$id] = $row['vertexa'];
      $vertices_b[$id] $row['vertexb'];
    }
    

    So with PDO:

    $db = new PDO('mysql:host=localhost;dbname=your_db_name;', $user, $password);
    
    foreach($db->query('SELECT * from your_table_name') as $row){
      echo $row['edge_id'];
      echo $row['vertexA'];
      echo $row['vertexB'];
    }
    

    Now if you need to use input data you need to escape it. The best way to do this is to use a prepared statement because escaping is handle when the parameters are bound to the query.

    Lets say for example you want to use the edge_id supplied from a get request like mysite.com/show-boundry.php?edge=5...

    $db = new PDO('mysql:host=localhost;dbname=your_db_name;', $user, $password);
    
    // create a prepared statement
    $stmt = $db->prepare('SELECT * from your_table_name WHERE edge_id = ?');
    
    // execute the statement binding the edge_id request parameter to the prepared query
    $stmt->execute(array($_GET['edge']));
    
    // loop through the results    
    while(false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC))){
      echo $row['edge_id'];
      echo $row['vertexA'];
      echo $row['vertexB'];
    }
    

    Also you shouldnt use mixed case column/table names like vertexA instead use underscore separators like vertex_a.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。