PHP getting no response body - php

Username and password values are being passed into my login php file and returning as a jsonResponse string. However the jsonResponse string that is being returning is empty?
<?php
# this file will return true or false depending if passed in username and password matcha user on the system.
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$dbhost = "localhost";
$dbname = "example";
$dbuser = "example";
$dbpass = "example";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$data = array( $_POST["username"],$_POST["password"] );
$stmt = $conn->prepare("Select * FROM example where username=?, password=?");
if(mysql_num_rows($stmt)>0)
{
$row = mysql_fetch_array($stmt);
if($_POST["password"] == $row["password"])
{
echo "loggedIn";
}
else
{
echo "passwordNotValid"; alert
}
}
else
{
echo "usernameNotValid";
}
if(!$stmt)
{
print_r($dbh->errorInfo());
}
}
?>

You have a lot of issues...
Remove the alert from that line
echo "passwordNotValid"; alert
Close the quotes like shown
echo "usernameNotValid";
Remove a } brace from the last line..
Apart from these issues... The (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead,the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !

you are mixing mysql_* with PDO. Here is a complete example of PDO. you should use PDO like this.
$dbhost = "localhost";
$dbname = "example";
$dbuser = "example";
$dbpass = "example";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("Select * FROM example where username=?, password=?");
use your username and password varaibles in bind params
$stmt ->bindParam(':username', $username, PDO::PARAM_STR);
$stmt ->bindParam(':password', $password, PDO::PARAM_STR);
$stmt ->execute();
$result = $stmt ->fetch(PDO::FETCH_ASSOC);
and use $result in your page

Syntax error in line
echo "usernameNotValid;
your code is most likely never executed.

Related

unable to update SQL table with php program

I have installed XAMPP and ensured that all the servers are running. I'm completely new to PHP and SQL
I configured a local database called test and a table called sensor.
I have added a user called arduino with a password.
pls ignore the comments
<?php
// Prepare variables for database connection
$dbusername = "arduino";
$dbpassword = "xxx";
$server = "localhost";
// Connect to your database
$dbconnect = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'arduino', 'test');
// Prepare the SQL statement
$sql = "INSERT INTO test.sensor (value) VALUES ('".$_GET["value"]."')";
// Execute SQL statement
// mysql_query($sql);
?>
I want to use this set up to fetch data from arduino. Before connecting this set up to arduino, I wanted to ensure that this would be able to fetch data by passing http://localhost/write_data.php?value=100 to the browser. I was expecting that this would update the table with id, timestamp and value (of 100). It did not.
I had trouble with $dbconnect = mysql_pconnect($server, $dbusername, $dbpassword); and hence replaced that with $db = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'arduino', 'test');
I also had trouble with mysql_query($sql);. So I have commented it out for now.
How can I get this to work? Where can I find easy to follow documentation for MySql replacements?
Updated Code based on answers
<?php
$dbusername = "arduino";
$dbpassword = "test";
$server = "localhost";
$dbconnect = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'arduino', 'test');
$stmt = $dbconnect->prepare('insert into sensor(value) values(:val)');
$stmt->bindParam(':val', $_GET["value"], PDO::PARAM_INT);
$stmt->execute();
print "procedure returned $return_value\n";
?>
Brother checkout this example.. you have to bind get parameter in your query
Example:-
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM `$table` WHERE `$fieldname`=:id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
You are not executing the SQL statement in your code. Try executing the below implementation :
$db = new PDO('mysql:host=localhost;dbname=rfid_db;charset=utf8mb4', 'username', 'password');
//$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //optional
//$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //optional
$stmt = $db->prepare('insert into sensor(value) values(:val)');
$stmt->bindParam(':val', $_GET["value"], PDO::PARAM_INT);
$stmt->execute();
Also for detailed study on PDO try referencing the documentation here http://php.net/manual/en/pdo.prepared-statements.php

PDO Username validation if already exists

