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

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']) {

Related

My PHP login system still Logging in even if the password or username is incorrect

Still loggin in even if the username and password is incorrect and also logins even if the value is null
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "login";
$conn = mysqli_connect($hostname, $username, $password, $dbname);
if (!$conn) {
die ("unable to connect");
}
if ($_POST) {
$uname = $_POST ["username"];
$pass = $_POST ["password"];
$sql = "SELECT * FROM users WHERE username = '$uname' AND password = '$pass' LIMIT 1 ";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1){
include("graph.php");
} else {
echo "Incorrect";
}
}
?>
First of all and very important it that you are open to SQL Injection attack, so you should use prepared statements, here is how should use your code, but instead of echo "Incorrect"; you should render different answer for each case:
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "login";
$conn = mysqli_connect($hostname, $username, $password, $dbname);
if (!$conn) {
die ("unable to connect");
}
if (isset($_POST["username"]) && isset($_POST["password"])) { // Check if you have posted data via POST
$uname = $_POST["username"];
$pass = $_POST["password"];
$sql = "SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1 ";
if($stmt = $conn->prepare($sql)) { // Check for MySQL errors
$stmt->bind_param('ss', $uname, $pass);
if ($stmt->execute()) {
$stmt->close();
include("graph.php");
} else { // There is a problem with your SELECT // bind params
echo "Incorrect";
}
} else { // You should handle mysql errors here
echo "Incorrect";
}
} else { // You don't have POST data
echo "Incorrect";
}
?>
Prepared statements
Like #Kuya notice you have and many other problems, there is a lot of tutorials in Google about implementation of login system.
You must check the post request with isset() in php like this :
<?php
if (isset($_POST["username"] && isset($_POST["password"]))) {
//..... Your code here
}else {
echo "Incorrect password or username";
}
?>

Cant connect to MySQL, wrong code?

I have tried to connect to my db, but nothing works...
This is the code that I have created:
$name ='testdb';
$user = 'root';
$password = '';
$host = 'localhost';
$link = new mysqli($name, $user, $password, $host);
$name = $_POST['name'];
$message = $_POST['message'];
$mail = $_POST ['mail'];
$name = $link->real_escape_string($_POST['name']);
$message = $link->real_escape_string($_POST['message']);
$mail = $link->real_escape_string($_POST['mail']);
$sql = "INSERT INTO test (Name, Message, Mail) VALUES ('$name','$message', '$mail')";
$result = $link->query($sql);
I have allready double-checked all the spellings.
Can anyone give me some tips? I may have gone blind.
Seems you did not initialize mysqli connection properly
error_reporting(E_ALL);//display all errors
$name ='testdb';
$user = 'root';
$password = '';
$host = 'localhost';
$link = new mysqli($host, $user, $password, $name);
Use prepared statements(Prevents SQL injection)
$sql = "INSERT INTO test (Name, Message, Mail) VALUES (?,?,?)";//placeholders (3placeholders for 3values)
$statement = $link->prepare($sql);//prepare query. returns true/false
$statement->bind_param('sss',$name, $message, $mail);//you dont need to escape anymore
$statement->execute(); //execute safely
The first parameter of mysqli is the hostname, you swapped hostname and databasename Connect to MySQL
$link = new mysqli($host, $user, $password, $name);
You can also use prepared statement, to prevent SQL injections
A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency.
$sql = "INSERT INTO test (Name, Message, Mail) VALUES (?,? ?)";
$stmt = $link->prepare($sql);
$stmt->bind_param("sss",$name, $message, $mail);
$result = $stmt->execute();
if ($result) {
// query was successful
}else {
// query failure
}
Please use this below code it will help you
$name ='testdb';
$user = 'root';
$password = '';
$host = 'localhost';
$link = new mysqli($host,$user,$password,$name);
// Check connection
if ($link->connect_error) {
die("Connection failed: " . $link->connect_error);
}
$name = $_POST['name'];
$message = $_POST['message'];
$mail = $_POST ['mail'];
$name = $link->real_escape_string($_POST['name']);
$message = $link->real_escape_string($_POST['message']);
$mail = $link->real_escape_string($_POST['mail']);
$sql = "INSERT INTO test (Name, Message, Mail) VALUES ('$name','$message', '$mail')";
if ($link->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $link->error;
}
$link->close();
To learn basic things in PHP and MYSQL refer this link
https://www.w3schools.com/php/

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
}
}

