开发者

Store elememts of a datatable into an array

开发者 https://www.devze.com 2023-01-27 17:21 出处:网络
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 e开发者_如何学Python

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 e开发者_如何学Pythonlements of these three columns to be stored into an array.

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


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.


You first need to connect to the database:

$link = mysql_connect('localhost','username','password');
if (!$link) {
    // Cannot connect
}
$ret = mysql_select_db('database-name', $link);
if (!$ret) {
    // Cannot select database
}

Then you need to execute your query:

$ret = mysql_query('SELECT * FROM `table`;', $link);
if (!$ret) {
    // Query failed
}

Then you simply load each row:

$data = array();
while ($row = mysql_fetch_assoc($ret)) {
    $data[] = $row;
}

Then you should free your request results

mysql_free_result($ret);

And voilà.


$res = mysql_query("............");
$row = mysql_fetch_array($res);

Checkout: mysql_fetch_array PHP page

0

精彩评论

暂无评论...
验证码 换一张
取 消