So im making a web game app my problem is my register.php is not inserting users in the database please need help by the way im just a beginner in PHP Thanks
Here is the Code:
<?php
require_once('mysql_conn.php');
$Username = mysql_real_escape_string($_POST['Username']);
$Password = md5(mysql_real_escape_string($_POST['Password']));
$Email = mysql_real_escape_string($_POST['Email']);
$query_check ="SELECT user_name FROM account_info WHERE user_name = '$Username'";
$retval_check = mysql_query( $query_check, $conn );
if( $Username == "" || $Password == "" || $Email == "" ){
echo"Please fill the field";
} else{
if(mysql_num_rows($retval_check)){
echo"Username Already Taken";
} else {
$query = "INSERT INTO account_info(user_name,user_passemail) VALUES ('$Username','$Password','$Email');";
$retval = mysql_query( $query, $conn );
echo "<script>";
echo "alert('Thank you for registering Enjoy the game !')";
echo "</script>";
echo "<script>";
echo 'location.href = "menu.html";';
echo "</script>";
}
}
mysql_close($conn);
?>
Change:
$query = "INSERT INTO account_info(user_name,user_passemail) VALUES ('$Username','$Password','$Email');";
To:
$query = "INSERT INTO account_info(user_name,user_pass,email) VALUES ('$Username','$Password','$Email');";
You forgot to add a comma ","
Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
Instead, the MySQLi or PDO_MySQL extension should be used.
YOu miss the coma between user_pass and email in column name
$query = "INSERT INTO account_info(user_name,user_pass,email) VALUES ('$Username','$Password','$Email');";
try mysqli
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "username"; //username
$password = "password"; //password
$mysql_database = "dbname"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
//require_once('mysql_conn.php');
$Username = mysqli_real_escape_string($_POST['Username']);
$Password = md5(mysqli_real_escape_string($_POST['Password']));
$Email = mysqli_real_escape_string($_POST['Email']);
//$query_check ="SELECT user_name FROM account_info WHERE user_name = '$Username'";
// $retval_check = mysqli_query( $query_check, $conn );
if(!empty($Username))
{
$stmt = $conn->prepare("SELECT user_name FROM account_info WHERE user_name =? ");
$stmt->bind_param('s',$Username);
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
//change it by respectively
$stmt->execute();
$get_result =$stmt->get_result();
$row_count= $get_result->num_rows;
//$row_count= $stmt->affected_rows;
$stmt->close();
//$conn->close();
}
if( $Username == "" || $Password == "" || $Email == "" ){
echo"Please fill the field";
} else{
if($row_count>0){
echo"Username Already Taken";
} else {
//$query = "INSERT INTO account_info(user_name,user_pass,email) VALUES ('$Username','$Password','$Email');";
^^^^^
//$retval = mysql_query( $query, $conn );
$stmt1 = $conn->prepare("INSERT INTO account_info(user_name,user_pass,email) VALUES (?,?,?)");
$stmt->bind_param('sss',$Username,$Password,$Email);
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
//change it by respectively
$stmt1->execute();
//$get_result1 =$stmt1->get_result();
//$row_count1= $get_result1->num_rows;
$row_count1= $stmt1->affected_rows;
$stmt1->close();
$conn->close();
if($row_count1>0)
{
echo "<script>";
echo "alert('Thank you for registering Enjoy the game !')";
echo "</script>";
}
else
{
echo "<script>";
echo "alert('registeration failed')";
echo "</script>";
}
echo "<script>";
echo 'location.href = "menu.html";';
echo "</script>";
}
}
wrong
$query = "INSERT INTO account_info(user_name,user_passemail) VALUES ('$Username','$Password','$Email');";
correct
$query = "INSERT INTO account_info(user_name,user_pass,email) VALUES ('$Username','$Password','$Email')";
Related
I am trying to insert records into an Oracle database using PHP, but for some reason, the INSERT code is not working.
--DB Table
CREATE TABLE USER (
ID NUMBER(20) GENERATED ALWAYS AS IDENTITY(START WITH 1 INCREMENT BY 1),
ROLE NUMBER(10),
NAME VARCHAR2(50),
PASSWORD VARCHAR2(50),
);
The connection string works:
#PHP: New Oracle Database Connection (db.php):
<?php
$user = "test";
$password = "test123";
$host = "localhost/XE";
$connection = oci_connect($user, $password, $host)
or die(oci_error());
if(!$connection){
echo "Failed: Verify the connection string in db.php";
}else{
//echo "CONNECTED";
}
oci_close ($connection);
?>
This is the insert in PHP that does not work, Could you help me to identify the error?
#PHP+Oracle: INSERT new user (userControllerOracle.php)
<?php
#DB Connection:
include("db.php");
#DB Oracle INSERT:
if (isset($_POST['registro'])) {
$name = $_POST['name'];
$password = $_POST['password'];
$cnn = oci_connect($user, $password, $host);
$query = "INSERT INTO USER (1, name, password) VALUES (1,'$name', '$password')";
}
?>
Previously, I used MySQL and it worked, but I don't know how to achieve the same result in Oracle
#PHP: MySQL Database Connection (db.php):
<?php
$con = mysqli_connect("localhost","test","test123","test");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function debug_to_console($data) {
$output = $data;
if (is_array($output))
$output = implode(',', $output);
echo "<script>console.log('Debug Objects: " . $output . "' );</script>";
}
?>
#PHP+MySQL: INSERT new user (userControllerMySQL.php)
<?php
#DB Connection:
include("php/db.php");
#DB MySQL INSERT:
if (isset($_POST['registro'])) {
if (strlen($_POST['name']) >= 1 && strlen($_POST['password']) >= 1) {
$name = trim($_POST['name']);
$password = trim($_POST['password']);
$query = "INSERT INTO USER(1, name, password) VALUES (1,'$name', MD5('$password')";
$result = mysqli_query($con,$query);
if ($result) {
?>
<h5 style="text-align: center; background-color:#28a745; color:white">User added!</h5>
<?php
} else {
?>
<h5 style="text-align: center; background-color:#dc3545; color:white">error!</h5>
<?php
}
} else {
?>
<h5 style="text-align: center; background-color:#ffc107; color:#343a40">add all fields!</h5>
<?php
}
}
?>
Use oci_bind_by_name() to bind parameters in the SQL, rather than substituting variables directly into the SQL string.
$name = $_POST['name'];
$password = $_POST['password'];
$cnn = oci_connect($user, $password, $host);
$query = "INSERT INTO USER (1, name, password) VALUES (1,:name, :password)";
$stmt = oci_parse($conn, $query);
oci_bind_by_name($stmt, ':name', $name);
oci_bind_by_name($stmt, ':password', $password);
oci_execute($stmt);
Fixed, I was missing:
$parse = oci_parse($connection, $sql);
oci_execute($parse);
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);
?>
I found a code php for updating database, but it's just for two field that's id and item. How about if I have 7 fields, that's id_admin, name, email, address, phonenumber, username, and password, and the table name is admin. This the code that I found.
<?php
error_reporting(0);
include("db_config.php");
// array for JSON response
$response = array();
if( isset($_POST['id'] ) && isset($_POST['item']) ) {
$id=$_POST['id'];
$item=$_POST['item'];
$result = mysql_query("update myorder set item='$item' where id='$id' ") or die(mysql_error());
$row_count = mysql_affected_rows();
if($row_count>0){
$response["success"] = 1;
$response["message"] = "Updated Sucessfully.";
}
else{
$response["success"] = 0;
$response["message"] = "Failed To Update.";
}
// echoing JSON response
echo json_encode($response); } ?>
Change these lines :
if( isset($_POST['id'] ) && isset($_POST['item']) ) {
$id=$_POST['id'];
$item=$_POST['item'];
$result = mysql_query("update myorder set item='$item' where id='$id' ") or die(mysql_error());
with these :
if( isset($_POST['submit'] ) ) {
$id=htmlspecialchars($_POST['id']);
$item=htmlspecialchars($_POST['item']);
$name=htmlspecialchars($_POST['name']);
$email=htmlspecialchars($_POST['email']);
//and so on...
$result = mysql_query("update myorder set item=$item, name=$name, email= $email ... where id=$id ") or die(mysql_error());
Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
Instead, the MySQLi or PDO_MySQL extension should be used.
<?php
error_reporting(0);
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "username"; //username
$password = "password"; //password
$mysql_database = "dbname"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
// array for JSON response
$response = array();
if( isset($_POST['id'] ) && isset($_POST['item']) ) {
$id=$_POST['id'];
$item=$_POST['item'];
$stmt = $conn->prepare("update myorder set item=?,name=?,id_admin=?,email=?,address=?,phonenumber=? where id=? ");
$stmt->bind_param('ssissii',$item,$name,$id_admin,$email,$address,$phonenumber,$id);
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
//change it by respectively
$stmt->execute();
$row_count= $stmt->affected_rows;
if($row_count>0)
{
$response["success"] = 1;
$response["message"] = "Updated Sucessfully.";
}
else{
$response["success"] = 0;
$response["message"] = "Failed To Update.";
}
// echoing JSON response
echo json_encode($response);
$stmt->close();
$conn->close();
}
?>
Always use parameterized queries when user value needs to be inserted in query.
Example:
$statement = $conn->prepare("update admin set name=?, email=?, address=?, phonenumber=?, username=?, password=? WHERE id_admin=?");
$statement->bind_param('ssssssi', $name, $email, $address, $phonenumber, $username, $password, $id_admin);
$statement->execute();
<?
session_start();
if(($connection = mysql_connect("localhost", "root", "")) == false)
die ("Couldn't connect to database");
if(mysql_select_db("Social", $connection) == false)
die ("Couldn't select db");
if (isset($_POST['username']) && isset($_POST['pass']) && isset($_POST['login'])){
$sql = sprintf("SELECT * FROM users WHERE username LIKE '%s' AND password LIKE '%s'", $_POST['username'], $_POST['pass']);
$query = mysql_query($sql);
if (mysql_num_rows($query) == 0){
$error = "<br />Wrong Username or Password";}
else{
$_SESSION['user'] = $_POST['username'];
header("Location: home1.php");
}
}
if (isset($_POST['register'])){
$sql2 = sprintf("INSERT INTO Social.users (username, password) VALUES (%s, %s)", $_POST['newUser'], $_POST['newPass']);
$query2 = mysql_query($sql2);
if (!$query2){
print "Registration failed";
}
else{
print "Registration sucessfull";
}
}
?>
My program is not inserting any data into mySQL table. I know all the syntax is right, everything should work out fine. I double checked on the command that mySQL uses in order to enter data into the table. Why is this not working? My query2 should be successful, but idk why its not.
Please help.
Thanks
to prevent sql injections, try mysqli or pdo
here is mysqli prepared statements version. However if you are trying to create user management system, I wouldn't recommend you do it. There are so many scripts which provide more security, http://www.usercake.com is a good user management system.
session_start();
$db = new mysqli('localhost', 'root', 'password', 'database');
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (isset($_POST['username'] && $_POST['pass'] && $_POST['login']))
{
$user_name = ''; //define these here.
$pass = '';
$stmt = $db->prepare("select * from users where username = ? and password = ?");
echo $db->error;//this will echo the error.
$stmt->bind_param('ss', $user_name, $pass);
$stmt->execute();
$result = $stmt->get_result();//get rows
if($result->num_rows < 1) //check if result is less than 1
{
$error = "<br />Wrong Username or Password";}
else{
$_SESSION['user'] = $_POST['username'];
header("Location: home1.php");
}
}
if (isset($_POST['register'])){
$uname = $_POST['newUser'];
$pass = $_POST['newPass'];
if(empty($uname))
{
echo "Please enter your username.";
}
elseif(empty($pass))
{
echo "Please enter your password.";
}
else{
$stmt = $db->prepare("insert into Social.users (username, password) values (?,?)");
echo $db->error;//this will echo the error.
$stmt->bind_param('ss', $uname, $pass);
$stmt->execute();
echo "You have successfully registered.";
}
}
The variables in the INSERT must be the username and password
$sql2 = sprintf("INSERT INTO Social.users (username, password) VALUES (%s, %s)", $_POST['username'], $_POST['pass']);
Use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.
You basically have two options to achieve this:
Using PDO:
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute(array('name' => $name));
foreach ($stmt as $row) {
// do something with $row
}
Using mysqli:
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name =
?'); $stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result(); while ($row = $result->fetch_assoc()) {
// do something with $row }
Font: How can I prevent SQL injection in PHP?
Sorry I am new to php so please be patient with me. I am creating a user interface and when I register it says I have registered but it doesn't store the data into the database. can someone please help me!
<?PHP
$uname = "";
$pword = "";
$errorMessage = "";
$num_rows = 0;
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$uname = $_POST['username'];
$pword = $_POST['password'];
$uname = htmlspecialchars($uname);
$pword = htmlspecialchars($pword);
$uLength = strlen($uname);
$pLength = strlen($pword);
if ($uLength >= 10 && $uLength <= 20) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Username must be between 10 and 20 characters" . "<BR>";
}
if ($pLength >= 8 && $pLength <= 16) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Password must be between 8 and 16 characters" . "<BR>";
}
if ($errorMessage == "") {
$user_name = "root";
$pass_word = "";
$database = "user authentication";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$uname = quote_smart($uname, $db_handle);
$pword = quote_smart($pword, $db_handle);
$SQL = "SELECT * FROM login WHERE USERNAME = $uname";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "Username already taken";
}
else {
$SQL = "INSERT INTO login (L1, L2) VALUES ($uname, md5($pword))";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");
}
}
else {
$errorMessage = "Database Not Found";
}
}
}
?>
<html>
<head>
<title>Basic Login Script</title>
</head>
<body>
<FORM NAME ="form1" METHOD ="POST" ACTION ="signup.php">
Username: <INPUT TYPE = 'TEXT' Name ='username' value="<?PHP print $uname;?>" maxlength="20">
Password: <INPUT TYPE = 'TEXT' Name ='password' value="<?PHP print $pword;?>" maxlength="16">
<P>
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Register">
</FORM>
<P>
<?PHP print $errorMessage;?>
</body>
</html>
You might also want to rather make use of PDO then you don't have to to do the cleanup of the user input as PDO will take care of that for you. You might want to creat a file that hold all your connection details like this:
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'user authentication');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DSN', 'mysql:host='. DB_HOST . ';dbname=' . DB_NAME);
?>
You then might want to create a class to do the connection to your database like:
<?php
class database{
public function databaseConnect(){
/*Creates a new instance of the PDO called $db.
* NOTE: the use of DSN, DB_USER and so on. These variable live in the dbsettings file.
*/
$db = new PDO(DSN,DB_USER,DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}
}
?>
Then you might want to create a class to register your user like:
<?php
//Include the database class file to allow access to properties and methods within that class.
require_once 'class.database.php';
//echo 'I am database class file now included in the users class file. <br />';
//This method will be user to check if the user enter the correct username password pair.
class users{
public function checkValidUser($username){
$userExists = false;
try {
$db = database::databaseConnect();
$stmt = $db->prepare('SELECT uname FROM table WHERE uname=:username');
$stmt->bindParam(':uname', $username, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->rowCount() == 1){
$userExists = true;
}
$db = null;
} catch (PDOException $e) {
$userExists = false;
}
return $userExists;
}
public function addUser($firstname, $lastname, $username,$password){
$success = true;
//Connect to the database
try {
$db = database::databaseConnect();
//$db->databaseConnect();
$stmt = $db->prepare('INSERT INTO table (FirstName, LastName, Username, Password) VALUES (:firstname, :lastname, :username, :password)');
$stmt->bindParam(':firstname', $firstname, PDO::PARAM_STR);
$stmt->bindParam(':lastname', $lastname, PDO::PARAM_STR);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$success = $stmt->execute();
if ($success){
$success = true;
}
$db = null;
} catch (PDOException $e) {
//echo 'There was an error adding a new user. Please go back and try again. If this problem persits please contact the administrator.';
$success = false;
}
return $success;
}
?>
Hope that this helps.
enter link description here$SQL = "INSERT INTO login (L1, L2) VALUES ($uname, md5($pword))";
You're not inserting the values into proper fields, it appears. You're inserting the $uname into L1 and md5($pword) into L2 but in the select query above, you have a different field name for username and I presume the same for password.
$SQL = "SELECT * FROM login WHERE USERNAME = $uname";
Most likely, your insert query should be something like:
$SQL = "INSERT INTO login (USERNAME, PASSWORD) VALUES ('{$uname}', MD5('{$pword}'))";
I added single quotes around the username and password since presumably they are strings. Also, I added curly braces around the variables to segregate what is SQL from what is PHP.
One last thing, I would check into doing this with PDO as Willem suggested