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");
Related
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
I'm trying to connect to a SOAP web service but I'm getting an error.
This is the error I'm getting:
Fatal error: Uncaught SoapFault exception: [Client] SoapClient::SoapClient(): Invalid parameters in /public_html/wp-content/themes/startuply-child/functions.php:901
Here is the code:
if(isset($_POST['input_1']))
{
require_once('lib/nusoap.php');
$proxyhost = '';
$proxyport = '';
$proxyusername = '';
$proxypassword = '';
$client = new soapclient('http://abr.business.gov.au/abrxmlsearch/ABRXMLSearch.asmx?WSDL', 'true', $proxyhost, $proxyport, $proxyusername, $proxypassword);
$err = $client->getError();
if ($err)
{
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
}
// Doc/lit parameters get wrapped
$param = array('searchString' => '',
'includeHistoricalDetails' => 'N',
'authenticationGuid' => '');
$result = $client->call('ABRSearchByABN', array('parameters' => $param), '', '', false, true);
// Check for a fault
if ($client->fault)
{
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
} else
{
// Check for errors
$err = $client->getError();
if ($err)
{
// Display the error
echo '<h2>Error</h2><pre>' . $err . '</pre>';
} else
{
$OutputGUID = $result['ABRPayloadSearchResults']['request']['identifierSearchRequest']['authenticationGUID'];
$OutputABN = $result['ABRPayloadSearchResults']['response']['businessEntity']['ABN']['identifierValue'];
$OutputABNStatus = $result['ABRPayloadSearchResults']['response']['businessEntity']['entityStatus']['entityStatusCode'];
$OutputASICNumber = $result['ABRPayloadSearchResults']['response']['businessEntity']['ASICNumber'];
$OutputEntityName = $result['ABRPayloadSearchResults']['response']['businessEntity']['mainName']['organisationName'];
$OutputTradingName = $result['ABRPayloadSearchResults']['response']['businessEntity']['mainTradingName']['organisationName'];
$OutputLegalName = $result['ABRPayloadSearchResults']['response']['businessEntity']['legalName']['givenName'] . " " .
$result['ABRPayloadSearchResults']['response']['businessEntity']['legalName']['otherGivenName'] . " " .
$result['ABRPayloadSearchResults']['response']['businessEntity']['legalName']['familyName'];
$OutputOrganisationType = $result['ABRPayloadSearchResults']['response']['businessEntity']['entityType']['entityDescription'];
$OutputState = $result['ABRPayloadSearchResults']['response']['businessEntity']['mainBusinessPhysicalAddress']['stateCode'];
$OutputPostcode = $result['ABRPayloadSearchResults']['response'] ['businessEntity']['mainBusinessPhysicalAddress']['postcode'];
echo $OutputEntityName;
}
}
}
I'm trying to make a form which sends an ABN to the ABN lookup tool and then returns certain fields but I can't seem to connect to it. I think it is something to do with the Proxy log in details. I don't know if i am meant to set these as something. I have SOAP installed on the server but I am using nuSOAP.
Any help would be greatly appreciated.
Cheers,
Jordan
You are using nuSOAP, update here -
From:
$client = new soapclient('http://abr.business.gov.au/abrxmlsearch/ABRXMLSearch.asmx?WSDL',
'true', $proxyhost, $proxyport, $proxyusername, $proxypassword);
To:
$client = new nusoap_client('http://abr.business.gov.au/abrxmlsearch/ABRXMLSearch.asmx?WSDL',
'true', $proxyhost, $proxyport, $proxyusername, $proxypassword);
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.
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.
It's whining of line 6: Warning: PDO::__construct() expects parameter 2 to be string, array given
Along with a line 7 error:
Fatal error: Call to a member function prepare() on a non-object in
How do I fix this? I've tested the query and it works fine..
<?php
## Loop through results from mysql
try{
#connection string
$dbconn = new PDO('mysql:host=localhost;port=3306;dbname=thedb',array(PDO::ATTR_PERSISTENT => true));
$q = $dbconn->prepare("SELECT thecol FROM thetbl");
#call stored proc
$q->execute();
#get the rows into an array
$result = $q->fetchAll();
foreach($result as $r){
$xmlUrl = $r['FW_ArtSrcLink'];
$ConvertToXml = simplexml_load_file($xmlUrl);
# -> Setup XML
$newsStory = $ConvertToXml->channel->item;
}
# -----> Load News Stories
for($i = 0;$i<sizeof($newsStory); $i++){
# Source of Article Info-->
$SrcTitle=$newsStory[$i]->title;
$SrcLink=$newsStory[$i]->link;
# Actual News Article Info -->
$title=$newsStory[$i]->title;
$desc=$newsStory[$i]->description;
# Output Results ------------>
echo '<hr>';
echo '<strong>'.'Title:'.$title.'</strong>'.'(via: <a href=\''.$SrcLink.'\'>'.$SrcTitle.'</a>'.'<br />';
//echo 'Link:'.$link.'<br />';
echo 'Description'.$desc.'<br>';
echo '<hr>';
}
} // try
catch(Exception $e){
$errorStored = $e->getMessage() . ' on ' .'/errors/fanwire_loop.php'; #where errors are stored
$pageDateOfError = '/aggregate_looping.php'.date('l jS \of F Y h:i:s A'); #inc the file and date into the file too
file_put_contents($errorStored,$pageDateOfError, FILE_APPEND | LOCK_EX);
} // catch
#Load in File
/*************************************************
$xmlUrl ="http://sports.espn.go.com/espn/rss/mlb/news";
$ConvertToXml = simplexml_load_file($xmlUrl);
# -> Setup XML
$newsStory = $ConvertToXml->channel->item;
# -----> Load News Stories
for($i = 0;$i<sizeof($newsStory); $i++){
// Source of Article Info-->
$SrcTitle=$newsStory[$i]->title;
$SrcLink=$newsStory[$i]->link;
// Actual News Article Info -->
$title=$newsStory[$i]->title;
$desc=$newsStory[$i]->description;
echo '<hr>';
echo '<strong>'.'Title:'.$title.'</strong>'.'(via: <a href=\''.$SrcLink.'\'>'.$SrcTitle.'</a>'.'<br />';
//echo 'Link:'.$link.'<br />';
echo 'Description'.$desc.'<br>';
echo '<hr>';
}
***********************************************/
?>
You're initializing the PDO object incorrectly, the second parameter of the constructor should be the username, not an array of options.
$dbconn = new PDO('mysql:host=localhost;port=3306;dbname=thedb',array(PDO::ATTR_PERSISTENT => true));
should be,
$dbconn = new PDO('mysql:host=localhost;port=3306;dbname=thedb',
'yourusername',
'yourpassword',
array(PDO::ATTR_PERSISTENT => true));
See the PHP manual page for PDO::__construct() for more information.
The second error you're getting because the $dbconn object wasn't created properly due to the first error.
Can u try
$dbconn = new PDO('mysql:host=localhost;port=3306;dbname=thedb');
$q = $dbconn->prepare("SELECT thecol FROM thetbl", array(PDO::ATTR_PERSISTENT => true));