PHP: Retrieving two most recent mySQL table entries and storing each in a different variable

StackOverflow https://stackoverflow.com/questions/23687804

  •  23-07-2023
  •  | 
  •  

سؤال

Please see the below code.

I am trying to retrieve the most recent two "element_value"s from my database table and then put them into a different table, with one column each. I can do this part with a mysql insert statement if I can get them into variables within the PHP, at the moment I have them being echoed out to the screen instead.

Does anyone know please how I can get them into two separate variables instead?

Thanks!

//Connect to database
$con=mysqli_connect("localhost","user","pass","dbname");

// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL database: " . mysqli_connect_error();
}

//Query the database
$result = mysqli_query($con, 'SELECT element_value FROM wp_formmaker_submits ORDER BY id DESC LIMIT 2;');

//Process the results
if  (mysqli_num_rows($result) > 0) {
while   (  $dataValue = mysqli_fetch_row($result))

    echo "<p>".$dataValue[0]."</p>";   
}
هل كانت مفيدة؟

المحلول

Change :

while ($dataValue = mysqli_fetch_row($result))

    echo "<p>".$dataValue[0]."</p>"; 

To this :

$values = null;
while ($dataValue = mysqli_fetch_assoc($result))
{
    $values[] = $dataValue['element_value'];
}

print_r($values);

This will store your values in an array, I've added print_r at the end just so you can see the resulting data structure.

If you want to display them in an array again, you can do this :

foreach ($values as $value)
{
    echo "<p>".$value."</p>"; 
}

I've changed your fetch_row method for fetch_assoc, an explanation can be found here : https://stackoverflow.com/a/9540590/2483649

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top