1

I'm trying to allow users to create an account on my website and have their data stored in my connected database. I've been able to establish a connection and pull data from the database and display it on my website, but I cannot figure out how to insert any data. Here's my code:

<form class"login-form" action="phptest.php" method="POST">
   <input type="text" name="username">
   <input type="submit">Create Account</input>
</form>

<?php
<-- establish connection do database-1 -->
   $serverName = "database-1";
   $connectionInfo = array("Database"=>"maindb", "UID"=>"admin", "PWD"=>"rootuser");
   $conn = sqlsrv_connect($serverName, $connectionInfo);

<!-- assign entered username to a variable and display on webpage -->
   $username = $_POST['username'];
   echo $username;

<!-- insert username into database -->
   if ($_SERVER['REQUEST METHOD'] == 'POST'){
      $sql = "INSERT INTO Accounts (username) VALUES ('$username')";
      $stmt = sqlsrv_query($conn, $sql);
      if ($stmt === false){
         die(print_r(sqlsrv_errors(), true));
      }
      if (sqlsrv_fetch($stmt) === false){
         die(print_r(sqlsrv_errors(), true));
      }
   }
?>

I am able to display the inputed data on to the webpage so I know that's working, but when I log on to my database in Sql Server Management Studio there is no new data in my Accounts table. There's a lot of examples on how to do this on MySql but I can't find any examples when it comes to Microsoft Sql Server. Any help would be much appreciated, Thanks in advance!

nkulow
  • 11
  • 3
  • Does this answer your question? [Why saving changes to a database fails?](https://stackoverflow.com/questions/17147249/why-saving-changes-to-a-database-fails) – SMor Jul 08 '20 at 20:31
  • Thanks for your reply. I'm still in college so i'm not very experienced with coding so I apologize if the answer is right in front of me but I'm still not understanding. It may answer my question but i'm having trouble understanding how it relates to my situation. Is it basically saying there's nothing wrong with my syntax and it has to do with the database or server? I am just using Sublime text editor to code everything, not Visual Studio, i'm not sure if that matters. – nkulow Jul 08 '20 at 21:20
  • You wrote you could "see" the rows you inserted in your application. That implies (because we can't see nor debug your app) that your insert statements work correctly. The issue seems to be related to how you attempt to examine your database afterwards. So either you are not looking at the correct database (or server instance) or you are running into the problem of the substitution string mentioned in the link. Or perhaps I don't really understand your issue - context is important when discussing technical issues in a public forum. – SMor Jul 08 '20 at 22:34

1 Answers1

0

use PDO you can check php manual at php.net https://www.php.net/manual/en/ref.pdo-dblib.php