PHP PDO mysql return strings

There are many questions to this, and I have done a lot of research. However, I am still wondering if I am doing this correctly.

Here is my statement (I simplified it):

try { $stmt = $pdc_db->prepare("SELECT * FROM table WHERE color = :color"); $stmt->bindValue(':color', $selected_color); $stmt->execute(); $color_query = $stmt->fetchAll(); } catch(PDOException $e) { catchMySQLerror($e->getMessage()); } 

Now I use the following to find out if they returned any results:

 if (count($color_query) > 0) { 

This works, HOWEVER ... the SELECT statement will return only one result. So now, to access the materials in the results, I use $ color_query [0] [colorname]. I know this because I use fetchAll (), but I really want to use fetch ()

But if I just use fetch (), I lose the ability to do count (), which is pretty simple for me. I know that I can make a separate query and check the results of SELECT COUNT (*), but this seems to work (setting two separate queries for each)

There must be a way using PDO in PHP with mySQL to check if fetch () returned a result?

+4
source share
2 answers

$ stmt-> rowCount () after executing (), but does not work with all databases ... try using MySQL and see what you get.

+4
source

You can do this with fecth , fecth will return false if the results are not returned.

 if ($row = $stmt->fetch()) { //get the first row of the result. //.... } 
0
source

Source: https://habr.com/ru/post/1392273/


All Articles