PHP PDO adding to database will not work? [calendar] - php

I found a calendar script anyways, Like the rest of my files I want them to run off one single config.php file. Every single script so far does, although I found a calendar script that is coded in PHP PDO the same language im coding the rest in although I Try and include config.php although for some reason it will not work.
Original code of the script: [Which worked]
<?php
$id = $_POST['id'];
$title = $_POST['title'];
$start = $_POST['start'];
$end = $_POST['end'];
try {
$bdd = new PDO('mysql:host=localhost;dbname=database2', 'root', 'mypassword');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// update the records
$sql = "UPDATE evenement SET title=?, start=?, end=? WHERE id=?";
$q = $dbh->prepare($sql);
$q->execu
te(array($title,$start,$end,$id));
?>
My edit of the script:
<?php
include "../inc/config.php";
$id = $_POST['id'];
$title = $_POST['title'];
$start = $_POST['start'];
$end = $_POST['end'];
// update the records
$sql = "UPDATE evenement SET title=?, start=?, end=? WHERE id=?";
$q = $dbh->prepare($sql);
$q->execute(array($title,$start,$end,$id));
?>
Config.php
<?php
$hostname = 'localhost';
$username = 'root';
$password = 'mypassword';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=database2", $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>

Related

Is it possible to parametarize query that has a concatenation variable?

As learning php and sql injections, I would like to parametize my queries for safe and secure website app. however, mine does not work I try to parametize my update and select my query but I didn't achieved the goal to make the program working.
The current output is throwing an error the ? is not found
As of now here is my code, am I missing something that does not work?
<?php
//connection
$connection = mysqli_connect("hostserver","username","");
$db = mysqli_select_db($connection, 'dbname');
if (isset($_POST['qrname'])) {
$qrid = $_POST['qrid'];
//Query No. 1
$qrQuery = "SELECT * FROM scratch_cards WHERE code='$qrid' ";
$qrQuery_run = mysqli_query($connection,$qrQuery);
//Query No. 2
$qrQuery2 = "UPDATE scratch_cards SET status = 'U' WHERE code='$qrid' ";
$qrQuery_run2 = mysqli_query($connection,$qrQuery2);
$qrQuery2->bind_param("s", $qrid);
$qrQuery2->execute();
while ($qrRow = mysqli_fetch_array($qrQuery_run)) {
$txtQrvalue = $qrRow['amount'];
$txtQrstatus = $qrRow['status'];
// QUERY TO UPDATE THE VALUE
// BIND AND PARAMETIZE MY QUERY
$qrQuery3 = $db->parepare("UPDATE shopusers SET ewallet = ewallet + " . (0+?) . " WHERE id = '?' ");
$qrQuery3->bind_param("ii", $txtQrvalue, $id);
$qrQuery3->execute();
//END
}
If I'm reading your question and code right, you can reduce this down to two queries using a JOIN instead, that way you can get rid of the SELECT statement. Use prepared statements for both.
I also specified your connection's charset to UTF-8 (which you should set for your PHP and HTML headers, and your database-tables too).
<?php
$connection = mysqli_connect("hostserver","username","");
$db = mysqli_select_db($connection, 'dbname');
$connection->set_charset("utf8");
if (isset($_POST['qrname'])) {
$qrid = $_POST['qrid'];
$sql = "UPDATE scratch_cards SET status = 'U' WHERE code=?";
$stmt = $connection->prepare($sql);
$stmt->bind_param("s", $qrid);
$stmt->execute();
$stmt->close();
$sql = "UPDATE shopusers su
INNER JOIN scratch_cards sc
ON sc.qrid = su.code
SET su.ewallet = su.ewallet + sc.amount,
sc.status = 'U'
WHERE sc.code = ?";
$stmt = $connection->prepare($sql);
$stmt->bind_param("s", $qrid);
$stmt->execute();
$stmt->close();
}
we have the foll syntax in PDO bind param, where i have put your update query as an example and it works perfectly fine. Try searching for named parameter binding
<?php
$user = 'root';
$pass = 'xxxx';
$DB = 'test';
$host = 'localhost';
$mysqlConnection = new \PDO('mysql:host='.$host.';dbname='.$DB, $user, $pass);
$mysqlConnection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$sql = 'update info set fname = fname + :fn where id = 1';
$stmt = $mysqlConnection->prepare($sql);
$stmt->bindValue(':fn', '100');
$stmt->execute();
echo $stmt->rowCount();
?>
Is this the query you wanted to run using mysqli bind params???
<?php
ini_set('display_errors', 1);
$user = 'root';
$pass = 'xxxx';
$DB = 'test';
$host = 'localhost';
$sql = 'update info set fname = fname + ? where id = 1';
$conn = new mysqli($host, $user, $pass, $DB);
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $val);
$val = 100;
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
exit;

update field when user logs using pdo

This is my code:
date_default_timezone_set('UTC');
$now = date('l jS \of F Y h:i:s A');
$host = 'localhost';
$dbname = 'myDB';
$username = 'james';
$paswword = '12345';
$dsn = 'mysql:host='. $host .';dbname='. $dbname;
try
{
$connect = new PDO($dsn, $username, $password);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connect->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$connect->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (PDOException $e) {
$message = $e->getMessage()."<br>";
die();
}
$sql = 'SELECT * FROM people WHERE email = :email && password = :password';
$stmt = $connect->prepare($sql);
$stmt->execute(['email' => $email, 'password' => $pass]);
$result = $stmt->fetch();
if($result)
{
$_SESSION["username"] = $post->firstname;
$_SESSION["id"] = $post->id;
$sql = 'UPDATE people SET last_log_date = :now && WHERE id = :id';
//error happens here
$stmt = $connect->prepare($sql);
$stmt->execute(['last_log_date' => $now, 'id' => $_SESSION["id"]]);
$connect = null;
header("location:welcome.php");
}
else
{
$connect = null;
$_SESSION["err_msg"] = 'The password or email does not match';
header("location:loginForm.php");
}
?>
My code will check to see if the user logged in correctly but when I go to update the last_log_date I get a fatal error everytime. I don't understand why I cannot update the field after fetching it. The error says something like SQLSTATE[42000]: Syntax error or access violation:.
How can I properly update the fields after the user has logged in. Please any help would be appreciated
You should bind the right named parameter which is now.
$stmt->execute([':now' => $now, ':id' => $_SESSION["id"]]);
The && before your where clause has nothing to do here. Remove it (check SQL syntax)

How do I reconnect my web pages on my website after updating to PHP 7 with a MySQL database 5.0.0?<?

I added the i updates to communicate with the database & now the page links don't work.
<?php
// Connect to database
$link=mysqli_connect('localhost', 'xxxxx', 'xxxxx');
mysqli_select_db($link, 'waddellc_PHRDB');
$sql = "SELECT * FROM quotes ORDER BY id";
$result = mysqli_query($link, $sql) or die(mysql_error());
$tenant_quotes = array();
$owner_quotes = array();
while($row = mysqli_fetch_array($result)) {
This should do the work, using PDO :
$servername = "localhost";
$username = "username";
$password = "password123";
$conn = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=databaseName", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
if(!is_null($conn)){
$stmt = $conn->prepare("SELECT * FROM quotes ORDER BY id");
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
}
I also think you need to update your database, it's quite old now.

How to change mysql_connect into PDO. Updating form

I'm new to programming and just changed from mysql to mysqli, but when i found my login script on the net it was written with PDO. So now i'm onto that ;D
How can i change this php file to use PDO to update my database?!
Config.php
<?php
// These variables define the connection information for your MySQL database
$username = "usr";
$password = "pass";
$host = "host";
$dbname = "databasee";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try { $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); }
catch(PDOException $ex){ die("Failed to connect to the database: " . $ex- >getMessage());}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
PHP:
<?php
if($_POST) {
$connect = mysqli_connect('host', 'username', 'password', 'dbname');
require("config.php");
if(empty($_SESSION['user'])) {
header("Location: index.php");
die("Redirecting to ../index.php");
} else {
// get data from model form meny.php
$valt_objekt_id = mysqli_escape_string($connect, strip_tags($_POST['valt_objekt_id']));
$valt_objekt_nummer = mysqli_escape_string($connect, strip_tags($_POST['valt_objekt_nummer']));
$valt_objekt_alias = mysqli_escape_string($connect, strip_tags($_POST['valt_objekt_alias']));
$valt_objekt_leverans = mysqli_escape_string($connect, strip_tags($_POST['valt_objekt_leverans']));
$valt_objekt_adress = mysqli_escape_string($connect, strip_tags($_POST['valt_objekt_adress']));
// update database
$sql = "UPDATE `objekt`
SET `objekt_nummer` = '$valt_objekt_nummer',
`objekt_alias`= '$valt_objekt_alias',
`objekt_leverans` = '$valt_objekt_leverans',
`objekt_adress` = '$valt_objekt_adress'
WHERE `objekt_id` = '$valt_objekt_id'";
//this is required for almost every mysqli_* function
$result = mysqli_query($connect, $sql); //the example
//mysqli can update multiple rows at a time
// if successfully updated.
if($result){
echo "Uppdateringen lyckades <br> <a href='../objekt.php'>Gå tillbaka</a>";
} else {
echo mysql_error();
}
}
}
?>
Here is the PDO version of your script:
if($_POST) {
if(empty($_SESSION['user'])) {
header("Location: index.php");
die("Redirecting to ../index.php");
} else {
require("config.php");
// get data from model form meny.php
$valt_objekt_id = $_POST['valt_objekt_id'];
$valt_objekt_nummer = $_POST['valt_objekt_nummer'];
$valt_objekt_alias = $_POST['valt_objekt_alias'];
$valt_objekt_leverans = $_POST['valt_objekt_leverans'];
$valt_objekt_adress = $_POST['valt_objekt_adress'];
// update database
$sql = "UPDATE `objekt`
SET `objekt_nummer` = :objekt_nummer,
`objekt_alias`= :objekt_alias,
`objekt_leverans` = :objekt_leverans,
`objekt_adress` = :objekt_adress
WHERE `objekt_id` = :objekt_id";
$stmt = $db->prepare($sql);
$result = stmt->execute(array(':objekt_nummer' => $valt_objekt_nummer,
':objekt_alias' => $valt_objekt_alias,
':objekt_leverans' => $valt_objekt_leverans,
':objekt_adress' = $valt_objekt_adress,
':objekt_id' => $valt_objekt_id
));
if($result){
echo "Uppdateringen lyckades <br> <a href='../objekt.php'>Gå tillbaka</a>";
} else {
print_r($db->errorInfo());
}
}
}
Learn more about PDO prepared statments

MySql PHP Update Error

I've been messing about with this code for a few hours now and can't work out why it's not working. It's a profile update php page that is passed through JQuery and all seems to be fine except for it actually updating into the table. Here is the code I'm using:
session_start();
include("db-connect.php");//Contains $con
$get_user_sql = "SELECT * FROM members WHERE username = '$user_username'";
$get_user_res = mysqli_query($con, $get_user_sql);
while($user = mysqli_fetch_array($get_user_res)){
$user_id = $user['id'];
}
$name = mysqli_real_escape_string($con, $_REQUEST["name"]);
$location = mysqli_real_escape_string($con, $_REQUEST["location"]);
$about = mysqli_real_escape_string($con, $_REQUEST["about"]);
$insert_member_sql = "UPDATE profile_members SET id = '$user_id', names = '$name', location = '$location', about = '$about' WHERE id = '$user_id'";
$insert_member_res = mysqli_query($con, $insert_member_sql) or die(mysqli_error($con));
if(mysqli_affected_rows($con)>0){
echo "1";
}else{
echo "0";
}
All I get as the return value is 0, can anybody spot any potential mistakes? Thanks
To begin with, use
require("db-connect.php");
instead of
include("db-connect.php");
And now, consider using prepared statements, your code is vulnerable to sql injections.
Consider using PDO instead of the mysql syntax, in the long run I find it much better to use and it avoids a lot of non-sense-making problems, you can do it like this (You can keep it in the db-connect file if you want, and even make the database conncetion become global):
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$databaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host, $databaseName, $user, $pass);
Now, here's how you can solve your problem (Using prepared statements, avoiding sql injection):
function userId($db, $user_username)
{
$query = "SELECT * FROM members WHERE username = :username;";
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(
':username' => $user_username
));
$result = $statement->fetch(PDO::FETCH_ASSOC);
if($result)
{
return $result['user_id'];
}
return false
}
function updateProfile($db, $userId, $name, $location, $about)
{
$query = "UPDATE profile_members SET name = :name, location = :location, about = :about WHERE id = :userId;";
$statement = $db->prepare($query); // Prepare the query.
$result = $statement->execute(array(
':userId' => $userId,
':name' => $name,
':location' => $location,
':about' => $about
));
if($result)
{
return true;
}
return false
}
$userId = userId($db, $user_username); // Consider if it is not false.
$name = $_REQUEST["name"];
$location = $_REQUEST["location"];
$about = $_REQUEST["about"];
$updated = updateProfile($db, $userId, $name, $location, $about);
You should check the queries though, I fixed them a little bit but not 100% sure if they work.
You can easily make another function which inserts into tha database, instead of updating it, or keeping it in the same function; if you find an existance of the entry, then you insert it, otherwise you update it.

Categories