I have a problem with register form.My form works properly but whenever i try to insert username that already exists it doesn't shows any error.
here is my php register file:
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=dblogin", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST['submit'])) {
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_pass = $_POST['user_pass'];
$hash = password_hash($user_pass, PASSWORD_DEFAULT);
$stmt = $con->prepare("SELECT user_name FROM users WHERE user_name = :user_name");
if($stmt->rowCount() > 0){
echo "exists!";
}
else{
$insert = $conn->prepare("INSERT INTO users (user_name,user_email,user_pass) values(:user_name,:user_email,:user_pass)");
$insert->bindparam(':user_name',$user_name);
$insert->bindparam(':user_email',$user_email);
$insert->bindparam(':user_pass',$hash);
$insert->execute();
}
}
catch(PDOException $e)
{
echo "connection failed";
}
?>
Thanks for your support
You are not executing the select statement. You need to bind params and execute the select statement, try this after the select statemnt.
$stmt->bindparam(':user_name',$user_name);
$stmt->execute();
public function usernameCheck($username)
{
$sql = "SELECT * FROM $this->table where username = :username";
$query = $this->pdo->prepare($sql);
$query->bindValue(':username', $username);
$query->execute();
if ($query->rowCount() > 0) {
return true;
} else {
return false;
}
}
use this one in your project hope it will work... :)
missing } in if statement
if (isset($_POST['submit'])) {
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_pass = $_POST['user_pass'];
$hash = password_hash($user_pass, PASSWORD_DEFAULT);
$stmt = $con->prepare("SELECT user_name FROM users WHERE user_name = :user_name");
if($stmt->rowCount() > 0){
echo "exists!";
}
}else{
}
I notice 4 things (2 of which have been mentioned by others):
First and smallest is you have a spelling error ($con instead of $conn) - don't worry it happens to the best of us - in you first $stmt query which means your select-results becomes NULL instead of 0 - so you rowCount find that it is not over 0 and moves on without your error message
Second you forgot to bind and execute the parameters in your first $stmt query which gives the same result for your rowCount results
Third always clean your variables even when using prepared statements - at a bare minimum use
$conn->mysql_real_escape_string($variable);
and you can with advantage use
htmlspecialchars($variable);
And fourth since you are not doing anything with the database (other than looking) you could simplify your code by simply writing:
$stmt = $conn->query("SELECT user_name FROM users WHERE user_name = '$user_name' LIMIT 1")->fetch();
as I said - no need to bind or execute in the first query
and as a general rule - don't use rowCount - ever - if you have to know the number of results (and in 99% of cases you don't) use count(); but if you as here just want to know if anything at all was found instead use:
if ( $stmt ) {
echo "exists!";
} else {
// insert new user as you did
}
Edit:
Also - as a side note - there are a few things you should consider when you initially create your connection...
Ex:
// Set variables
$servername = "localhost";
$username = "***";
$password = "***";
$database = "***";
$charset = 'utf8'; // It is always a good idea to also set the character-set
// Always create the connection before you create the new PDO
$dsn = "mysql:host=$servername;dbname=$database;charset=$charset";
// Set default handlings as you create the new PDO instead of after
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // And add default fetch_mode
PDO::ATTR_EMULATE_PREPARES => false, // And ALWAYS set emulate_prepares to false
];
// And now you are ready to create your new PDO
$conn = new PDO($dsn, $username, $password, $opt);
Just a suggestion... happy trails

query error when access clearDB database using php on Heroku

