PHP is not passing proper data to MYSQL - php

I am unable to pass proper data to MySQL I have no idea what is wrong done by me please help me out my code is as follow:
$con = mysqli_connect('localhost', 'root', '', 'database');
if($con) {
echo "we are connected";
} else {
die("connection failed");
}
if(isset($_POST['submit'])) {
// echo "Yeah it works";
$user = $_POST['username'];
$pass = $_POST['password'];
$query = "INSERT INTO users(username, password) VALUES ('$user', '$pass')";
$result = mysqli_query($con, $query);
if(!$result) {
die("Query failed");
}
}
When I run this code I'm getting 0 for username and 0 for password. whatever I type for username and password I get 0 in database.

Try this code, which also removes SQL injections.
$con = mysqli_connect('localhost', 'root', '', 'database');
if(! $con )
die('Unable to connect');
foreach(array('submit', 'username', 'password') as $arg)
if(! isset($_POST[$arg]) )
die('Missing argument(s)');
unset($arg);
http_response_code(200);
$username = $con->real_escape_string($_POST['username']);
$password = $con->real_escape_string($_POST['password']);
$query = "INSERT INTO users (username, password) VALUES ('{$username}', '{$password}')";
if(! mysqli_query($con, $query))
http_response_code(400);
If this code doesn't work, make sure that username and password from your table are varchar's not int's. (Because your script inserts a 0 value)

Related

Mysql & Php Database connection error

