PHP Unable to insert data into database using PDO - php

I want to insert data given by the user into the database when I use simple mysqli it works perfectly but when I use PDO data is inserted into the database.
<?php
$server = 'localhost';
$username = 'root';
$pass = '';
$database = 'db';
try {
$conn = new PDO("mysql:host=$server;dbname=$database", $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$name = '';
$password = '';
$email = '';
$uid = '';
$sql = "INSERT INTO users(name,email,password,userid) VALUES(?,?,?, ?)";
if (isset($_POST['username'])) {
$name = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$uid = $_POST['uid'];
$newpass = hash("sha256", $password);
if ($name != '' && $password != '' && $email != '') {
$insertUser = $conn->prepare($sql);
$insertUser->execute($name, $email, $password, $uid);
}
}
$conn = null;

Just use parameters array:
$sql = "INSERT INTO users(name,email,password,userid) VALUES(?, ?, ?, ?)";
if(isset($_POST['username']))
{
$name = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$uid = $_POST['uid'];
$newpass = hash("sha256", $password);
if($name!='' && $password!='' && $email!='')
{
$insertUser = $conn->prepare($sql);
// use ARRAY instead plain variables
$insertUser->execute([$name, $email, $password, $uid]);
}
}
Execute PHP online

Related

HTML form returns PHP script instead of success message

There is an html form which I want to store data from in a database. After filling the form, it returns the php script instead of success message. And no data is getting stored in the database. Can you please help?
<?php
if (isset(['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$gender = $_POST['gender'];
$email = $_POST['email'];
}
if (!empty($username) || !empty($password) || !empty($gender) || !empty($email) {
$host = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbname = "cakeshop";
$conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);
if (mysqli_connect_error()) {
die('Connect Error('. mysqli_connect_error().)')'. mysqli_connect_error());
}else {
$SELECT = "SELECT email From register Where email = ? Limit 1"
$INSERT = "INSERT INTO register (username, password, gender, email) values(?, ?, ?, ?)";
$stmt = $conn->prepare($SELECT);
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($email);
$stmt->store_result();
$rnum = $stmt->num_rows;
if ($rnum==0){
$stmt->close();
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("ssss", $username, $password, $gender, $email);
$stmt->execute();
echo "New record inserted successfully"
}else {
echo "Someone already registered";
}
$stmt->close();
$conn->close();
}
}
?>

Connect Error(2002)Connection refused (Heroku)

I have been trying to connect to my database (I used Xampp) and made a PHP trying to link the file to the "users" database that I made. There is an issue as whenever I click the "Register" button it has an error saying "Connect Error(2002)Connection refused." Any help would be appreciated!
PHP code
<?php
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$phone = $_POST['phone'];
if (!empty($name) || !empty($username) || !empty($password) || !empty($email) || !empty($phone)) {
$host = "localhost:80";
$dbUsername = "root";
$dbPassword = "";
$dbname = "pracdata";
//create connection
$conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);
if (mysqli_connect_error()) {
die('Connect Error('. mysqli_connect_errno().')'. mysqli_connect_error());
} else {
$SELECT = "SELECT email From users Where email = ? Limit 1";
$INSERT = "INSERT Into users (name, username, password, email, phone) values(?, ?, ?, ?)";
//Prepare statement
$stmt = $conn->prepare($SELECT);
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($email);
$stmt->store_result();
$rnum = $stmt->num_rows;
if ($rnum==0) {
$stmt->close();
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("ssssii", $username, $username, $password, $email, $phone);
$stmt->execute();
echo "Your account has been registered!";
} else {
echo "This email is already linked to Preak account";
}
$stmt->close();
$conn->close();
}
} else {
echo "All fields are required";
die();
}
?>

What is the mistake in this PHP code?

I have a user registration system but its empty. This is the script I use in forum.modxpertz.tk. It worked at first but it shows nothing now. Here is the code.
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db($conn,'login');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT userid FROM login";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$reguserid=$row["userid"];
}
$userid = mysqli_real_escape_string($conn, $_POST['userid']);
$pswrd = mysqli_real_escape_string($conn, $_POST['pswrd']);
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$token = rand('122332344','922332344');
$url = array('forum.modzexpertz.tk/verify.php#',$token);
$post= join($url);
if($userid!=$reguserid){
$sql = "INSERT INTO login(fname, lname, userid, pswrd, gender)VALUES('$fname', '$lname', '$userid', '$pswrd', '$gender')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
}else {
echo "Failed to Register.";
}} else {
echo "A user with the email youve provided has already been registered.";
}}
$conn->close();
?>
I know only little about PHP and jQuery.
Please try below code :
<?php
$servername = "localhost";
$username = "root";
$pswrd = "";
$db = "login";
$conn = mysqli_connect($servername,$username,$pswrd, $db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$table = 'login';
if(#mysqli_num_rows(mysqli_query($conn, "SELECT NULL FROM `$table` WHERE userid='".$_POST['userid']."'")) > 0){
$error = "1";
echo "user with same userid is already exist";
}
if(isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['gender']) && isset($_POST['userid']) && isset($_POST['pswrd']) && $_POST['fname']!="" && $_POST['lname']!="" && $_POST['gender']!="" && $_POST['userid']!="" && $_POST['pswrd']!="")
{
if($error==''){
$ins['fname'] = mysqli_real_escape_string($conn, $_POST['fname']);
$ins['lname'] = mysqli_real_escape_string($conn, $_POST['lname']);
$ins['gender'] = mysqli_real_escape_string($conn, $_POST['gender']);
$ins['userid'] = mysqli_real_escape_string($conn, $_POST['userid']);
$ins['pswrd'] = mysqli_real_escape_string($conn, $_POST['pswrd']);
$insertsql = "INSERT INTO `$table` (fname, lname, gender, userid, pswrd) VALUES ('".$ins['fname']."','".$ins['lname']."','".$ins['gender']."','".$ins['userid']."','".$ins['pswrd']."')";
#mysqli_query($conn, $insertsql);
//echo $insertsql; exit;
echo "Success";
}
}else{
echo "Please enter required parameters";
}
mysqli_close($conn);
?>

