what's wrong in this PDO script - php

Here i am writing a script which will send three different values to a database using a simple html form.But whenever i submit the form no values are inserted and i get the following error :
what might be the reason for this error.How can i fix this problem.
$server='localhost';
$user='root';
$password='';
$dbname='fruits';
if(isset($_POST['name']) &&isset($_POST['colour']) && isset($_POST['calories'])){
if(!empty($_POST['name']) && !empty($_POST['colour']) && !empty($_POST['calories'])){
$name=$_POST['name'];
$colour=$_POST['colour'];
$calories=$_POST['calories'];
try{
$conn=new PDO('mysql:host=$server,dbname=$dbname,$user,$password');
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$stmt=$conn->prepare("INSERT INTO favfruit(name,colour,calories)
VALUES(:name,:colour,:calories)");
$stmt->execute(array(':name'=>$name,':colour'=>$colour,':calories'=>$calories));
echo 'it was successfully entered to database';
}catch(PDOException $e){
echo 'error : '.$e->getMessage();
}
}
}
HTML form :
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post'>
fruit name :<input type='text' placeholder='fruit name' name='name'></br>
colur :<input type='text' placeholder='fruit colour' name='colour'></br>
calories :<input type='text' placeholder='calories' name='calories'></br>
<input type='submit' value='SUBMIT FORM'>
</form>

Your problem is just a typo. Replace
$conn=new PDO('mysql:host=$server,dbname=$dbname,$user,$password');
by
$conn=new PDO("mysql:host=$server;dbname=$dbname",$user,$password);

require_once($_SERVER['DOCUMENT_ROOT'].'/settings.php');
class db extends pdo{
//variables
public $db = '';
public $config;
public $settings = array(
'host' => SERVER,
'database' => DB,
'username' => USER,
'password' => PASS,
);
public function __construct(){
$this->db = new PDO(
"mysql:host={$this->settings['host']};" .
"dbname={$this->settings['database']};" .
"charset=utf8",
"{$this->settings['username']}",
"{$this->settings['password']}"
);
$this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
Within the settings.php file define the constants for your db connection
then create a new function.
public function InsertFruit() {
if(isset($_POST['name']) &&isset($_POST['colour']) && isset($_POST['calories'])){
if(!empty($_POST['name']) && !empty($_POST['colour']) && !empty($_POST['calories'])){
$name=$_POST['name'];
$colour=$_POST['colour'];
$calories=$_POST['calories'];
try{
$query = <<<SQL
INSERT INTO favfruit(name,colour,calories)
VALUES(:name,:colour,:calories)
SQL;
$resource = $this->db->prepare($query);
$resource->execute(array(
'name' => $_POST['name'],
'colour' => $_POST['colour'],
'calories' => $_POST['calories'],
));
echo $_POST['name'].' entered into database';
$stmt=$conn->prepare("INSERT INTO favfruit(name,colour,calories)
VALUES(:name,:colour,:calories)");
}catch(PDOException $e){
echo 'error : '.$e->getMessage();
}
}
}
}
I know for sure as long as your webserver is up and running that this will work for your connection and that it will ease any other connections you need to use later on. As for your actual form just use a case process to determine what function is ran.

Related

How to store editable define constant web settings in mysql [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm creating simple web application using php. And there is basic constant settings in (config.php) like:
define('SITE_NAME', 'Site A');
define('SITE_URL', 'https://example.com');
define('SITE_EMAIL', 'test#example.com');
define('SENDGRID_API', 'G.6786jka9769fhgg45479989hjvh');
And calling this file almost every page. Is it possible to store this value in mysql and it's editable via web interface for admin? If yes, how to do it? So that i don't need to connect to db for everytime using this constant. If i'm not mistaken, some settings from wordpress is using something like this.
For your solution create a table like:
DROP TABLE IF EXISTS `settings`;
CREATE TABLE IF NOT EXISTS `settings` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`site_option` varchar(200) NOT NULL,
`site_value` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
COMMIT;
Needs 4 files: index.php, db.php, create.php, update.php
db.php
function connect()
{
$dsn = 'mysql:host=localhost;port=3306;dbname=update;';
try{
return new PDO($dsn, 'root', '');
}catch( \Exception $e ){
return $e->getMessage();
}
}
index.php
<?php
session_start();
?>
<htmL>
<head>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<title>Test UPDATING records in PHP</title>
</head>
<div>
<?php
if(isset($_SESSION['success'])){
echo $_SESSION['success'];
}elseif(isset($_SESSION['error'])){
echo $_SESSION['error'];
}
//clearing all session values
session_unset();
?>
<h2>Create New Site Option / Setting</h2>
<form action="create.php" method="POST">
Site Option: <input type='text' name='site_option' size='12' value=''>
Site Value: <input type='text' name='site_value' size='12' value=''>
<input type="submit" value="Submit">
</form>
</div>
<?php
require_once('db.php');
$pdo = connect();
if( $pdo instanceof \PDO ){
$sql = "SELECT * FROM settings";
$dbh = $pdo->prepare($sql);
var_dump($dbh);
$dbh->execute();
foreach($dbh as $row){
echo "<div style='padding-bottom:1em;' class='datarow'>";
echo "<input type='text' name='site_option' size='12' value='{$row['site_option']}'>";
echo "<input type='text' name='site_value' size='3' value='{$row['site_value']}'>";
echo "<input type='hidden' name='id' size='3' value='{$row['id']}'>";
echo "<button onClick='updateValues(this);'>Update Option</button>";
echo "</div>";
//define the constant
if (!defined($row['site_option'])) {
define( strtoupper($row['site_option']),$row['site_value']);
}
}
// To see all constants , uncomment if you need to see them for testing
// print_r(get_defined_constants(true));
}else{
//echo $pdo->getMessage();
}
?>
<script type="text/javascript">
function updateValues(obj){
let datarow = $(obj).closest('.datarow');
//("input[name='quantity']").val()
console.log($('input[name="author"]', datarow).val());
$.post( "update.php", { site_option: $('input[name="site_option"]', datarow).val(),
site_value: $('input[name="site_value"]', datarow).val(),
id: $('input[name="id"]', datarow).val()
//id: $(obj).data('parentid')
}
).done(function( data ) {
if( ! $.isEmptyObject( data.error ) ) {
alert( 'error' + data.error);
}else{
//success
alert( 'Success: ' + data.success );
location.reload();
}
});
}
</script>
</htmL>
create.php
session_start();
require_once('db.php');
if(isset($_POST['site_option']) && isset($_POST['site_value'])){
//Todo: do some sort of validation / sanity checking (dont trust user input)
$site_option = $_POST['site_option'];
$site_value = $_POST['site_value'];
$sql = "INSERT INTO settings ( id, site_option, site_value ) VALUES ( NULL, :site_option, :site_value )";
$pdo = connect();
$dbh = $pdo->prepare($sql);
try{
$dbh->execute( [
':site_option' => $site_option,
':site_value' => $site_value
] );
$_SESSION['success'] = 'Successful creation of new record';
header("Location: index.php");
}catch( \Exception $e ){
$_SESSION['error'] = 'Error creating new entry';
//echo json_encode( [ 'error' => $e->getMessage() ] );
}
}
update.php
require_once('db.php');
header('Content-Type: application/json');
if(isset($_POST['id'])){
//Todo: do some sort of validation / sanity checking (dont trust user input)
$sql = "UPDATE settings SET site_option=:site_option, site_value=:site_value WHERE id=:id";
$pdo = connect();
$dbh = $pdo->prepare($sql);
try{
$dbh->execute( [
':site_option' => $_POST['site_option'],
':site_value' => $_POST['site_value'],
':id' => $_POST['id']
] );
echo json_encode( [ 'success' => 'Record updated.' . $_POST['site_option'] ] );
}catch( \Exception $e ){
echo json_encode( ['error' => 'Error updating the record' ]);
//echo json_encode( [ 'error' => $e->getMessage() ] );
}
}

PHP/SQL Question regarding updating/deleting in php with a sql database

I'm working on a basic database app which uses a sql database to store and retrieve information from as part of the crud operations the creation and reading of data works perfectly fine. However I'm facing issues with updating and deleting the data stored and it never happened before.Is there something I'm doing wrong?
I'm assuming the something that I've done wrong in update may be similar to my issue in delete.
Here's the code for the update part : [Note this is just for a basic demo and so security features aren't important]
<?php
require "config.php";
require "common.php";
if (isset($_POST['submit'])) {
try {
$connection = new PDO($dsn, $username, $password, $options);
$user =[
"char_id" => $_POST['char_id'],
"char_name" => $_POST['char_name'],
"currency" => $_POST['currency'],
"server_id" => $_POST['server_id'],
"account_id" => $_POST['account_id']
];
$sql = "UPDATE characters
SET
char_name = :char_name,
currency = :currency,
server_id = :server_id,
account_id = :account_id
WHERE char_id = :char_id";
$statement = $connection->prepare($sql);
$statement->execute($user);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
if (isset($_GET['char_id'])) {
try {
$connection = new PDO($dsn, $username, $password, $options);
$char_id = $_GET['char_id'];
$sql = "SELECT * FROM characters WHERE char_id = :char_id";
$statement = $connection->prepare($sql);
$statement->bindValue(':char_id', $char_id);
$statement->execute();
$user = $statement->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
} else {
echo "Something went wrong!"; //this happens
exit;
}
?>
<?php require "templates/header.php"; ?>
<?php if (isset($_POST['submit']) && $statement) : ?>
<blockquote><?php echo escape($_POST['char_name']); ?> successfully
updated.</blockquote>
<?php endif; ?>
<h2>Edit a character</h2>
<form method="post">
<?php foreach ($user as $key => $value) : ?>
<label for="<?php echo $key; ?>"><?php echo ucfirst($key); ?>
</label>
<input type="text" name="<?php echo $key; ?>" id="<?php echo $key; ?>" value="<?php echo escape($value); ?>" <?php echo ($key === 'id' ? 'readonly' : null); ?>>
<?php endforeach; ?>
<input type="submit" name="submit" value="Submit">
</form>
Back to home
<?php require "templates/footer.php"; ?>
The problem seems to be that your loop of inputs expects an array variable called $user. The $user comes from a DB query, using inputs from your form, but the actual input values comes from the $user variable which isn't set until the DB query is run!
First I would try keeping the $_GET in your code. Your SELECT query expects $_GET['char_id'] to be set in order to execute. Do that by adding ?char_id=SOME NUMBER HERE to your url and go. The number should be a char_id present in your Database.
Now the DB query gets the $_GET['char_id'] that it needs (since the $_GET method fetches parameters from the URL), and you should get some working inputs from your loop, and be able to update entries in your Database.

PDO Connection issue cannot Insert data into mysql DB

I just wanted to create PDO connection rather than old connection but I can't get form fields to be inserted into MYSQL DB. I am sure I am making a stupid mistake however I can't figure it out what exactly.
Here is my database.php file
<?php
$server = 'localhost';
$username = 'root';
$password = '';
$database = 'dbaname';
try{
$conn = new PDO("mysql:host=$server;dbname=$database;", $username, $password);
} catch(PDOException $e){
die( "Connection failed: " . $e->getMessage());
}
and after submit action is taking place at my process.php
<?php
if (!isset($_SESSION)) session_start();
if(!$_POST) exit;
require 'database.php';
include dirname(__FILE__).'/settings/settings.php';
include dirname(__FILE__).'/functions/emailValidation.php';
$TechName = strip_tags(trim($_POST["TechName"]));
$Date = strip_tags(trim($_POST["Date"]));
$ToolSerial = strip_tags(trim($_POST["ToolSerial"]));
$CartridgeSerial = strip_tags(trim($_POST["CartridgeSerial"]));
$TorqueSerial = strip_tags(trim($_POST["TorqueSerial"]));
$LastCalibration = strip_tags(trim($_POST["LastCalibration"]));
$ThreadCond = strip_tags(trim($_POST["ThreadCond"]));
$HardfacingCond = strip_tags(trim($_POST["HardfacingCond"]));
$PocketCond = strip_tags(trim($_POST["PocketCond"]));
//$emailaddress = strip_tags(trim($_POST["emailaddress"]));
/*------------------ STEP 2 ------------------*/
$TorquedOEM = strip_tags(trim($_POST["TorquedOEM"]));
$FullAssembly = strip_tags(trim($_POST["FullAssembly"]));
//$file_url = strip_tags(trim($_POST["file_url"]));
$Notes = strip_tags(trim($_POST["Notes"]));
/*------------------ STEP 3 ------------------*/
//$Signature = strip_tags(trim($_POST["Signature"]));
$SignedDate = strip_tags(trim($_POST["SignedDate"]));
try {
$q = "INSERT INTO tportal (TechName, Date, ToolSerial, CartridgeSerial, TorqueSerial, LastCalibration, ThreadCond, HardfacingCond, PocketCond, TorquedOEM, FullAssembly, Notes, SignedDate)
VALUES (:TechName, :Date, :ToolSerial, :CartridgeSerial, :TorqueSerial, :LastCalibration, :ThreadCond, :HardfacingCond, :PocketCond, :TorquedOEM, :FullAssembly, :Notes, :SignedDate)";
$query = $conn -> prepare($q);
$results = $query -> execute(array(
":TechName" => $TechName,
":Date" => $Date,
":ToolSerial" => $ToolSerial,
":CartridgeSerial" => $CartridgeSerial,
":TorqueSerial" => $TorqueSerial,
":LastCalibration" => $LastCalibration,
":ThreadCond" => $ThreadCond,
":HardfacingCond" => $HardfacingCond,
":PocketCond" => $PocketCond,
":TorquedOEM" => $TorquedOEM,
":TorqueSerial" => $TorqueSerial,
":FullAssembly" => $FullAssembly,
":Notes" => $Notes,
":SignedDate" => $SignedDate,
));
if ($conn->query($q)) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted. $PocketCond');</script>";
}
$conn = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
After I click on submit button I get a "Data not successfully inserted pass" pass: is variable result from $PocketCondvariable I placed to test the data.
Thank you for your time.
Apparently after refreshing the database I realized my entries were added to the database however my error scripts were creating problem.
if ($conn->query($q)) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted. $PocketCond');</script>";
}

php include not working on host server but works on local (xampp) server

I cannot resolve why what works locally fails at the host server. It connects to the database, retrieves and displays data, but it fails to retrieve the data and include the form. Hopefully, I have included enough code.
First the data is retrieved and displayed:
/*------------------- DISPLAY ACCESSORIES ------------------*/
if(isset($_GET['table']) && $_GET['table'] === "accessories")
{
$table = 'accessories';
include '../includes/dbconnect.php';
try {
$result = $db->query("SELECT * FROM $table");
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$accessories[] = array(
'id' => $row['id'],
'buy_link' => $row['buy_link'],
'img' => $row['img'],
'item_number' => $row['item_number'],
'name' => $row['name'],
'description' => $row['description'],
'laser_series' => $row['laser_series'],
'laser_model' => $row['laser_model'],
'quantity' => $row['quantity'],
'price' => $row['price'],
);
}
}
catch (PDOException $e)
{
$error = 'Error fetching data.' . $e->getMessage();
include 'error.html.php';
exit();
}
try {
$sql2 = 'DESCRIBE accessories';
$s2= $db->prepare($sql2);
$s2->execute();
$table_fields = $s2->fetchAll(PDO::FETCH_COLUMN);
}
catch (PDOException $e)
{
$error = 'Error fetching data from database.';
include 'error.html.php';
exit();
}
// Close database connection
$db = null;
// Display data on included page
include 'display-accessories.html.php';
exit();
}
Then, in the row the user wishes to edit, he clicks the edit button. Here's that html:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<input type="hidden" name="id" value="<?php htmlout($accessory['id']); ?>">
<button class="btn btn-default btn-sm" type="submit" name="action" value="edit_accessories">Edit</button>
</form>
Clicking the edit button triggers this php, which fails (not locally). It does not include the file (the path is correct; in the same folder).
/*------------------- EDIT ACCESSORIES ------------------*/
if(isset($_POST['action']) && $_POST['action'] === "edit_accessories")
{
// Assign name of table being queried to variable
$table = 'accessories';
// Sanitize posted data
$id = sanitize($_POST['id']);
// Connect to database
include '../includes/dbconnect.php';
try {
$sql = "SELECT * FROM $table WHERE id = :id";
$s = $db->prepare($sql);
$s->bindValue(':id', $id);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error fetching data.' . $e->getMessage();
include 'error.html.php';
exit();
}
// Store single row result in $item associative array
$item = $s->fetch(PDO::FETCH_ASSOC);
// Close database connection
$db = null;
// Display row content in form
include 'edit-accessories-form.html.php';
exit();
}
If anyone has any ideas why this does not work, I welcome your insight!
Just change the sentence:
FROM: '../includes/dbconnect.php';
TO: $_SERVER['DOCUMENT_ROOT'].'/includes/dbconnect.php';
In the server the path can't be write as '../' because there is a whole different server path configuration.

Client looks like we got no XML document in soapclient php

I have problem in using SoapClient in php. Considering that it is my fist try in authenticating user credentials so I might have some basic mistakes in my code as well.
I have a simple html tags that takes user credentials(on client side) and sends them to a processing page (works in backend) and sends soap message to server page using __soapCall. Here is the code.
Please help with your suggestions
Client.php
<html>
<body>
<form method='POST' action='middle_client.php'>
<lable>User Name</lable><input type='text' name= 'user' id='user'>
<br>
<lable>Password</lable><input type='password' name= 'pass'>
<br>
<lable>Insurance Name</lable><input type='text' name= 'insurance'>
<br>
<input type='submit' name= 'submit'>
</form>
<body>
</html>
Middle_client.php
<?php
use \SoapClient;
if(isset($_POST['submit'])){
$name= $_POST['user'];
$password= $_POST['pass'];
$insurance= $_POST['insurance'];
$con=mysql_connect("localhost","root","");
// Check connection
if (!$con) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db($insurance, $con);
if (!$db_selected) {
die('Invalid query: ' . mysql_error());
}
if ($db_selected=='insurance'){
//header('Location:server.php');
}
}
class client{
function __construct(){
$parameters = array('location' => 'http://localhost/XXX/server.php',
"uri" => 'urn://localhost/XXX/',
'trace' => 1,
);
$this->instance = new SoapClient(NULL,$parameters);
$auth_parameter = new stdClass();
$auth_parameter->name = "ABC";
$auth_parameter->password = "root";
$header_param = new SoapVar($auth_parameter, SOAP_ENC_OBJECT);
$header = new SoapHeader('XXX', 'authenticate', $header_param, false);
$this->instance->__setSoapHeaders(array($header));
}
public function getname($array){
return $this->instance->__soapCall('testing', $array);
}
}
$client = new client();
$array = array ('P_name'=> 'Foo');
echo $result = $client->getname($array);
var_dump($client);
?>
and Server.php
<?php
class server{
private $con;
public function authenticate($header_param){
if ($header_param->name == 'ABC' && $header_param->password == 'root' ){
return true;
}
else throw new SOAPFault("Wrong Name/Password", 401);
}
public function __construct(){
$this->con = (is_null($this->con)) ? self::connect() : $this->con;
}
static function connect(){
$con=mysql_connect("localhost","root","insurance");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$db = mysql_select_db("user", $con);
return $con;
}
public function testing($array){
$usernme = $array['P_name'];
$sql = "SELECT * from user where P_name=".$usernme;
$qry= mysql_query($sql,$this->con);
$result = mysql_fetch_array($qry);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
/return $returned_name= $result["P_name"];
}
}
$parameter = array("uri" => 'localhost/XXX/server.php');
$server = new SoapServer(NULL, $parameter);
$server-> setClass('server');
$server-> handle();

Categories