Hello. The idea is: there is a MySQL table, say, with 2 columns:

  1. The id column, which is Primary Key Not NULL AUTO INKREMENT
  2. A column with a numeric value (price or number, whatever).

How to unload all the values ​​understood, and how to unload the values ​​of the second column depending on id, yet. Everything is invoked through PHP .

I added the question to what I managed to do on my own. PHP knowledge is not enough.

<?php ini_set('display_errors','On'); error_reporting(E_ALL);//показ всех ошибок $host = 'localhost'; // имя хоста $database = 'test_sql'; // имя базы данных $user = 'root'; // имя пользователя $pswd = ''; // пароль $dbh = mysql_connect($host, $user, $pswd) or die("Не могу соединиться с MySQL.");//соединение с бд mysql_select_db($database) or die("Не могу подключиться к базе."); $query = "SELECT * FROM `oc_product`";//выгрузка из таблицы $res = mysql_query($query); $row = mysql_fetch_array($res);//вызов массива while($row = mysql_fetch_array($res)){ echo "ID: ".$row['product_id']."<br>";//вывод всех id echo "Цена: ".$row['price']."<br>";//вывод всех цен } ?> 

  • select поле from table where id=X - Mike
  • Perhaps not exactly described the question. In the future, the value of the 2nd column will be pulled into the calculator. If you describe the full picture, the user enters the site, selects the product (it’s id) and when using the calculator, the value of the 2nd column will be used exactly this id. That is, if you use your query, then you need to write it to each id, right? This is not exactly what you need. - Vlad Yudkin
  • which means "write to each id". You have only 2 options: Get the entire table in memory and give it entirely to the customer and let him search for the price in the array at the moment of selecting the goods. Either the client sends a request to the server (normal or ajax) at the moment of selecting the goods and sends the ID. You get the price from the database on the received ID and give it to the client - Mike
  • The second is either well described, what is needed) But I don’t quite understand how to write id = x with the promise id = "that's what they’ve just clicked on" - Vlad Yudkin
  • examples in the documentation php.net/manual/ru/pdostatement.execute.php see, there just the parameters are passed to the request. either bind first then execute, or an array of parameters is passed directly to execute, which of course is much more convenient - Mike

2 answers 2

Good day, for a start, the advice is this, if you write in procedural styles in php, it is strongly recommended to put the information about the connection to the database in a separate php file, for example called (connect.php):

 $host = 'localhost'; $database = 'test_sql'; $user = 'root'; $pswd = ''; $link = mysql_connect($host, $user, $pswd) or die("Не могу соединиться с MySQL."); 

And then already where you need to simply write the command at the top:

 require_once "connect.php" 

It is worth mentioning why require and not include. This is all due to the fact that include from require differs in that require falls in a Fatal error when the file cannot be connected for any reason. And include only issues Warning and quietly continues to work. Therefore, they themselves should understand if it was not possible to load the file with the database connection, there is no sense to continue working further. And adding "_once" is necessary in order to avoid re-connecting this file ... And now about your question itself, if you need to unload the value by id depending on which event in the program, then you simply create a variable, for example:

 $number; 

And then you programmatically assign it the desired value, and the output data by the value of this variable (for example, assign it id = 5):

 $number = 5; $query = "SELECT * FROM oc_product WHERE id= " . $number; $result = mysqli_query($link, $sql); $comands = mysqli_fetch_all($result, MYSQLI_ASSOC); 

I hope that my answer will be useful to you, I wish you good luck in learning the PHP language!

  • Thanks for the answer! I already wrote the code, even (for me) translated it into PDO. Now I fight for security and your advice will not pass by. Thanks again. - Vlad Yudkin
 <?php $product_id = NULL; if(array_key_exists('product_id',$_GET)){ $product_id = (int)$_GET['product_id']; } $host = 'localhost'; // имя хоста $port = 3306; $database = 'test_sql'; // имя базы данных $user = 'root'; // имя пользователя $password = ''; // пароль $db = new \PDO('mysql:host='.$host.';port='.$port.';dbname='.$database, $user, $password); echo 'Соединение успешно установлено'; if($product_id !== NULL){ $query = sprintf( 'SELECT product_id, price FROM oc_product WHERE id=%s', mysql_real_escape_string($product_id) ); $statement = $db->prepare($query); $result = $statement->execute(); if(is_bool($result)) { die('Не могу выполнить запрос.'); } $result->setFetchMode(\PDO::FETCH_ASSOC); if($row = $result->fetch()) { echo 'Товар: '.$row['product_id'].'. Цена: '.$row['price'].'<br/>'; }else{ echo 'Товар не найден.'; } }else{ $query = 'SELECT product_id, price FROM oc_product' $statement = $db->prepare($query); $result = $statement->execute(); if(is_bool($result)) { die('Не могу выполнить запрос.'); } $result->setFetchMode(\PDO::FETCH_ASSOC); while($row = $result->fetch()) { echo '<a href="/index.php?id='.$row['product_id'].'"> Товар: '.$row['product_id'].'</a>. Цена: '.$row['price'].'<br/>'; } } $db = null; 

When you click on the link http://my_site/index.php get a list of products, and when you click on the product, the SQL query is executed only on it.

  • 2
    Please do not give examples using the old methods and especially using the outdated mysql extension, whose support in php has almost ceased and will disappear from the hosting sites in a few years, after which the code will stop working. Use examples only with the use of modern extensions mysqli, and better PDO. And using variable bindings instead of substitution directly into the query text - Mike