I can access clearDB database well by using Mysql Workbench.
But when I query database by using php on Heroku, it always fail.
This is my code:
$url=parse_url(getenv("CLEARDB_DATABASE_URL"));
$dbhost = $url["host"];
$dbuser = $url["user"];
$dbpass = $url["pass"];
$dbname = substr($url["path"],1);
mysqli_connect($dbhost, $dbuser, $dbpass);
mysqli_select_db($dbname);
$sql = "SELECT * FROM `user_info` WHERE `user_account`='".$user_account."'";
$result = mysqli_query($sql) or die('MySQL query error');
user_account is a table in the database, $user_account is a input variable from client user
help me
thanks
You're not passing the link to mysqli_query(). You need to either do that, or use the object oriented style and call query() on the connection.
You also have a possible SQL injection there, because $user_account could contain "foo' OR 1 OR '", returning all rows (and that's just a simple, not very evil case), so you should escape that using mysqli_real_escape_string(), or even better, use prepared statements.
Finally, instead of or die(), how about extracting error information properly, or even configuring mysqli to throw exceptions?
<?php
$url = parse_url(getenv("CLEARDB_DATABASE_URL"));
$server = $url["host"];
$username = $url["user"];
$password = $url["pass"];
$db = substr($url["path"], 1);
$conn = new mysqli($server, $username, $password, $db);
$sql = "SELECT * FROM `user_info` WHERE `user_account`='".$conn->real_escape_string($user_account)."'";
if($result = $conn->query($sql)) {
foreach($result as $row) {
// ...
}
} else {
throw new Exception($conn->error);
}

Having issues retrieving data from database

I am trying to figure out how to connect and fetch data from a database using PDO, I have been using mysqli but figure PDO is the way to go now a days.
Here is my code, looks like I can connect but I am not able to grab any data.
<?php
$host = "localhost";
$user = "";
$pw = "";
$dbName = "test";
$numberID = 1;
$pdo = new PDO("mysql:host=$host", $user, $pw);
if ($pdo){
echo "Connected";
$smt=$pdo->prepare("SELECT from sample WHERE id=:ID");
$smt->bindParam(":ID", $numberID);
if($smt->execute()){
$rows=$smt->fetchAll();
print_r($rows);
}
}
There is syntax error in your query. You are missing * or specific column names which you want to select
$smt=$pdo->prepare("SELECT * from sample WHERE id=:ID");
and you have not used database name in your connection. Try to use this
$dbo = new PDO('mysql:host='.$host.';dbname='.$dbName, $user, $pw);
You must specify the column names or * after the SELECT and use the database while creating the PDO object. The working code is provided
<?php
$host = "localhost";
$user = "";
$pw = "";
$dbName = "test";
$numberID = 1;
$pdo = new PDO('mysql:host='.$host.';dbname='.$dbName, $user, $pw);
if ($pdo){
echo "Connected";
$smt=$pdo->prepare("SELECT * FROM sample WHERE id=:ID");
$smt->bindParam(":ID", $numberID);
if($smt->execute()){
$rows=$smt->fetchAll();
print_r($rows);
}
}
?>
This is really silly, but have you confirmed PDO is installed? Check the error logs to see if it's barking about a missing pdo driver.

mysqli does not execute Select statement

I have the code bellow. When I use this code without the WHERE clause, all the users from the table are displayed, as expected. But when the WHERE clause is used, nothing is displayed.
What could be the cause and how can I fix it?
Thank you!
function requestUser($user) {
$DBHost = "localhost";
$DBUser = "dbUser";
$DBPass = "dbPass";
$DBName = "dbName";
$db = new mysqli($DBHost, $DBUser, $DBPass, $DBName);
if ($db -> connect_errno > 0) {
$lbOK = false;
}
else {
$lbOK = $db -> set_charset('utf8');
}
if ($lbOK) {
$id = NULL;
$user_name = NULL;
$user = htmlentities($user, ENT_QUOTES);
$lcSQL = "SELECT `user_name` FROM `users` WHERE user_name=?";
$stmt = $db -> prepare($lcSQL);
$ok = $stmt -> bind_param('s', $user);
$ok = $stmt -> execute();
$ok = $stmt -> bind_result($user_name);
while ($row = $stmt -> fetch()){
echo $user_name;
}
$stmt->close();
}
}
There are many major faults with your code, some of them can be responsible for the problem, and some not. But nevertheless, they all have to be corrected
Never connect co database inside of an application function. Connect somewhere in the bootstrap file, once, and use that single connection throughout all the application.
Do not use htmlentities with whatever database interactions. It may easily spoil the data
Always check for the the errors
Do not use mysqli, it is unusable. Use PDO instead.
$dsn = "mysql:host=DBHost;dbname=DBName;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,$DBUser, $DBPass, $opt);
function requestUser($user) {
global $db;
$sql = "SELECT `user_name` FROM `users` WHERE user_name=?";
$stmt = $db->prepare($sql);
$stmt->execute(array($user));
return $stmt->fetchColumn();
}
echo requestUser($user);
if it still doesn't work, verify it this way
$sql = "SELECT `user_name` FROM `users` WHERE user_name='$user'";
var_dump($sql);
and then try to run in console/phpmyadmin to find out what's wrong with your data/value

Categories