PDO, $_GET, and SELECTing from MySQL Database - php

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;

Related

Is there a way to store in same database row divided in two forms?

I have a form that gets some information, then redirects to html static pages, and comes back to another form to store the contact information (phone). I wonder if somehow i can save or set the same id of data inserted before, so I can insert the phone in the right row. I uploaded the project so you can have a better understanding:
link to website
Here's the code of first form data insert:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$pdo = new PDO(''); //removed this line for security
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST['nome']))
{
$sql = $pdo->prepare("INSERT INTO dados VALUES(null,?,?,?,?)");
$sql->execute(array(
$_POST['nome'],
$_POST['profissao'],
$_POST['idade'],
$_POST['telefone']
));
}
echo "<br/>";
if (isset($_POST['r1']))
{
$sql = $pdo->prepare("INSERT INTO respostasVALUES(null,?,?,?,?,?,?,?,?,?)");
$sql->execute(array(
$_POST['r1'],
$_POST['r2'],
$_POST['r3'],
$_POST['r4'],
$_POST['r5'],
$_POST['r6'],
$_POST['p1'],
$_POST['p2'],
$_POST['hotel']
));
}
?>
And here's the second form insert:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
$pdo = new PDO(""); //removed for security
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST["telefone"]))
{
$sql = $pdo->prepare(
"UPDATE dados SET telefone=? WHERE id = 'LAST_INSERT_ID()'"
);
$sql->execute([$_POST["telefone"]]);
}
?>
I can't get that to work, some help would be appreciated. I'm also new into programming, so please, be comprehensive.

php PDO doesn't print out database values

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.

PHP/mySQL - INSERT INTO not working but also no error

one specific php/mydql command is not working. the sql will not be executed, nor do I get an error message. The sql command executed by HEIDI SQL gives me no error. Query before this command are executed correct. Only this one specific isn't working. I wrote it done one by one as the others which worked perfect before. Heres the code:
$sql = "INSERT INTO users (username,password,email) VALUES(?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->execute(array($username, $hash, $email));
The connection.php file code:
global $conn;
$config = [
$dbname = "mysql:host=localhost; dbname=starwardb;",
$login = "root",
$password = ""
];
try {
$conn = new PDO(...$config);
} catch (Exception $ex) {
echo "ERROR: " . $ex;
}
Thank you for any advice!
The mistake was, that the hashing of the password extends the string. The Database length of the password was by 50. I have increased it to 64 and now it works fine.
From: https://stackoverflow.com/revisions/45147068/3

Cannot update MySQL using PDO::PARAM_LOB on a serialized array.No error is being thrown

