简体   繁体   中英

php wont insert into mysql database

Im trying to insert some data into a mysql database. But I can not get it to work..

This is my reg.php file:

<?php
include 'mysql.php';
if (isset($_POST['submit']))
{
$email = $_POST["email"];
$sql = ("INSERT INTO users (`email`) VALUES('".$email."') ");
mysql_query($sql);
}
?>
<form action="" method="post"> <br />
<input type="text" name="email">
<input type="submit" name="submit"  >
</form>

And this is my mysql.php file:

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}


echo 'Connected to MySQL<br>';
mysql_close($conn);
?>

And this is my table from phpmyadmin:

CREATE TABLE `users` (
`ID` int(11) NOT NULL,
`email` varchar(25) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`ID`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

So any tips here to how i can solve this?

Thanks!

As someone said in updated version of php mysql_* function are deprecated you can use mysqli_* functions, your code is not working because you have closed your mysqli connection in mysql.php

<?php
   $dbhost = 'localhost';
   $dbuser = 'root';
   $dbpass = '';
   $dbname = "dbname";
   $conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);//Put you db name here
   if(! $conn )
   {
      die('Could not connect: ' . mysqli_error());
   }


   echo 'Connected to MySQL<br>';
   //mysqli_close($conn); comment this line you code will work fine
?>

Thanks
Hope! This will help you

MySQl functions have been deprecated and try to put this in your code

mysql_query($sql);

after this

mysql_close();

also check your XAMPP/PHP version as from PHP 7 MYSQL function has been deprecated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM