PDO error duplicate data on SteamAuth - php

I am currently using steam auth which I then translated to integrate my code into MySQL.
Unfortunately, I get a message that informs me that the table already exists.
I would like to have a code that allows me to update the data if needed, but unfortunately, I can not find on google.
Here is my code in PDO.
<?php
function newPDO() {
$host = 'x';
$db = 'x';
$user = 'x';
$pass = 'x';
$dsn = "mysql:host=$host;dbname=$db";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
return $pdo;
}
{
$pdo = newPDO();
$stmt = $pdo->prepare('INSERT INTO players (uid, name, avatar) VALUES (:uid, :name, :avatar)');
$stmt->execute(['uid' => $_SESSION['steam_steamid'], 'name' => $_SESSION['steam_personaname'], 'avatar' => $_SESSION['steam_avatar']]);
if($pdo->lastInsertId()) {
//login successfull
return true;
} else {
//registration failed
return false;
}
}
if(!isset($_SESSION['steamid'])) {
loginbutton("rectangle"); //login button
} else {
include ('steamauth/userInfo.php');
//Protected content
echo $steamprofile['personaname'];
echo '<img src="'.$steamprofile['avatar'].'" title="" alt="" />'; // Display their avatar!
logoutbutton("rectangle");
}
?>
And finaly this is the error code my php tells me
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '76561197992043760' for key 'uid'' in C:\xampp\htdocs\inc\login.php:23 Stack trace: #0 C:\xampp\htdocs\inc\login.php(23): PDOStatement->execute(Array) #1 C:\xampp\htdocs\index.php(52): include('C:\xampp\htdocs...') #2 {main} thrown in C:\xampp\htdocs\inc\login.php on line 23
Can you help me solve the prob ?

You can verify first if filed exist with SELECT
If not exist create the row with INSERT
Else update the record with UPDATE

Related

PHP get single value from MySQL with variable [duplicate]

This question already has answers here:
Call to a member function prepare() on a non-object PHP Help [duplicate]
(8 answers)
Closed 2 years ago.
I can't seem to get simple query working to find UserID from the table of Users by UserEmail
I have simple function to suppose to return UserID
functions.php
function get_userID($UEml)
{
// Check database connection
if( ($DB instanceof MySQLi) == false) {
return array(status => false, message => 'MySQL connection is invalid');
}
$qSQL = "SELECT UsID FROM Users WHERE UsEml=? LIMIT 1";
$qSQL = $DB->prepare($qSQL);
$UEml = $DB->real_escape_string($UEml);
$qSQL->bind_param("s", $UEml);
$qSQL->execute();
$result = $qSQL->get_result();
while ($row = $result->fetch_row()) {
return $row[0];
}
// return $row[0];
if($qSQL) {
return array(status => true);
}
else {
return array(status => false, message => 'Not Found');
}
}
and I call it from php script
check-User.php
<?php
require_once("db-config.php");
include 'functions.php';
...
$UsID = get_userID("joe#example.com");
echo 'UserID: <span style="color: blue">'. $UsID ."</span>";
...
?>
db-config.php
<?php
// Two options for connecting to the database:
define('HOST_DIRECT', 'example.com'); // Standard connection
define('HOST_LOCAL', '127.0.0.1'); // Secure connection, slower performance
define('DB_HOST', HOST_DIRECT); // Choose HOST_DIRECT or HOST_STUNNEL, depending on your application's requirements
define('DB_USER', 'dbUser'); // MySQL account username
define('DB_PASS', 'SecretPas'); // MySQL account password
define('DB_NAME', 'DBName'); // Name of database
// Connect to the database
$DB = new MySQLi(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($DB->connect_error) {
die("Connection failed: " . $DB->connect_error);
}
//echo "Connected successfully";
?>
I tried many variations, but no luck and also checked many similar posts here, but just can't get it working.
Thanks
You have a couple of errors here:
$DB is not available in the function
the echo statement is wrong
This is the code without these 2 errors:
function get_userID($DB, $UEml)
{
// Check database connection
if ( ($DB instanceof MySQLi) == false) {
return array(status => false, message => 'MySQL connection is invalid');
}
$qSQL = "SELECT UsID FROM Users WHERE UsEml=? LIMIT 1";
$qSQL = $DB->prepare($qSQL);
$qSQL->bind_param("s", $UEml);
$qSQL->execute();
$result = $qSQL->get_result();
while ($row = $result->fetch_row()) {
return $row[0];
}
// return $row[0];
// I do not know why you wrote this code. If you get an user this code will not be executed
if ($qSQL) {
return array(status => true);
} else {
return array(status => false, message => 'Not Found');
}
}
And your echo:
// ...
$UsID = get_userID($DB, "joe#example.com");
echo "UserID: <span style=\"color: blue\">{$UsID}</span>";

Checking if email address exists in SQL database with php

I am doing a school assignment which has to contain a page for users to register. I am getting an error with checking if their email address is already in the database, but I can't figure out why. The error is:
Notice: Undefined variable: kapcsolat in /home/hallgatok/jyhv6c/www/wf2/php_bead/register.php on line 39
Fatal error: Uncaught Error: Call to a member function prepare() on null in /home/hallgatok/jyhv6c/www/wf2/php_bead/database.php:9 Stack trace: #0 /home/hallgatok/jyhv6c/www/wf2/php_bead/register.php(9): lekerdezes(NULL, 'SELECT * FROM `...', Array) #1 /home/hallgatok/jyhv6c/www/wf2/php_bead/register.php(39): letezik(NULL, 'koostamas199753...') #2 /home/hallgatok/jyhv6c/www/wf2/php_bead/register.php(53): validate(Array, Array, Array) #3 {main} thrown in /home/hallgatok/jyhv6c/www/wf2/php_bead/database.php on line 9
My database.php, where I connect:
database.php
<?php
function kapcsolodas($kapcsolati_szoveg, $felhasznalonev = '', $jelszo = '') {
$pdo = new PDO($kapcsolati_szoveg, $felhasznalonev, $jelszo);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
function lekerdezes($kapcsolat, $sql, $parameterek = []) {
$stmt = $kapcsolat->prepare($sql);
$stmt->execute($parameterek);
return $stmt->fetchAll();
}
function vegrehajtas($kapcsolat, $sql, $parameterek = []) {
return $kapcsolat
->prepare($sql)
->execute($parameterek);
}
$kapcsolat = kapcsolodas(
'mysql:host=localhost;dbname=****;charset=utf8',
'****', '****');
?>
And the page which does the work:
register.php
<?php
include('database.php');
///////////////////////////////////
function letezik($kapcsolat, $felhasznalonev) {
$felhasznalok = lekerdezes($kapcsolat,
"SELECT * FROM `felhasznalok` WHERE `felhasznalonev` = :felhasznalonev",
[ ":felhasznalonev" => $felhasznalonev ]
);
return count($felhasznalok) === 1;
}
function regisztral($kapcsolat, $teljes_nev, $felhasznalonev, $jelszo) {
$db = vegrehajtas($kapcsolat,
"INSERT INTO `felhasznalok` (`teljes_nev`, `felhasznalonev`, `jelszo`)
values (:teljes_nev, :felhasznalonev, :jelszo)",
[
":teljes_nev" => $teljes_nev,
":felhasznalonev" => $felhasznalonev,
":jelszo" => password_hash($jelszo, PASSWORD_DEFAULT),
]
);
return $db === 1;
}
function validate($post, &$data, &$hibak) {
if (trim($post['nev']) === '') {
$hibak[] = 'Teljes név kötelező!';
}
else {
$data['nev'] = $post['nev'];
}
if (trim($post['email']) === '') {
$hibak[] = 'E-mail cím kötelező!';
} else if (!filter_var($post['email'], FILTER_VALIDATE_EMAIL)) {
$hibak[] = "Hibás e-mail cím!";
} else if (letezik($kapcsolat, $post['email'])) { <========This is line 39, but $kapcsolat was defined in database.php
$hibak[] = "Ehhez az e-mail címhez már tartozik felhasználói fiók!";
}
else {
$data['email'] = $post['email'];
}
$data['jelszo'] = $post['jelszo'];
return count($hibak) === 0;
}
$hibak = [];
if ($_POST) {
if (validate($_POST, $data, $hibak)) {
regisztral($kapcsolat, $data['nev'], $data['email'], $data['jelszo']);
header("Location: index.php");
exit();
}
}
?>
The error only occurs when that part of the if statement runs. I just can't figure out what the problem is.What am I doing wrong?
As I said in a comment, your variable $kapcsolat is defined in your file database.php, but is used in the function validate.
When you create a function, all variables used in it are supposed to be local variables.
I suggest to take this variable as parameter instead of using the global variable, it's more flexible. But if you really want to use this variable, you have to declare $kapcsolat as global.
In register.php you should use:
<?php
function validate($post, &$data, &$hibak) {
global $kapcsolat; //IMPORTANT IS HERE
//...Some code
}
See the global keyword

PHP Object in SQL Select Query

Here is my web service call.
Right now, it's hard coded, but I will stick it behind a User Form.
It's returning an object. How do I use that object with a SQL query? I need to do various Select queries with Products, Manufacturers, in the WHERE criteria I need the contract vehicle ID.
<html>
<head>
<title>Call to Navigator Web Service</title>
</head>
<body>
<?php
$param = array('commodity' => 'LAPTOP', 'placeOfPerformance' => array('location' => 'LSA' , 'lsaStates' => 'NY', 'VA', 'TX', 'oconusStates' => 'ALASKA', 'EMEA'), 'equipmentType' => 'ANY', 'socioEconomicObjective' => 'NONE', 'agencyCode' => '007',);
$client = new SoapClient('https://sso-test.fas.gsa.gov/mpdev/navigator/wsdl');
$results = $client->__soapCall('retrieveContractVehicles', array('parameters' => $param));
print_r($results);
echo ("<br />");
echo ("End of line");
?>
</body>
</html>
class test_object
{
public $contractVehicle = array(
0=>'ITSchedule70',
1=>'ITCommodityProgram'
);
function get_contract()
{
return $this->contractVehicle;
}
}
$var = new test_object(); //let us say this is the part you are getting the result from web service
echo $var->contractVehicle[0]; //this is how you will get ITSchedule70
result:
ITSchedule70
what do you mean by How to insert a query? Do you mean how to save it? I am not sure about the question, but this is how I will insert a query(save to the database)
<?php
define('DB_IP',''); //this is your server's IP/name
define('DB_USERNAME',''); //database username
define('DB_PASSWORD',''); //database password
define('DB_DATABASE',''); //default database to use
class test_object //I do not have the webservice object so I just add this
{
public $contractVehicle = array(
0=>'ITSchedule70',
1=>'ITCommodityProgram'
);
function get_contract()
{
return $this->contractVehicle;
}
}
$var = new test_object(); //lets say this is the variable you will save the result when you invoke the webservice
try
{
//check for connection
$connection = mysqli_connect(DB_IP,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
if(!$connection)
{
$db_conn_err = "Unable to Connect to Database ERROR: ". mysqli_connect_error($connection);
throw new Exception($db_conn_err);
}
}
catch(Exception $e)
{
echo $e->getMessage();
}
$qry_trans = "INSERT INTO `Product`
(
`id`,
`other_column`,
`ContractVehicle`
)
VALUES
(
1, //use your own value depending on your table requirements
'use your own values',
$var->contractVehicle[0] //ITSchedule70
);";
try
{
$result = mysqli_query($connection, $qry_trans ); //execute the query
if( $result )
{
echo 'Successfully saved!';
}
else
{
$err = 'Unable to insert into table err:'.mysqli_error($connection).'<br>';
throw new Exception($err);
}
}
catch(Exception $e)
{
echo $e->getMessage();
}
?>
UPDATE BASED ON YOUR COMMENT
If the data changes, you might want to know which index in the webservice you want to find,
echo $var->contractVehicle[2]; //will return OtherContractVehicle
you might want to clarify your question or atleast post your sample data so that I can analyse it more.

php fluentpdo -> Undefined variable: fpdo

I am confused with the include stuff i think, I don't know where exactly its wrong.
The Connection file with fluentpdo
<?php
error_reporting(E_ALL | E_STRICT);
include($_SERVER['DOCUMENT_ROOT'].'/Mark20/libs/FluentPDO/FluentPDO.php');
$pdo = new PDO("mysql:dbname=ummah", "pluto","admin");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$pdo->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
$fpdo = new FluentPDO($pdo);
//~ $software->debug = true;
?>
if i am using to insert data like this as below:
Insert.php
<?php
include '../connect.inc.php';
function inReg(){
try{
$values = array('name' 'xyz', 'pwd' => '1234');
$query = $fpdo->insertInto('users')->values($values)->execute();
echo 'success';
return;
}catch (Exception $e) {
die ('File did not upload: ' . $e->getMessage());
}
}
?>
Not a problem with above stuff, its just in a php file. What I am trying to do is use a class as i did below:
Connection file is same.
DBInsert.php
<?php
include($_SERVER['DOCUMENT_ROOT'].'/Mark20/bin/connect.inc.php');
class DBInsert {
function Insert($table, $values){
try{
$query = $fpdo->insertInto($table)->values($values)->execute();
return 'success';
}catch (Exception $e) {
die ('File did not upload: ' . $e->getMessage());
}
}
}
?>
now i am creating object of above class and trying to call the Insert function like this:
Test.php
include($_SERVER['DOCUMENT_ROOT'].'/Mark20/bin/dao/DBInsert.php');
function Signup(){
$values = array('name' => 'xyz', 'pwd' => '1234');
$db = new DBInsert();
echo $db->Insert('users',$values);
}
Signup();
?>
So when i am accessing Test.php i am getting the following error:
Notice: Undefined variable: fpdo in E:\Program Files\Apache Software
Foundation\Apache2.2\htdocs\Mark20\bin\dao\DBInsert.php on line 15
Fatal error: Call to a member function insertInto() on a non-object in
E:\Program Files\Apache Software
Foundation\Apache2.2\htdocs\Mark20\bin\dao\DBInsert.php on line 15
I am new to php, not totally new also :). So a little help is greatly appreciated.
Thanks and Regards
Adeeb
Global variables are not in scope in functions by default. You need to do:
function inReg(){
global $fpdo;
try{
$values = array('name' 'xyz', 'pwd' => '1234');
$query = $fpdo->insertInto('users')->values($values)->execute();
echo 'success';
return;
}catch (Exception $e) {
die ('File did not upload: ' . $e->getMessage());
}
}
or pass $fpdo as a parameter to the function.

PHP + MongoHQ : MongoCursorException

I'm trying to use mongodb with PHP.
For that, I have created a MongoHQ instance, but for some reasons when I try to insert something or any other operation from my php server I get the following error:
Fatal error: Uncaught exception 'MongoCursorException' with message 'unauthorized for db [datab] lock type: -1 ' in C:\Program Files\EasyPHP5.3.0\www\application\controllers\Stat.ctrl.php:56
Stack trace:
#0 C:\Program Files\EasyPHP5.3.0\www\application\controllers\Stat.ctrl.php(56): MongoCursor->rewind()
#1 C:\Program Files\EasyPHP5.3.0\www\index.php(105): Stat->index()
#2 {main} thrown in C:\Program Files\EasyPHP5.3.0\www\application\controllers\Stat.ctrl.php on line 56
Does anyone know where it can be coming from?
This is the php code I'm using:
$username = 'test';
$password = 'test';
try
{
$link = new Mongo( "flame.mongohq.com:27022/datab -u <".$username."> -p <".$password.">" );
//MongoDB::authenticate ( $username , $password )
//$link = new Mongo();
}
catch(MongoConnectionException $e)
{
die('Could not connect. Check to make sure MongoDB is running.');
}
$db = $link->datab;
$col = $db->order;
try
{
// Insert a document (row) into the collection (table)
$doc = array('login' => 'jsmith', 'password' => ' 5f4dcc3b5aa765', 'email' => 'jsmith#example.com');
$col->insert($doc, true);
$doc = array('login' => 'psmith', 'password' => ' 5f4dcc3b', 'email' => 'psmith#example.com');
$col->insert($doc, true);
}
catch(MongoCursorException $e)
{
echo 'Je suis la!';
}
// Get the id of last insert
$id = $doc['_id'];
// Get all documents
$res = $col->find();
echo 'All documents:<br/>';
foreach($res as $doc)
{
echo '<pre>';
print_r($doc);
echo '</pre>';
}
// Query for the document matching the last insert ID
$doc = $col->findone(array('_id' => $id));
echo 'Single document (_id = $id):<br/><pre>';
print_r($doc);
// Update a document
$col->update(array('_id' => $id), array('$set' => array('password' => 'b497dd1a701a33033620780d')));
// Query the updated docuemnt
$doc = $col->findone(array('_id' => $id));
echo 'Updated docuement:<br/><pre>';
print_r($doc);
echo '</pre>';
That is not the connection format MongoDB uses. See http://www.php.net/manual/en/mongo.construct.php.
You probably need to change it to something like:
$m = new Mongo("mongodb://$username:$password#flame.mongohq.com:27022/datab");

Categories