SQL INSERT TROUBLE - php

I'm sitting infront of this code for 2 hours i cant figure out whats wrong :(
I've been trying to have a html form which calls the php function to insert the information from the form into the database but for some reason does not work :/
here is my form code :
<?php include 'connection.php'; ?>
<html>
<body>
<form action="user_create.php" method="POST">
username: <input type="text" name="username"/>
password: <input type="text" name="password"/>
email: <input type="text" name="email"/>
<input type="submit" name='submit' value="user_create"/>
</form>
</body>
</html>
database connection
<?php
//Connecting databases
$localhost = "";
$dbuser = "";
$dbpass = "m";
$dbname = "";
$connect = mysql_connect($localhost, $dbuser, $dbpass);
mysql_select_db("$dbname", $connect);
?>
my php function
<?php include 'connection.php';?>
<?php
if (isset($_POST['submit']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$query = mysql_query("INSERT INTO users( username,password,email,type)
VALUES ('$username', '$password', '$email','1')");
mysql_query($query);
echo '<script type="text/javascript">alert("You have been registered");</script>';
}
else
{
echo '<script type="text/javascript">alert("jo");</script>';
}
?>

You should use PHP-PDO in order to avoid from SQL Injection attacks also it will fix insert trouble too.
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=animals", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** INSERT data ***/
$sql = "INSERT INTO users(username,
password,
email,
type) VALUES (
:username,
:password,
:email,
:type)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $_POST['username'], PDO::PARAM_STR);
$stmt->bindParam(':password', $_POST['password'], PDO::PARAM_STR);
$stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
$stmt->bindParam(':type', $_POST['type'], PDO::PARAM_INT);
$stmt->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>

Are you connecting properly?
$dbuser = "";
Maybe must be "root" or other user?
Check this part :
//Connecting databases
$localhost = "";
$dbuser = "";
$dbpass = "m";
$dbname = "";

Related

PHP using Xampp : POST is not allowed error