Trouble connecting data to MySQL

I can't seem to find out why my PHP code won't allow me to store the info in MySQL when I click the submit button. Can someone tell me whats wrong with the code below?
I want to get it to the point where users submit their registration form and their info can get moved over to a MySQL database. Then, I want the users to be taken to my index.html file.
Any help is appreciated.
Thanks
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$mysql_database = "21st";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Could not connect database");
mysqli_select_db($conn, $mysql_database) or die("Could not select database");
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
if ($password == $password2) {
$sql = "INSERT INTO members (username, email, password) VALUES ('$userrname','$email','$password')";
} else {
echo "Your passwords must match";
}
?>
Try this using mysqli_query to actually run the query. When you set $sql all that did was set a variable named $sql to the query. Also note you set the variable $userrname in the query when it should be $username as set from the $_POST directly above. My adjusted version of your code below:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$mysql_database = "21st";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Could not connect database");
mysqli_select_db($conn, $mysql_database) or die("Could not select database");
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
if ($password === $password2) {
// Set the query.
$sql = "INSERT INTO members (username, email, password)"
. " VALUES (?, ?, ?)"
;
// Bind the values to the query.
mysqli_stmt_bind_param($sql, 'sss', $username, $email, $password);
// Run the query.
mysqli_query($conn, $sql);
// Free the result set.
mysqli_free_result($sql);
// Close the connection.
mysqli_close($conn);
}
else {
echo "Your passwords must match";
}

PHP PDO connection failure [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 3 years ago.
Hey, so I am new with PDO, and I cannot figure out why my data will not insert into my tables. Much appreciated!
<?php
include("class.php");
$dbhost = "localhost";
$dbname = "db";
$dbuser = "user";
$dbpass = "pass";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$username = $_POST['username'];
$password = $_POST['password'];
$email = strtolower($_POST['email']);
$firstName = ucwords(strtolower($_POST['firstName']));
$lastName = ucwords(strtolower($_POST['lastName']));
$date = date("Y-m-d");
$hash = Secure::Encrypt($username, $password);
$sql = "INSERT INTO users (username,password,email,firstName,lastName,createDate) VALUES (:username,:password,:email,:firstName,:lastName,:date)";
$q = $conn->prepare($sql);
$q->execute(array(
':username'=>$username,
':password'=>$hash,
':email'=>$email,
':firstName'=>$firstName,
':lastName'=>$lastName,
':date'=>$date));
?>
If all of your table's field names match, I have found that PDO will sometimes fail if one of your array variables are empty.
to find out if any errors are being thrown, add the following after your new PDO declaration (PDO error reporting is silent by default):
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Then add try/catch around each PDO activity as follows:
try {
..Code Here...
}catch (PDOException $err) {
echo $err->getMessage();
}
Final Code:
<?php
include("class.php");
$dbhost = "localhost";
$dbname = "db";
$dbuser = "user";
$dbpass = "pass";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$username = $_POST['username'];
$password = $_POST['password'];
$email = strtolower($_POST['email']);
$firstName = ucwords(strtolower($_POST['firstName']));
$lastName = ucwords(strtolower($_POST['lastName']));
$date = date("Y-m-d");
$hash = Secure::Encrypt($username, $password);
$sql = "INSERT INTO users (username,password,email,firstName,lastName,createDate) VALUES (:username,:password,:email,:firstName,:lastName,:date)";
try {
$q = $conn->prepare($sql);
}catch (PDOException $err) {
echo 'Prepare Failed: '.$err->getMessage();
}
try {
$q->execute(array(
':username'=>$username,
':password'=>$hash,
':email'=>$email,
':firstName'=>$firstName,
':lastName'=>$lastName,
':date'=>$date));
}catch (PDOException $err) {
echo 'Execute Failed: '.$err->getMessage();
}
?>
Then please update with any errors you receive :)

Categories