Playing with Arrays

II have a query which goes into an array.

  $sql = "SELECT model,manufacturer,airflow_type,external_width,external_depth,external_height,weight,
  number_of_columns_front,number_of_columns_back,number_of_rows_front,number_of_rows_back,total_plugs,
  required_plugs,plug_type,requires_diverse_power,power_consumption 
  FROM chassises 
  INNER JOIN chassis_types ON chassises.chassis_type_id = chassis_types.chassis_type_id 
  WHERE new = 1"; 
  
  //echo $sql;
  
$result = $pdo->query($sql);

	$chassises = array();
	if($result->rowCount() > 0){
		while($row = $result->fetch()){
		  $chassises[] = $row;
		}
	}
	echo '<pre>'; print_r($chassises); echo '</pre>';

the result
Array
(
[0] => Array
(
[model] => ghuu
[0] => ghuu
[manufacturer] => rghu
[1] => rghu
[airflow_type] => Ambient
[2] => Ambient
[external_width] => 4.000
[3] => 4.000
[external_depth] => 4.000
[4] => 4.000
[external_height] => 4.000
[5] => 4.000
[weight] => 4.000
[6] => 4.000
[number_of_columns_front] => 1
[7] => 1
[number_of_columns_back] => 0
[8] => 0
[number_of_rows_front] => 0
[9] => 0
[number_of_rows_back] => 0
[10] => 0
[total_plugs] => 1
[11] => 1
[required_plugs] => 0
[12] => 0
[plug_type] =>
[13] =>
[requires_diverse_power] => 1
[14] => 1
[power_consumption] => 5.000
[15] => 5.000
)

)

how can I get rid of the numerical keys so there is no duplication?

Why not just do this →

$chassises = $pdo->query($sql)->(PDO::FETCH_ASSOC);

echo '<pre>'; print_r($chassises); echo '</pre>';

You should have a unique index (id)?

am getting
Parse error : syntax error, unexpected ‘(’, expecting identifier (T_STRING) or variable (T_VARIABLE) or ‘{’ or ‘$’ in C:\xampp\htdocs\DCT\2\materials\new_chassis_csv_engine.php on line 19

  $sql = "SELECT model,manufacturer,airflow_type,external_width,external_depth,external_height,weight,
  number_of_columns_front,number_of_columns_back,number_of_rows_front,number_of_rows_back,total_plugs,
  required_plugs,plug_type,requires_diverse_power,power_consumption 
  FROM chassises 
  INNER JOIN chassis_types ON chassises.chassis_type_id = chassis_types.chassis_type_id 
  WHERE new = 1"; 
  
  //echo $sql;
  
$chassises = $pdo->query($sql)->(PDO::FETCH_ASSOC); 
	echo '<pre>'; print_r($chassises); echo '</pre>';

shouldn’t that work?

Cause forgot the command.

=>
$chassises = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);

1 Like

Set the default fetch mode to assoc when you make the database connection, so that you don’t need to keep specifying it in each fetch statement.

1 Like

like

    $pdo = new PDO("mysql:host=localhost;dbname=dct", "root", "");

  $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.