when it try to submit the form content to the database i get the following error :
{"code":"MethodNotAllowedError","message":"POST is not allowed"}
I am using Dreamweaver cc 2017 and xampp v3.2.2 to run Apache and Mysql on windows 10.
html form :
<form action="register.php" id="form1" name="form1" method="post">
and register.php content is :
<?php
$hostname_conn = "localhost";
$database_conn = "hotels";
$username_conn = "root";
$password_conn = "";
$conn = mysqli_connect($hostname_conn, $username_conn, $password_conn) or trigger_error(mysqli_error(),E_USER_ERROR);
$db=mysqli_select_db($conn,$database_conn);
$q1= "insert into users(username,email,password,number)values('$_POST[textfield]','$_POST[email]','$_POST[password]','$_POST[number]')";
$q2=mysqli_query($conn,$q1);
if(mysqli_query($conn,$q1))
{
$msg = 'User information saved successfully.';
}
else
{
$msg = 'Error: We encountered an error while inserting the new record.';
}
echo $msg;
mysqli_close($conn);
?>
</body>
</html>
using PDO:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "hotels";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$stmt = $conn->prepare("INSERT INTO users (username, email, password, number)
VALUES (:username, :email, :password, :number)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);
$stmt->bindParam(':number', $number);
$username = $_POST['textfield'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$stmt->execute();
The problem is for syntax. Anyway you should to use good practices. Check this post How can I prevent SQL injection in PHP?
$username = $_POST["textfield"]; //unsafe
$username = mysql_real_escape_string($username); //safe
$email = mysql_real_escape_string($_POST["email"]);
$password = mysql_real_escape_string($_POST["password"]);
$number = mysql_real_escape_string($_POST["number"]);
$db=mysqli_select_db($conn,$database_conn);
$q1= "insert into users(username,email,password,number)values('".$username ."','".$email."','".$password."','".$number."')";
$q2=mysqli_query($conn,$q1);

PHP Login Can't login to index.php

Why can't I login to my index.php page its just getting stucked in my login.php page. Please help. Thanks.
<?php
session_start();
$conn = new PDO('mysql:host = localhost;dbname=userdb','root','');
if (isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
$query = $conn->prepare("SELECT COUNT('userID') FROM 'tbl_account' WHERE 'username' = '$username' AND 'password' = '$password' ");
$query->execute();
$count = $query->fetchColoumn();
if ($count == 1){
$_SESSION['username'] = $username;
header("location : index.php");
exit();
}else{
$error = "Your Login Name or Password is invalid";
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action = "?" method = "POST">
<input type = "text" name="username"><br> //username
<input type = "password" name = "password"><br> //password
<input type = "submit" name = "submit" value = "Login"> /button
</form>
</body>
</html>
where could probably my mistake? on my PDO? on my prepared statement? TIA
1)form action missing.
2)isset($_POST['login']) wrong name checking in if condition.
3)prepared statement have lots of issue.
try something like this
<?php
session_start();
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "root"; //username
$password = ""; //password
$mysql_database = "userdb"; //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");
if(isset($_POST['submit']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $conn->prepare("SELECT * FROM tbl_account WHERE username =? AND password =? ");
$stmt->bind_param('ss',$username,$password);
$stmt->execute();
$get_result= $stmt->get_result();
$row_count= $get_result->num_rows;
$stmt->close();
$conn->close();
if ($row_count>0){
$_SESSION['username'] = $username;
header("location:index.php");
exit();
}else{
$error = "Your Login Name or Password is invalid";
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action = "login.php" method = "POST">
<input type = "text" name="username"><br> //username
<input type = "password" name = "password"><br> //password
<input type = "submit" name = "submit" value = "Login"> /button
</form>
</body>
</html>
its syntax to use an exit(); after any header('location [...]') calls, you're missing this in your code which could be the reason why your page does nothing.
Also, I'd really like to touch up on some security notes: what the hell is that?
PDO has pre-written functions to allow you the full dynamics of a connection with security, they are there to be used; as it stands, your SQL statement is a security risk as you're directly inserting untrusted data into a statement without stripping it of injections.
Heres an example you could use to secure this:
class DB extends PDO
{
function __construct(
$dsn = 'mysql:host=localhost;dbname=kida',
$username = 'root',
$password = 'root'
) {
try {
parent::__construct($dsn, $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
parent::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function query($statement, array $parameters = array())
{
$stmp = parent::Prepare($statement);
$i = 1;
foreach($parameters as $parameter) {
$stmp->bindParam($i, $parameter);
$i++;
}
$stmp->execute();
return $stmp->FetchAll();
}
}
$Con = new DB();
$username = "example";
$row = $Con->query("SELECT * FROM table WHERE username = ?", [$username]);
You have wrongly used prepared statement.
You should write,
$query = $conn->prepare("SELECT COUNT('userID') FROM REGISTRY WHERE name = ? AND password' = ?");
$query->bindParam(':name', $username);
$query->bindParam(':password', $password);
$query->execute();
$result_rows = $query->fetchColumn(); // get result
Check this link for more detail.
Suggestion:- also add exit; after header tag to stop execution of afterward code.
try and change this code to
"SELECT COUNT('userID') FROM 'tbl_account' WHERE 'username' = '$username' AND 'password' = '$password' ");
put semicolon inside the quotes and on the outside as well
"SELECT userID FROM tab1_account WHERE username='$username' AND password='$password';";

Simple PHP Form SQL Insert

I need some help with a very basic issue that I cannot resolve.
A bit of background: I have a PHP form and I would like the information inside the table to insert into my SQL table. For some reason, when I hit submit nothing inserts into the table and I have no idea why. Please help!
This is the PHP Code:
<?php
try
{
$db = new PDO('mysql:host=' . $Database_Host . ';dbname=' . $Database_Database, $Database_Username, $Database_Password);
}catch(PDOException $e){
die("Failed to connect to database! Please check the database settings.");
}
if(isset($_POST['submit'])) {
$result = mysql_query('INSERT INTO requests (song,name,dedicated,time) VALUES ("' . mysql_real_escape_string($_POST['name']) . '", "' . mysql_real_escape_string($_POST['dedicated']) . '", "' . mysql_real_escape_string($_POST['song']) . '", UNIX_TIMESTAMP())');
if ($result) {
echo 'Song requested successfully!<br />';
}
}
?>
This is the HTML Code:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">Request:<br /><br />
Song:<br />
<input type="text" name="song"><br />
Name:<br />
<input type="text" name="name"><br />
Comments:<br />
<input type="text" name="dedicated"><br />
<input type="submit" name="submit" value="Submit" >
</form>
What this is meant to do is insert the request form into the SQL table, however nothing is happening. Any help is appreciated.
Kind Regards,
Edward
You can't mix mysql and PDO like that. You should use a PDO prepared query for the insert.
Also, the order of the values in the VALUES list have to match the column list -- you had the values in the order name, dedicated, song, time instead of song, name, dedicated, time.
<?php
if (isset($_POST['submit'])) {
try
{
$db = new PDO('mysql:host=' . $Database_Host . ';dbname=' . $Database_Database, $Database_Username, $Database_Password);
}catch(PDOException $e){
die("Failed to connect to database! Please check the database settings.");
}
$stmt = $db->prepare('INSERT INTO requests (song,name,dedicated,time) VALUES (:song, :name, :dedicated, UNIX_TIMESTAMP())');
$result = $stmt->execute(array(':song' => $_POST['song'], ':name' => $_POST['name'], ':dedicated' => $_POST['dedicated']));
if ($stmt->rowCount == 1) {
echo "Song requested successfully";
} else {
echo "Song could not be requested";
}
}
You should study about pdo and mysql and then use them ...
just see this simple example with mysql :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary#example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie#example.com";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>
and this one with pdo :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
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);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
// insert another row
$firstname = "Mary";
$lastname = "Moe";
$email = "mary#example.com";
$stmt->execute();
// insert another row
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie#example.com";
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
I prefer using pdo
Source : http://www.w3schools.com/php/php_mysql_prepared_statements.asp
NOTE : use prepared statements to avoid sql injection .

No Match found using query in MySql database using PHP

I have a MySql database with the following columns:
and a HTML form like so:
<form method="post" action="validate.php">
<label for="users_email">Email:</label>
<input type="text" id="users_email" name="users_email">
<label for="users_pass">Password:</label>
<input type="password" id="users_pass" name="users_pass">
<input type="submit" value="Submit"/>
</form>
Here's snippet of code within the validate.php page:
$email = $_POST['users_email'];
$pass = $_POST['users_pass'];
$dbhost = '************';
$dbuser = '************';
$dbpass = '************';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn)
{
die('Could not connect: '. mysql_error());
}
mysql_select_db("SafeDropbox", $conn);
$result = mysql_query("SELECT Email, UserPassword FROM tblnewusers WHERE Email = $email");
$row = mysql_fetch_array($result);
if($row['Email'] == $email && $row['UserPassword'] == $pass) {
echo "Valid";
}
elseif($row.count() == 0) {
echo "No Match";
}
else {
echo "Invalid";
//header("Location: http://www.google.ie");
//exit();
}
The problem is I'm getting no match even though the values of $email and $pass are definitely within my database. What am I doing wrong?
The problem is in:
$result = mysql_query("SELECT Email, UserPassword FROM tblnewusers WHERE Email = $email");
$email should be escaped and surrounded by quotes. The safest solution is to use a prepared statement:
$result = mysql_query("SELECT Email, UserPassword FROM tblnewusers WHERE Email = ?");
$con=new mysqli($dbhost, $dbuser, $dbpass, $yourDatabase);
$stmt = $mysqli->prepare($result);
$stmt->bind("s",$email);
$result=$stmt->execute();
For more details see http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

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