I know that it's not the main idea of this site to answer such kind of questions but in couple of days I'll have the chance to apply for a junior (or maybe more correctly a probationer) position as a PHP programmer and that's why I decided to post here, hoping it will turn out good.
The company is some kind of big compared to others here, so it's well known what is the exam for people wanting to get in this position - it's either - writing a pagination script or some sort of SOAP service.I have no problem with the pagination, but since now I have never payed too much attention to SOAP and now I need to learn tha basics ot SOAP service when used with PHP.Giving the postion I'm applying for, noone expect to show something brilliant but I still I need basic understanding of SOAP client and server sevices, maybe I won't even bother for now about WSDL since I don't think I have enough time for everything.
So I have a sample code that is most likely what I'll need to write and explain If I'm to write SOAP service :
Client side -
<?php
if (isset($_REQUEST["cname"]) && isset($_REQUEST["cpass"]))
{
$cname = $_REQUEST["cname"];
$md5pass = md5( $_REQUEST["cpass"]);
$client = new SoapClient(null, array(
'location' => "http://localhost/test/BuildInSoapWithWSDL/server.php",
'uri' => "urn://localhost/test/BuildInSoapWithWSDL/",
'trace' => 1 ));
try
{
if ( $client->saveUserNameAndPass($cname, $md5pass))
{echo "Data updated!";}
else
{echo "Error updating data!";}
print "<pre>\n";
print "Request :\n".htmlspecialchars($client->__getLastRequest()) ."\n";
print "Response:\n".htmlspecialchars($client->__getLastResponse())."\n";
print "</pre>";
}
catch (Exception $e)
{
echo 'Exception: ', $e->getMessage(), "\n";
}
}
else
{
echo "Error!";
}
?>
server side -
<?php
$server = new SoapServer(null, array('uri' => 'urn://localhost/test/BuildInSoapWithoutWSDL/'));
$server->addFunction("saveUserNameAndPass");
$server->handle();
function database_connect($host, $account, $password, $dbname)
{
$connect = mysql_connect($host, $account, $password);
$connect = mysql_select_db($dbname, $connect);
return $connect;
}
function saveUserNameAndPass($userName,$passWord)
{
try
{
if (database_connect("localhost", "saveuser", "123456", "savetask") == 1)
{
$userName = mysql_real_escape_string($userName);
$sql = "INSERT INTO accounts (name,passmd5) VALUES ('".$userName."','".$passWord."')";
$result = mysql_query($sql);
mysql_close();
if ($result)
{ return true;}
else
{ return false;}
}
else
{
return false;
}
}
catch (Exception $e)
{
return false;
}
}
?>
Even I have the code I still have poor knowledge of what do what.So I need some explanation ot the basics when writing SOAP service and if it's not acceptable this topci to be discussed here I would appreciate any kind of source where these thing are explained from the point of beginner.
Thanks
SOAP is used just the same as you interact with MySQL database. I can give you real life example, for connections to Atlassian JIRA web application.
At first, you just make connection. You will need an WSDL file, that contains all the stuff, that contains every function that this specific SOAP server allows you to do:
try { $soapObject = new SoapClient('http://jira/rpc/soap/jirasoapservice-v2?wsdl'); }
catch(Exception $ex) { die('SOAP connection failed: '$ex->getMessage()); }
After connection has been made, you just use it. If it is needed, login:
$authToken = $soapObject->login(JIRA_LOGIN, JIRA_PASS);
Then send requests to server:
$jqlquery = "status not in (Closed,Resolved) and assignee = user");
try { $issues = $soapObject->getIssuesFromJqlSearch($authToken, $jqlquery, 20); }
catch(Exception $ex) { die('JIRA query failed: '$ex->getMessage()); }
Work on results:
foreach ($issues as $k => $v) { $users[$v->reporter] = array('fullname'=>$soapObject->getUser($authToken,$v->reporter)->fullname,'name'=>$v->reporter); }
$project = $soapObject->getProjectByKey($authToken,"PROJECT");
Note that getIssuesFromJqlSearch, getUser, getProjectByKey and others, are application-specific commands (in this case, all methods/functions are described in JIRA RPC plugin documentation).
That's it. You don't need to "disconnect", afaik when loading finishes, destructor is called, that closes connection by itself.
Related
My .php includes quote.php followed with the rest of the page.
When the connection fails, I see "Fatal error: Uncaught mysqli_sql_exception: ----- include_once('C:\xampp\htdocs...') ----
and the remainder of the page does not load.
What must I do to display an error message, THEN the rest of my page?
Your situation is a rare case when using a try catch is justified.
All you need to do it wrap the include in a try-catch:
try {
require 'quote.php';
} catch(\Throwable $e) {
error_log($e); // for the future inspection
echo "Problem loading this part of page";
}
That's all. The error message will be shown and the rest of the page will be loaded.
But of course this approach should only be used when the content from quote.php is optional. In the every other case there must be no local try-catch but a site-wide error handler.
php / msqli is throwing exceptions. You need to write exception handler code (try { } catch (mysqli_sql_exception $e) { } code in your program to handle errors.
As a quick and sleazy workaroud for the current state of your code you can put this line of code at the top of your page. give this line of code
mysqli_report(MYSQLI_REPORT_OFF):;
This will suppress php exceptions and warnings, and let you rely completely on mysqli_connect_errno() to catch your errors.
Using #O. Jones idea and some nasty GoTO's, this does the job. The warnings and error are still displayed. The rest of the page is able to load now.
<?php
mysqli_report(MYSQLI_REPORT_OFF);
$dbServer = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "project_01";
$conn = mysqli_connect($dbServer, $dbUsername, $dbPassword, $dbName);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to the MySQL Database: ";
goto end;
}
$sql = "SELECT * FROM tbl_quotes";
if ($result=mysqli_query($conn,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
$rand = random_int(1,$rowcount);
} else {
echo "No records were found";
goto end;
}
$sql = "SELECT quote, credit FROM tbl_quotes where ID = $rand";
if ($result = mysqli_query($conn, $sql)) {
// Fetch one and one row
while ($row = mysqli_fetch_row($result)) {
printf ("%s" . " - " . "(%s)\n", $row[0], $row[1]);
}
// Free result set
mysqli_free_result($result);
}
end:
?>
Thanks to all who looked.
I'd like my PHP script (using PDO) to detect whether or not a target database is in the middle of a restore process other than waiting several minutes for a response from a failed connection.
My database connection code eventually returns the message below if a database is being restored, but it happens because the connection fails and it takes several minutes to respond when this happens. Searching on StackOverflow and Google doesn't seem to find anything that fits my need, nor does searching through PHP's documentation.
function getParameterizedPDOConnection($host = false, $overrideOptions = []) {
include(INCLUDE_DIR . "/itrain.config.php");
$host = strtolower($_SERVER["HTTP_HOST"]);
if (count($overrideOptions) > 0) {
$configOptions["host"][$host] = $overrideOptions;
}
$sthUserName = $configOptions["userName"];
$pwd = $configOptions["pwd"];
$addr = $configOptions["host"][$host]["addr"];
$db = $configOptions["host"][$host]["db"];
try {
$pdo = new PDO("sqlsrv:Server=$addr;Database=$db;ConnectionPooling=0", $sthUserName, $pwd, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT));
return($pdo);
} catch (PDOException $e) {
return "Database connection failure: " . $e->getMessage();
}
}
Returns: "42000",927,"[Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Database 'Workforce' cannot be opened. It is in the middle of a restore.
I am using laravel 5.7 and mongo db(v1.5.3 stable).
I am trying to test connection from laravel to db but everytime I am getting successfull connection even I am providing wrong credentials.
I have tried by the following ways:
Jessengers
$arrMongo = [];
if(true == DB::connection('mongodb')) {
$arrMongo = array(
'status'=>true,
'message' => 'Mongo connection OK'
);
}else{
$arrMongo = array(
'status'=>false,
'message' => 'Mongo connection failed'
);
}
Normal PHP way
$server = "mongodb://google.com:27017/university";
$c = new \MongoDB\Client( $server );
if($c->connected)
echo "Connected successfully";
else
echo "Connection failed";
I am never getting as connection failed while testing with wrong credentials.
Please help me to resolve this problem.
Laravel only connects to the database when it needs something from the database.
You may opt for getting the list of databases inside try/catch block as follow:
try {
DB::connection()->getMongoClient()->listDatabases();
} catch (\Exception $e) {
echo $e->getMessage();
}
I am trying to list data from two specific columns in a table. Whenever I go to the file, it returns a server error. When I remove the while loop, it executes perfectly, so I have no idea what I am doing wrong.
Here's the error:
Server error The website encountered an error while retrieving
http://dayzlistings.com/reg-whitelist.php. It may be down for
maintenance or configured incorrectly. Here are some suggestions:
Reload this webpage later. HTTP Error 500 (Internal Server Error): An
unexpected condition was encountered while the server was attempting
to fulfill the request.
try {
$dbh = new PDO('mysql:host=localhost;dbname=dbname','dbuser','dbpass');
$sql = "SELECT * from wp_cimy_uef_data";
$q = $dbh->prepar($sql);
$q->execute();
while($row = $q->fetchall() {
echo $row['USER_ID'];
echo $row['VALUE'];
}
}
$dbh = null;
} catch (PDOException $e) {
print "Error from Dedicated Database!: " . $e->getMessage() . "<br/>";
die();
}
500 means something wrong when you interact with the server, e.g. access db.
And $row['USER_ID'] will never work, instead you should use $row[0]['USER_ID'].
isn't fetchAll() returns the whole table as an array?..
you don't need to while loop $row.. just do $row = $q->fetchAll() without while and print_r the whole array and see what you get..
and if you still wanna do while I think you may use
while($row = $q->fetch()){
// rest of the code here
}
Also you cannot put annything between try catch..
try{
//code
}
$dbh = null; //**This is not allowed by the way...**
catch(PDOException $e){
//code
}
Dins
I have access to the webservice of an website which allow you to get a user information if you know his username and security code. I tried to do this with a simple test, but I always recieve the message "unknown username or wrong security-code", although the information is correct.
Any idea what is wrong with this code?
<?php
$client = new SoapClient('http://handballmania.tk/fx/WebService.wsdl');
$Username = 'icsulescu';
$SecurityCode = 'nusa7maru';
try {
$answer = $client->GetTeam($Username, $SecurityCode);
}
catch (Exception $e) {
echo $e->getMessage();
}
?>
I think the parameters sent should be contained in an array.
...
$user_info["Username"] = "icsulescu";
$user_info["SecurityCode"] = "nusa7maru";
...
$answer = $client->GetTeam($user_info);
...