When ever I use php to connect to my database I get a sudden error saying "database connection failed" is there anyway to fix this its for a login and register screen. Thanks to anyone who help...
<?php
$connection = mysqli_connect('localhost', 'root','','test');
if (!$connection){
die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'test');
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
<?php
//
require('database.php');
$connection = mysqli_connect('localhost', 'root','','test');
// If the values are posted, insert them into the database.
if (isset($_POST['Register'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO `user` (username, email, password) VALUES ('$username', '$email', '$password')";
//echo $query;
$result=mysqli_query($connection,$query);
if($result){
$smsg = "User Created Successfully.";
}else{
$fmsg ="User Registration Failed";
}
}
?>
Connection to a database with php requires 4 parameters (host, data base user, password, data base name, passwd), it's better nowadays to use db object instead of procedural "old" behaviour:
function connection(){
try{
//host, user, passwd, DB name)
$mysqli = new mysqli("localhost", $dbUser, $passwd, $dbName);
if (!$mysqli->set_charset("utf8")) $msg = "error charset mySQLi"; else $msg = "Set UTF-8 ok";
return $mysqli;
}
catch (Exception $mysqlin){
echo "Error stablishing connection with database ".$mysqlin->getMessage();
}
}
then you can connect easily as follows:
$sql = "SELECT * FROM users;";
if(!$result = connection()->query($sql)) echo "db query error"; else "query ok";
$rs = mysqli_fetch_assoc($result);
//do whatever and, to get next line of results:
if($rs!=''){
$rs = mysqli_fetch_assoc($result);
}
So you get a row of the results on $rs[] array.
EDIT: You'll need to apply security, this is a simple connection without regarding on it. Check mysqli bind params on php official webpage for it:
http://php.net/manual/en/mysqli-stmt.bind-param.php
Hope it helps

mysqli insert, what is wrong?

the data is not inserting. i think there is something wrong in
$sql = "INSERT INTO `users` (`Username`, `Password`, `FirstName`, `LastName`, `Email`, `ContactNumber`)
VALUES ('".$_POST["Username"]."','".$_POST["Password"]."','".$_POST["FirstName"]."','".$_POST["LastName"]."','".$_POST["Email"]."','".$_POST["ContactNumber"]."')";
When i try to change the statement in "else" with echo "successs"; its working.
please someone can tell me what is wrong.
<?php
error_reporting(E_ALL & ~E_NOTICE);
if(isset($_POST["Register"]))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbuseraccounts";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user = $_POST['Username'];
$pass = $_POST['Password'];
$query = mysqli_query($conn, "SELECT * FROM users WHERE Username= '".$user."'");
if(mysqli_num_rows($query) > 0)
{
echo "email already exists";
}
else
{
$sql = "INSERT INTO users (Username, Password, FirstName, LastName, Email, ContactNumber)
VALUES ('".$_POST["Username"]."','".$_POST["Password"]."','".$_POST["FirstName"]."','".$_POST["LastName"]."','".$_POST["Email"]."','".$_POST["ContactNumber"]."')";
}
$conn->close();
}
?>
Your data is not inserting because you haven't even executed your query.
if (mysqli_num_rows($query) > 0) {
echo "Username already exists";
} else {
$sql = "INSERT INTO users (Username, Password, FirstName, LastName, Email, ContactNumber) VALUES ('".$_POST["Username"]."','".$_POST["Password"]."','".$_POST["FirstName"]."','".$_POST["LastName"]."','".$_POST["Email"]."','".$_POST["ContactNumber"]."')";
/* Run your query and check for errors */
$query = mysqli_query($conn, $sql) or die(mysqli_error($conn));
}
Please Execute query using
mysqli_query($conn, your query);

Cant update data in table

hi im creating a login page where it would insert data into a php table but it does not seem to insert data into the table i have 2 tables in 1 database
hrms
<?php
$servername = "localhost";
$user = "root";
$dbpassword="";
$dbname = "hrms";
$username=$_POST['username'];
$passphrase=$_POST['passphrase'];
$conn = new mysqli($servername, $user, $dbpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM user WHERE username='$username' AND passphrase='$passphrase'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$sql = "INSERT INTO access (user, status)
VALUES ('John', 'locked')";
header("location: main.php");
} else {
header("location: index.php");
}
$conn->close();
?>
You forgot to execute the query, do like below:
$sql = "INSERT INTO access (user, status) VALUES ('John', 'locked')";
$conn->query($sql);

Insert into mysql database through php

I try to insert some information about user but it gives error no database selected (im using phpmyadmin and xampp btw)
code:
<?php
$username = $_POST['username'];
$name = $_POST['name'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
if($password == $cpassword)
{
mysql_escape_string($username);
mysql_escape_string($name);
mysql_escape_string($password);
mysql_escape_string($cpassword);
$md5pass = md5($password);
mysql_select_db("users");
mysql_query("INSERT INTO users (id, username, name, password) VALUES (DEFAULT, '$username', '$name', '$md5pass'") or die(mysql_error());
}
else
{
die("Passwords don't match");
}
?>
You haven't established connection with your mysql database.
Use following code to make connection with server.
$link = mysql_connect('your servers address', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
else
{
//rest of your code
}

Specifying parameters for a PHP sql query

I want to specify a raw username/password into an SQL query with PHP:
function doRegister($username, $password) {
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME) or die('error');
$query = "SELECT username FROM users WHERE username = $username";
$result = $db->query($query);
if (mysqli_num_rows($result) == 1) {
$msg = 'Username already taken';
} else {
$register = "INSERT INTO users(username, password)" .
"VALUES($username, SHA($password))";
//error happens here
$db->query($register) or die('error registering your account');
$msg = "Register successful";
}
$db->close();
echo $msg;
}
I am getting an error at $db->query($register). What am I doing wrong?
You have not surrounded your $username or $password in quotes, so when passing an integer it works correctly but won't accept a string:
$query = "SELECT username FROM users WHERE username = '$username'";
//----------------------------------------------------^^^^^^^^^^^^
$register = "INSERT INTO users(username, password)" .
"VALUES('$username', SHA('$password'))";
//-------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Please be certain that you have properly escaped these values with mysql_real_escape_string().
These columns should really not be type TEXT. They ought to be VARCHAR(). Perhaps your VARCHAR() attempt failed because you were missing the length parameter, as in VARCHAR(32) for max 32 characters.
Try this:
function doRegister($username, $password) {
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME) or die('error');
$query = "SELECT username FROM users WHERE username = '$username'";
$result = $db->query($query);
if (mysqli_num_rows($result) == 1) {
$msg = 'Username already taken';
} else {
$register = "INSERT INTO users(username, password)" .
"VALUES('$username', SHA('$password'))";
$db->query($register) or die('error registering your account');
$msg = "Register successful";
}
$db->close();
echo $msg;
}

Categories