php PDO doesn't print out database values - php

I want to make a login page using html and php.
This is a method of inputting ID and password in html and passing the value to login.php in POST format.
here is my php code.
...
<body>
<?php
try {
$db = new PDO("mysql:dbname=user;host=localhost","root","");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$id = $_POST[$id];
$pw = $_POST[$password];
$check = "SELECT password FROM user WHERE id = '$id'";
$rows = $db->query($check);
foreach ($rows as $row) {
print($row);
}
}
catch (PDOException $ex) {
?>
<p>Sorry, a database error occurred. Please try again later.</p>
<p>(Error details: <?= $ex->getMessage() ?>)</p>
<?php
}
?>
So I created a database for testing andI wrote the above code to check if the values ​​are imported correctly in the php codebut no value is printed.
I checked there is a value in mysql's database.
How can I fix this?

$pw = $_POST[$password]; need to be like $pw = $_POST['html_form_field_name']; apparently you are using variable instead of actual static name of the form field.

Related

I can't send data from input fields to my MySQL database

I have a little problem. I have a register form. It works almost perfectly, I can check the value of the input fields, I can check weather do we have the same username in the db, but if everything is OK I cannot send the datas to my db. I use it as administrator/root, so I have the privileges. What is the problem? Please, help!
<?php
// declaring variables from input fields
$email = $_POST['email'];
$username=$_POST['username'];
$password=$_POST['password'];
$password2=$_POST['password2'];
function registration ($username, $email, $password) {
//new user registering
//return true or errormessage
//connecting to database, YEAH IT WORKS!
$connection = connecting_to_db();
//checking unique of username and IT WORKS!
$result = $connection->query("SELECT * FROM user WHERE username='".$username."'");
if (!$result) {
throw new Exception ('We couldnt query. Sorry.');
}
if ($result->num_rows>0) {
throw new Exception ('We have already this username! Choose something else!');
}
// if it is OK send it to the DB AND THIS IS NOT WORKING :-(
$result = $connection->query("INSERT INTO user VALUES'".$username."', shal('".$password."'), '".$email."')");
// I get alwasy this way and get this message.
if (!$result) {
throw new Exception ('We couldnt save your datas in our database. Try it later!');
}
return true;
}
?>
it looks like you have shal(letter L) instead of sha1(# one) in your insert query. print out your result from the query and you should see your issue.
Connect the database and the table then get the data
$servername = "localhost";
$username = "root";
$password = "";

PDO, $_GET, and SELECTing from MySQL Database

So I'm working on a PHP Pastebin-esque project on my freetime to learn PHP and server management, and I've run into a LOT of issues, and I haven't been able to solve them. I decided to restart from sratch on my own with the information I've gathered so far, and threw this code together.
<?php
require 'connection.php';
$getid = $_GET["id"];
$sql = 'SELECT paste FROM pasteinfo WHERE id=:id';
$stmt = $con->prepare($sql);
$stmt->bind_param(':id', trim($_GET["id"], PDO::PARAM_INT));
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['paste'];
}
?>
What I'm trying to achieve with this code is a system where a user can type the id of whatever paste they're interested in viewing in the url and have it display the pasteinfo row, which is the row that holds the paste itself. The format they should have is viewpaste.php?id=(user input).
How can I fix this code? I would also greatly appreciate if you explain whatever code you might end up putting in the comments so I can learn from it. Thanks!
Try this;
connection.php
try{
$db = new PDO('mysql:host=localhost;dbname=database_name;charset=utf8mb4', 'database_username', 'database_password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $ex){
echo $ex->getMessage();return false;
}
function retrieve($query,$input) {
global $db;
$stmt = $db->prepare($query);
$stmt->execute($input);
$stmt->setFetchMode(PDO::FETCH_OBJ);
return $stmt;
}
To retrieve data, call the retrieve() function
Retrieval page, say display.php
require 'connection.php';
$getid = $_GET["id"];
$result=retrieve("SELECT paste FROM pasteinfo WHERE id=?",array($getid));
$row=$result->fetch();
//To get paste column of that id
$paste=$row->paste;
echo $paste;

How can I prevent this script from being freely accessed?

I am trying to create a simple PHP/MySQL message system. The following code is a section of the page that displays the messages a user has received, messages.php. The user's messages have been fetched from MySQL and stored in the variable $messages.
foreach($messages as $message) {
// formatting, printing the text, etc.
echo 'Remove';
}
And here is the file msg_del.php:
<?php
$id = $_GET['id'];
// Connect to the database
require("../info/dbinfo.php");
$db_user = constant("DB_USER");
$db_pass = constant("DB_PASS");
$db_name = constant("DB_NAME");
$db_server = constant("DB_SERVER");
try {
$conn = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("DELETE FROM messages WHERE id = " . $conn->quote($id) . ";");
$stmt->execute();
}
catch(PDOException $e) {
echo "Error connecting to database!";
exit();
}
// Redirect to messages page
header("Location: messages.php");
exit();
?>
The code is fully functional, but the problem is that anyone can type msg_del.php?id=SOMEID into a browser and delete messages. How can I secure this to where messages can only be deleted from the links on messages.php?
You're going to need some sort of token in your request to validate that this is indeed a valid request from your system.
One method would be to append a nonce to your request. This ensures that the request came from a form you control, and someone isn't using an old form to spoof a new request.
There are many nonce libraries for PHP you can choose from.
The script needs to know if the current user has permission to do the action. One simple way to do that is with the $_SESSION variable.
Something like:
session_start();
if (!isset($_SESSION['user_id']) && /*permission logic here*/) {
//display an error message
die();
}
// database query here

PDO print_r() returns 1

So I have a PDO and MySQL script that is used to retrieve a result based on the user's username, or screen name, in this case being e.
First, I have a function at the beginning of the file that is used to connect to the database. (it is present in a functions.php file and required at the beginning of each page, thus the globalization). This function doesn't have anything wrong with it (as far as I know).
function SQLConnect () {
// Database connection variables
$host = "localhost";
$dbname = "dropbox";
$user = "root";
$password = "ethan17458";
// Connect to the database
try {
//put $connect in global scale of document
global $connect;
// attempt to connect to database
$connect = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
// Sets error mode
$connect->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch (PDOException $e) {
// Retrieves error message if connection fails
echo $e->getMessage();
}
}
This function uses PDO to connect to the database containing the user's information.
Next is the script to retrieve the user's data
// Test user in database
$test = "e";
try {
//confirms running of "try" block
echo "tried";
//database information
$host = "localhost";
$dbname = "dropbox";
$user = "root";
$password = "ethan17458";
//Prepare statement from connection function
// username_raw is "e"
//username should be e1671797c52e15f763380b45e841ec32 (md5)
$statement = $connect->prepare("SELECT `username` FROM `users` WHERE `username_raw` = ':name'");
//create placeholder for prepared statement
$statement->bindParam(":name", $test);
//make the statement fetch in an associative array
$statement->setFetchMode(PDO::FETCH_ASSOC);
//execute the prepared statement
$statement->execute();
//set $get_result to the fetched statement
$get_result = $statement->fetch();
//attempt to display the data fetched in $get_result
echo "<br />";
echo "<pre>";
//Outputs 1 for some reason
// **not working**
echo print_r($get_result);
echo "</pre>";
echo "<br />";
} catch (PDOException $e) {
//confirm running of "catch" block
echo "caught";
// echo error message
echo $e->getMessage();
}
When I run this script I get this output:
tried
1
In this output, tried is the confirmation that the "try" statement was processed, and the 1 is where I start to run into problems.
If the script was working as I would like, the script would retrieve the data e1671797c52e15f763380b45e841ec32 from the database because it is the column username where the username_raw is e, as is stated in the PDO prepared statement.
The ideal output should be
tried
e1671797c52e15f763380b45e841ec32
What am I doing wrong?
fetch() is returning false, which prints nothing to the screen. This is false because you're getting no results because you're putting single quotes around your parameter in the query, which PDO takes care of for you. Just remove the quotes around :name.

login fails with correct info using PDO

I converted my login page to use PDO but now it's not working. I've run through all kinds of code examples and I can't figure out where I'm going wrong. This looks perfect to me. Also error reporting is fully enabled and yet I don't get any errors. I just get the browser error for the page being "incorrectly configured". FYI, this is a SQL db
//Code
<?php
require ("../Android/connect_db.php");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$query_unpw = $db->prepare("
SELECT member_mast.company_name
FROM member_mast
WHERE username = ?
AND password = ?
");
//$username = $_POST['username'];
//$password = $_POST['password'];
$username = 'abc';
$password = 'abc';
$name = "name";
$query_unpw->bindValue(1, $username, PDO::PARAM_STR);
$query_unpw->bindValue(2, $password, PDO::PARAM_STR);
$query_unpw->execute();
$count = $query_unpw->rowCount();
if ($count > 0) {
while ($row = $query_unpw->$fetch(PDO::FETCH_ASSOC)) {
$name = $row['company_name'];
}
echo $name;
} else {
echo "Username/Password is invalid";
}
} catch(PDOException $e) {
die($e->getMessage());
}
?>
Now the only thing I've been able to figure out after commenting out different pieces of code is that if I comment out the username and password, like this
//$username = 'abc';
//$password = 'abc';
Then the page loads and just gives me my else echo of "Username/Password is invalid". However I don't think I'm using them wrong and I know they are correct. So the obvious question is am I blind, what's wrong here? The bonus question is, since I will be using _POST for these variables when this works, am I properly sanitizing the user inputs? Still really new to PDO and I want to make sure I'm doing this right. Thanks for the help!
Problem is here:
$query_unpw->$fetch
It must be:
$query_unpw->fetch()
It's a method, so skip that $ sign.
I suggest you to use ini_set('display_errors', "On") while developing.

Categories