I am running a test to serialize an array using PHP, in order to update my database I use the PDO extension. I have tried changing the code a bit, but there is no error to be catched by the try block. I have other functions where I successfully updated other tables, the only diferense here is the PDO::PARAM_LOB line. Any help is greatly appreciated.
<?php
require("database.php");
try {
$test = array('15525');
array_push($test, '12345');
var_dump($test);
$stest = serialize($test);
var_dump($stest) ;
$dapartmentToUpdate = 3;
$result = $db->prepare("
UPDATE departments_employees
SET employee_id = ?
WHERE department_id = ?
");
$result ->bindParam(1,$stest,PDO::PARAM_LOB);
$result ->bindParam(2,$departmentToUpdate,PDO::PARAM_INT);
$result -> execute();
} catch (Exception $e) {
echo "Could not write to database for some odd reason";
exit;
}
?>
I must add that by taking the query directly to SQL makes it run just fine, so I must be missing something. The statement on SQL looks like
UPDATE departments_employees
SET employee_id = 'a:2:{i:0;s:5:"15525";i:1;s:5:"12345";}'
WHERE department_id = 3
config.php are just some environment constants, user, password and some other private stuff, database.php looks like this:
<?php
require_once ('config.php');
try {
$db = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME .";port=" . DB_PORT,DB_USER,DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch (Exception $e) {
echo "Could not connect to the database.";
exit;
}

How to fix server error 500 when executing PHP script?

I am trying to insert into a database through PHP. However, when I connect to the PHP file I get server 500 error. Would anyone be able to spot what I am doing wrong?
<?php
include 'db-security.php';
function db_login()
{
$userName = filter_input(INPUT_POST, "userName");
$password = filter_input(INPUT_POST, "password");
//binding the variable to sql.
$statement = $link->prepare("INSERT INTO user(username, password)
VALUES($userName, $password)");
//execute the sql statement.
$statement->execute();
}
db_login();
?>
Updated:
I have discovered the error occurs when i add filer_input or $_post to the php.
<?php
include 'db-security.php';
function db_login() {
global $conn;
// use my eaxmple to filter input to get the data out of the form, because security.
//$userName = filter_input(INPUT_POST, "userName");
$userName = $_POST['userName'];
$password = $_POST['password'];
//$password = filter_input(INPUT_POST, "password");
//binding the variable to sql.
$stmt = $conn->prepare("INSERT INTO user(username, password)VALUES(:usrname, :pswd)");
$stmt->bindParam(':pswd', $password);
$stmt->bindParam(':usrname', $userName);
$stmt->execute();
//execute the sql statement.
}
db_login();
?>
db-security.php
<?php
include_once 'conf.php';
function db_connect() {
// Define connection as a static variable, to avoid connecting more than once
static $conn;
// Try and connect to the database, if a connection has not been established yet
if(!isset($conn)) {
// Load configuration as an array. Use the actual location of your configuration file
try
{
$conn = new PDO("mysql:host=localhost;port=3307;dbname=database", DB_USERNAME,DB_PASSWORD);
// stores the outcome of the connection into a class variable
$db_msg = 'Connected to database';
}
catch(PDOException $e)
{
$conn = -1;
$db_msg = $e->getMessage();
}
//$conn = new PDO(DB_HOST,DB_USERNAME,DB_PASSWORD , MAIN_DB);
}
}
db_connect();
?>
Where is $link defined? In 'db-security.php'? If yes then you have a variable scope problem. Just pass $link in the function call. This would have to be done for all functions.
define function as = function db_login($link)
call function like = db_login($link);
EDIT:
Don't use a function for 'db-security.php' it should be like this:
<?php
$conn = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
?>
This is not complete code, just a sample. Now $conn is in the global variable scope and using global in the functions will work. Or just pass $conn to the function and not use global at all.
EDIT2:
Below are the working sample scripts. You need to change some information to match your setup. I'm not sure why the function is called db_login() since the function actually adds the user/password into the 'user' table.
conf.php
<?php
define('DB_USERNAME', 'test');
define('DB_PASSWORD', '123456');
?>
db-security.php
<?php
include_once 'conf.php';
try
{
$conn = new pdo("mysql:host=localhost; dbname=test; charset=utf8", DB_USERNAME, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
die('Unable to connect to database!');
}
?>
main script
<?php
include 'db-security.php';
function db_login()
{
global $conn;
$userName = $_POST['userName'];
$password = $_POST['password'];
$stmt = $conn->prepare("INSERT INTO user(username, password) VALUES(:usrname, :pswd)");
$stmt->bindParam(':usrname', $userName);
$stmt->bindParam(':pswd', $password);
$stmt->execute();
}
db_login();
?>
So you need to bind your parameters after prepare statement
$stmt = $link->prepare("INSERT INTO user(username, password)VALUES(:usrname, :pswd)");
$stmt->bindParam(':pswd', $password);
$stmt->bindParam(':usrname', $userName);
$stmt->execute();
I have been looking at your code and I would advice you to try a different approach. I've been wrapping my head around this subject for a while when learning PHP. Best advice i've had is that you can best try when fetching information from the DB is using a try/catch statement everytime. Sounds annoying or problematic but it easy to overlook and well written maintained code because you know every try catch block will execute or catch the error atleast.
With PDO being one of the best solutions because it can connect with multiple databases the best way to execute getting information from the Database is this:*
I am gonna give you my example of something i wrote. I don't want to write it all out in your situation because i feel that's something you can better do to learn what went wrong and i hope this gives you a step in the right direction.
database.php
$serverName = "";
$dbName = "";
$userName = "";
$password = "";
try {
$db = new PDO("mysql:host=$serverName;dbname=$dbName", $userName, $password);
// Set the PDO error mode to exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
}
catch(PDOException $e){
echo"Connection failed: " . $e->getMessage();
exit;
}
?>
index.php Executing a simple commmand get firstName from employers
<?php
require_once 'database.php';
try
{
$sQuery = "
SELECT
firstName
FROM
employees
";
$oStmt = $db->prepare($sQuery);
$oStmt->execute();
while($aRow = $oStmt->fetch(PDO::FETCH_ASSOC))
{
echo $aRow['firstName'].'<br />';
}
}
catch(PDOException $e)
{
$sMsg = '<p>
Regelnummer: '.$e->getLine().'<br />
Bestand: '.$e->getFile().'<br />
Foutmelding: '.$e->getMessage().'
</p>';
trigger_error($sMsg);
}
?>
Good luck and i hope my index.php is helpful in showing you how I find is the best way momentarily to talk to the database.

Categories