Roman Roman - 1 month ago 4
MySQL Question

MySQL query with output to PHP page

I am trying to make simple page which will return values from MySQL table, but the problem is that if I want to use condotions in query then it doesn't work.

My PHP page:

<?php
$servername = "10.10.10.10";
$username = "username";
$password = "password";
$dbname = "GENERIC_TABLES";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT WO_NUM+1 from GENERIC_TABLES.WO_NUMBERS ORDER BY WO_NUM DESC limit 1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> WO Number ". $row["WO_NUM"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>


So, WO_NUM column has numbers like 1, 2, 3 etc.
I want to get the last one + 1
So if I do like:

$sql = "SELECT WO_NUM from GENERIC_TABLES.WO_NUMBERS ORDER BY WO_NUM DESC limit 1";


Then it works fine, but if I want to make it WO_NUM + 1 then it returns nothing.

Why it happens like that and is there any way to get what I want using MySQL?
I don't want to get WO_NUM and then using PHP make it + 1, since I also need INSERT to the table values and I would like to understand why it doesn't work.

Answer

As you realized, WO_NUM+1 changes the column name in the resulting array, so use an alias WO_NUM+1 as NEW_NUM. However I would not bother with the sorting and limit. Consider MAX():

SELECT max(WO_NUM)+1 as NEW_NUM from GENERIC_TABLES.WO_NUMBERS
Comments