-1

How can i convert the result into a string to use it in js? I made an AJAX connection and need the number of all records.

server3.php: The result should be converted to an int.

<?php
  $antwort = $_GET['aa'];

  $con = mysqli_connect('localhost','root','','loginpage');
  if (!$con) {
  die('Could not connect: ' . mysqli_error($con));
  }

  mysqli_select_db($con,"loginpage");
  $sql="SELECT COUNT(id) AS anzahl FROM frage";
  $result = mysqli_query($con,$sql);

  $row = intval($result);

  echo "<p>" . $row . "</p>";

  mysqli_close($con);

  ?>

js.js: I tried it with this.response too.

function anzahlFragen() {

var xmlhttp2 = new XMLHttpRequest();
xmlhttp2.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        fragenAnzahl = this.responseText;
    }
}

xmlhttp2.open("GET","server3.php",true);
xmlhttp2.send();
}
  • You need to stop manually checking for errors. Please read: [Should we ever check for mysqli_connect() errors manually?](https://stackoverflow.com/q/58808332/1839439) and [Should I manually check for errors when calling “mysqli_stmt_prepare”?](https://stackoverflow.com/q/62216426/1839439) – Dharman Dec 23 '20 at 21:49

2 Answers2

2

You haven't fetched your result data. After

$result = mysqli_query($con,$sql);

You need to get the column value, which you can do using mysqli_fetch_array:

$row = mysqli_fetch_array($result);
$count = $row[0];

Then you can echo the count:

echo "<p>" . $count . "</p>";
Nick
  • 138,499
  • 22
  • 57
  • 95
0

You need to fetch row from db, something like:

$sql = "SELECT COUNT(id) AS anzahl FROM frage";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($result);

// access your value by alias in the query
echo "<p>" . $row['anzahl'] . "</p>";

mysqli_close($con);
u_mulder
  • 54,101
  • 5
  • 48
  • 64