I'm new to php and I'm writing a test function to test a class I have already written. However, I'm not sure how I should properly make a call to the function assertTrue().
Here is the code I have:
<?php
require_once(dirname(__FILE__) . '/simpletest/autorun.php');
require_once('../db/fileToBeTested.php');
class TestDbManager extends UnitTestCase {
function TestDbManager(){
$this->UnitTestCase("Test DB Manager");
}
// Function to test if isTableExisting() method works correctly
function testIsTableExisting() {
$testDB = new DB("localhost", "root", "password", "GraphAppDB", "3306", "empty#empty.com", true, "GraphApp")
$this->assertTrue($testDB->isTableExisting("users"), "users table exists");
$this->assertFalse($testDB->isTableExisting("notAValidTable"), "notAValidTable does not exist");
$this->assertFalse($testDB->isTableExisting(""));
}
}
?>
And here is the error I am getting:
Parse error: syntax error, unexpected '$this' (T_VARIABLE) in
/Applications/XAMPP/xamppfiles/htdocs/GraphApp/tests/TestDbManager.php
on line 14
You're missing a ; after
$testDB = new DB("localhost", "root", "password", "GraphAppDB", "3306", "empty#empty.com", true, "GraphApp")
The call to assertTrue is probably fine.
Related
I am currently looking at improving my PHP knowledge and creating websites to a better extent by using classes and such but I've ran into an issue when trying to allow other classes in separate files to access the PDO connection that I've sent up. I've tried hundreds of resolutions which have been inputted onto this site but can't seem to figure it out at all and can't seem to understand where I'm going wrong.
I'm being met with the following error:
[16-Sep-2022 11:05:02 UTC] PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Kit\core::__construct(), 0 passed in /home/liamapri/public_html/kit/global.php on line 24 and exactly 1 expected in /home/liamapri/public_html/kit/app/class.core.php:11
Stack trace:
#0 /home/liamapri/public_html/kit/global.php(24): Kit\core->__construct()
#1 /home/liamapri/public_html/index.php(3): include_once('/home/liamapri/...')
#2 {main}
thrown in /home/liamapri/public_html/kit/app/class.core.php on line 11
I have a global.php file which will be added to each individually page such as /home /index etc, it references all the files that I'll need and starts the session from it, see below:
error_reporting(E_ALL ^ E_NOTICE);
define('C', $_SERVER["DOCUMENT_ROOT"].'/kit/conf/');
define('A', $_SERVER["DOCUMENT_ROOT"].'/kit/app/');
define('I', 'interfaces/');
// Management
require_once C . 'config.php';
// Interfaces
require_once A . I . 'interface.engine.php';
require_once A . I . 'interface.core.php';
require_once A . I . 'interface.template.php';
// Classes
require_once A . 'class.engine.php';
require_once A . 'class.core.php';
require_once A . 'class.template.php';
// OBJ
$engine = new Kit\engine();
$core = new Kit\core();
$template = new Kit\template();
// Start
session_start();
$template->Initiate();
This references the class.engine.php first which is where I have created the database connection class, as shown below:
namespace Kit;
use PDO;
if(!defined('IN_INDEX')) { die('Sorry, this file cannot be viewed.'); }
class engine
{
public $pdo;
public function __construct()
{
global $_CONFIG;
$dsn = "mysql:host=".$_CONFIG['mysql']['hostname'].";dbname=".$_CONFIG['mysql']['database'].";charset=".$_CONFIG['mysql']['charset'].";port=".$_CONFIG['mysql']['port'].";";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$this->pdo = new PDO($dsn, $_CONFIG['mysql']['username'], $_CONFIG['mysql']['password'], $options);
} catch (\PDOException $e) {
print "<b>An error has occurred whilst connecting to the database:</b><br />" . $e->getMessage() . "";
die();
}
}
}
$connection = new engine();
I'm then trying to run a PDO query on another class (class.core.php) and keep getting met with either a PDO can't be found error or the one described above.
See the file below:
namespace Kit;
if(!defined('IN_INDEX')) { die('Sorry, this file cannot be viewed.'); }
class core implements iCore
{
public $connection;
public function __construct($connection)
{
$this->connection = $connection;
}
public function website_settings()
{
$qry = $this->connection->pdo->prepare("SELECT `website_name` FROM `kit_system_settings`");
$qry->execute([]);
if ($qry->rowCount() == 1) { while($row = $qry->fetch()) { return $row; } }
}
}
Sorry if this is a simple fix but I really can't see where I'm going wrong.
Look in your global .php on Line 24 (its probably this line: $core = new Kit\core();)
In your class.core.php you tell the constructor that it will get a connection, but in your global.php you dont give constructor (when you initialize a class) any argument.
That's what this error is telling you
PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Kit\core::__construct(), 0 passed
Just guessing, but i think
$core = new Kit\core($engine->pdo);
will fix your issue.
i am following a tutorial to create an OOP based login system.I did everything accordingly but while creating pdo i am getting an error in DB.php file in line 15.Can't figure out the reason for this error.Been stuck there for some time.Can anyone help me out with this error .The code might look long but it is a piece of cake for you i promise.There are FOUR php files.
1.init.php file holds the ingredients to create a new PDO() object.
2.config.php file is used to get data from init.php file as string is passed to it as ('mysql/host') type and use explode() function to extract data from it.
2.DB.php file is used to connect to database.
The error i am getting is
DB.php file:
class DB{
private $_instance=null;
private $pdo,
$query,
$error=false,
$results,
$count=0;
private function __construct(){
try{
$this->$pdo=new PDO('mysql:host='.Config::get('mysql/host').';dbname='.Config::get('mysql/db'),Config::get('mysql/user'),Config::get('mysql/password'));
}catch(PDOException as $e){
echo $e->getMessage();
}
}
public static function getInstance(){
if(!isset(self::$_instance)){
self::$_instance=new DB();
}
return self::$_instance;
}
}
Config.php file:
class Config{
public static function get($path){
if($path){
$config=$GLOBALS['config'];
$arr=explode('/',$path);
foreach($arr as $bit){
if(isset($config[$bit])){
$config=$config[$bit];
}
}
return $config;
}
}
}
init.php file:
session_start();
$GLOBALS['config']=array(
'mysql'=>array(
'host' => 'localhost',
'db' => 'login',
'user' => 'root',
'password' => ''
)
);
spl_autoload_register(function($class){
require_once 'c:/xampp/htdocs/login/classes/'.$class.'.php';
});
require_once 'c:/xampp/htdocs/login/function/sanitize.php';
index.php file:
require_once 'c:/xampp/htdocs/login/core/init.php';
DB::getInstance()->query('SELECT name FROM table WHERE id=1');
Your error message is a Parse Error. This means the PHP interpreter/processor/program tried to read your file, but found a syntax error, and had to stop. If you look at Line 15 of DB.php (per the error message)
}catch(PDOException as $e){
You'll see the problem. This isn't valid PHP syntax -- you probably want
}catch(PDOException $e){
The PDOException bit of that is a a class type hint for the exception handling code -- there's no need to use the as.
I'm using this code inside the public function __construct() of a class:
$this->mConnection = mysql_connect(BASE_DB_HOST,BASE_DB_USER,BASE_DB_PASS) or throw new Exception("Couldn't connect to database.");
BASE_DB_HOST, BASE_DB_USER and BASE_DB_PASS are defined. I get the following error:
Parse error: syntax error, unexpected T_THROW in /home/... on line 6
Am I not allowed to use the or construction with Exceptions? How can I workaround this?
Try using like this and let me know if its work for you or not-
<?php
function throwException() {
throw new Exception("Couldn't connect to database.");
}
$this->mConnection = mysql_connect(BASE_DB_HOST,BASE_DB_USER,BASE_DB_PASS) OR throwException();
?>
Reference - http://www.php.net/manual/en/language.exceptions.php#81960
Another way is to throw an exception in an anonymous function after the or logical operator.
$this->mConnection = mysql_connect(BASE_DB_HOST,BASE_DB_USER,BASE_DB_PASS) or call_user_func(function() { throw new Exception("Couldn't connect to database."); });
session.php
include("database.php");
function addPOTW($subweek, $subtitle, $subcaption, $subsubmittedby)
{
global $database, $form;
/* Errors exist, have user correct them */
if ($form->num_errors > 0) {
return 1; // Errors with form
}
/* No errors, add the new POTW to the database */
else {
if ($database->addNewPOTW($subweek, $subtitle, $subcaption, $subsubmittedby, $subfile)) {
return 0; //Event signup added succesfully
} else {
return 2; //Event signup attempt failed
}
}
}
This is my function, "addPOTW", located in the file session.php (with useless parts redacted). For some reason, I keep getting the error message: "Fatal error: Call to undefined method MySQLDB::addNewPOTW()" even though it's defined right here:
database.php
class MYSQLDB {
function addNewPOTW($date, $title, $caption, $submitter, $filepath)
{
$q = "INSERT INTO `" . TBL_POTW . "` VALUES ('','$date','$title','$caption','$submitter','$filepath')";
return mysql_query($q, $this->connection);
}
}
I have other functions in session.php accessing functions in database.php using the $database variable in the exact same way, and they work perfectly fine. Any ideas why only this one function is being reported as undefined??
Because you are referring to $this, you would need to instantiate an object from that class and then call the method.
Something like this should get it working...
$database = new MYSQLDB;
Make sure you have it in scope before your addPOTW() function.
I have a wsdl file and i am trying to call it from a php class. I am using the following code:
<?php
include ("dbconn.php");
class dataclass
{
function getCountries()
{
$connection = new dbconn();
$sql = "SELECT * FROM tblcountries";
$dataset = $connection -> connectSql($sql);
return $dataset;
}
function getTest()
{
$connection = new dbconn();
$sql = mysql_query('CALL sp_getTest');
$dataset = $connection -> connectSql($sql);
return $dataset;
}
##-------------------------------------------CUSTOMER METHODS-------------------------------------------
function registerCustomer($username,$name,$surname,$password,$email,$country,$tel)
{
$connection = new dbconn();
$sql="INSERT INTO tblcustomer (customer_username, customer_password, customer_name, customer_surname,
customer_email, customer_country, customer_tel)
VALUES('$username','$name','$surname','$password','$email','$country','$tel')";
$dataset = $connection -> connectSql($sql);
}
ini_set("soap.wsdl_cache_enabled", "0");
// start the SOAP server - point to the wsdl file
$webservice = new SoapServer("http://localhost/dataobjects/myWebservice.wsdl", array('soap_version' => SOAP_1_2));
// publish methods
$webservice->addFunction("getCountries");
$webservice->addFunction("registerCustomer");
// publish
$webservice->handle();
}
?>
It is all the time giving me a problem with ini_set("soap.wsdl_cache_enabled", "0");
The error is:
Parse error: syntax error, unexpected T_STRING, expecting T_FUNCTION in C:\Program Files\xampplite\htdocs\dataobjects\dataClass.php on line 47
I believe it is because you have ini_set() call in the body of your class. Put it at the top of the file or in the constructor if you have one.
class dataClass
{
function registerCustomer()
{
// some stuff
}
ini_set(/*args*/); // it's illegal to put instructions in the body of the class
}
Now I see the whole thing. You probably want to close the class with a closing backet before line 47.
You let the parser think "0" is a string, and not a number, please remove the quotes!
Edit 1 If that wouldn't work, your error must be before that line, please post the full code for review.
Edit 2 The code you provided was running inside the class, you miss a bracket before the line with ini_set.
Move the last } in front of ini_set(...)
By the way, you said you want to call a web service, but you are creating a server which may be called by others.
To call a web service, try something like this:
try{
$client = new SoapClient($service, array('location' =>"http://example.org/myWebService"));
$parameter1 = new myWebServiceParameter();
$result = $client->myWebServiceFunction($parameter1);
} catch (Exception $e) {
// handle errors
}
myWebServiceParameter must be any class with a member variable foreach WSDL message attribute of the same name.
And myWebServiceFunction is the name of the web service method.