Home > Enterprise >  On DB Query PHP return NULL but are records
On DB Query PHP return NULL but are records

Time:09-01

[PHP 8.1/SQL 10.4]

DB Structure

CREATE TABLE `trundschreiben` (
  `rsID` int(11) NOT NULL,
  `rsMTGLemail` varchar(255) COLLATE latin1_german1_ci NOT NULL,
  `rsVersendet` tinyint(1) DEFAULT NULL,
  `rsVersanddatum` date DEFAULT NULL,
  `rsAbsender` varchar(255) COLLATE latin1_german1_ci DEFAULT NULL,
  `rssprache` varchar(3) COLLATE latin1_german1_ci NOT NULL,
  `rskurse` text COLLATE latin1_german1_ci NOT NULL,
  `rskurseplain` text COLLATE latin1_german1_ci NOT NULL,
  `rsfirmenname` varchar(255) COLLATE latin1_german1_ci DEFAULT NULL,
  `rstyp` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_german1_ci;

PHP Code:

   $sql = "SELECT MAX(rsID) as rsid FROM trundschreiben";   
   $result = mysqli_query($db_link, $sql);  
   $nrRS =  mysqli_fetch_array($result, MYSQLI_ASSOC)

GOAL

Get the highest value of 'rsID' from the table

WHAT I TRIED

In phpmyadmin it works perfectly, the value is returned

QUESTION

In PHP, var_dump($nrRS); returns me a value of

array(1) { ["rsid"]=> NULL }

while the $result returns me this array

current_field: 0 
field_count: 1 
lengths: null 
num_rows: 1 
type:0

How come I can't receive the value as I expect? Thank you!

CodePudding user response:

As You can see you have already returned num_rows: 1 That means your query is working fine and it is returning record.

Please try to update your code

$sql = "SELECT MAX(rsID) as rsid FROM trundschreiben";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo "id: " . $row["rsid"]."<br>";
  }
} else {
  echo "0 results";
}

CodePudding user response:

Tested your case on my side and works perfectly. Are you sure there's no code after $nrRS that's harming the result !?

<?php
$database = mysqli_connect("localhost","root","","pse");
$sql = "SELECT MAX(rsID) as rsid FROM trundschreiben";   
$result = mysqli_query($database, $sql);  
$nrRS =  mysqli_fetch_array($result, MYSQLI_ASSOC);

var_dump($nrRS);

Result:

array(1) { ["rsid"]=> string(1) "2" }

Note: PHP Version 7.4.27

PHP 8.1.0 Result:

array(1) {
  ["rsid"]=>   
  string(1) "2"
}
  • Related