Error with PDO in this script | The page turn blank

I'm having a strange problem using PDO in this script. Probably the problem is very simple but i can't find it and it is making me crazy.
The problem is when i launch the script the page turn blank.
<?php
//PDO
if(isset($_POST['submit'])) {
// test row
$password = $_POST['upassword'];
$email = $_POST['email'];
$_SESSION['email'] = $email;
$servername = "localhost";
$username = "root";
$password = "passwordxyz";
$dbname = "abcd";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $conn->prepare('SELECT `password` FROM `users` WHERE `email` = :email');
$statement->bindParam(':email', $email);
$statement->execute();
while($row = $statement->fetch() ){
echo 'ok';
}
}
}
?>
Please help me to solve the problem.
Thank you.
You have try clause but no catch which is what is generating the error.
<?php
//PDO
if(isset($_POST['submit'])) {
$password = $_POST['upassword'];
$email = $_POST['email'];
$_SESSION['email'] = $email;
$servername = "localhost";
$username = "root";
$password = "passwordxyz";
$dbname = "abcd";
try{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $conn->prepare('SELECT `password` FROM `users` WHERE `email` = :email');
$statement->bindParam(':email', $email);
$statement->execute();
while($row = $statement->fetch() ){
echo 'ok';
}
}
catch(Exception $e){
//change from general to specific exception and handle here
}
}

Convert php code with Mysql ext to PDO won't work

I have decided for security to convert my simple php with mysql code to PDO,since it will tighten my security.My old code:
$host = "localhost";
$user = "username";
$pass = "pass";
$database = "mydatabase";
$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");
$name=$_POST['name'];
$message=$_POST['message'];
$ip = $_SERVER['REMOTE_ADDR'];
$query="INSERT INTO table (date_time, name, message,ip) VALUES (NOW(),'$name','$message','$ip')";
If (mysql_query($query,$linkID)){
//Success
}else{
//Failure
}
My new code is:
$hostname = 'localhost';
$username = 'username';
$password = 'pass';
$dbname = 'mydatabase';
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
if($_POST['name'] && $_POST['message']) {
$name = $_POST['name'];
$message = $_POST['message'];
$ip = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO table (date_time, name, message,ip)VALUES (NOW(), :name, :message,'$ip')";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':message', $message, PDO::PARAM_STR);
if ($stmt->execute()) {
echo "OK";
}
}
It's very strange that when i point my browser to index.php?name=someName&message=someMessage my PDO code won't echo a single thing(even echo "ok" ) or an error so i can fugure out where is the problem.
I can confirm that no data is inserted to the database.
I've even added try catch but nothing changed. My php is supporting PDO and the simple Mysql code is working.
Any ideas? Thanks
In your case,
if($_POST['name'] && $_POST['message']) {
Should be:
if($_GET['name'] && $_GET['message']) {

Categories