0

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.

2
  • 1
    SELECT max(WO_NUM)+1 as NEW_NUM from GENERIC_TABLES.WO_NUMBERS ??? Commented Oct 21, 2016 at 16:39
  • Exactly! I didnt take into mind that if I use WO_NUM + 1, it changes column name, that is why it didn't give any result..Using Alias solved problem. Thanks you very much @AbraCadaver, saved my time by pointing to this... Commented Oct 21, 2016 at 16:47

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

As it has been pointed by AbraCadaver, I missed that if I am using WO_NUM + 1 then column name changing so that is why i didn't get any output, so using alias solved problem.

1 Comment

Please accept @AbraCadaver Answer, if it helped you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.