Undefined variable following a method call [duplicate] - php

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 8 years ago.
I am trying to put myself in OOP and I have a problem with variable scope.
Everything works except a session array and everything posts correctly.
My 'session table' and its elements are declared but its variables remain undefined. I get the following error messages:
Notice: Undefined variable: row
Notice: Trying to get property of non-object
What I can do to get access to $row?
This is my code for the class, including its methods:
$db = db::connect();
class auth {
protected $login;
protected $password;
protected $email;
public function setLogin($login) {
$this->login = $login;
}
public function setPassword($password) {
$this->password = $password;
}
public function login($fields, $table, $col_login, $col_password) {
$query = Db::getInstance()->prepare('SELECT ' . $fields . ' FROM ' . $table . ' WHERE ' . $col_login . ' = :login AND ' . $col_password . ' = :password');
$query->bindValue( ':login', $this->login, PDO::PARAM_STR);
$query->bindValue(':password', $this->password, PDO::PARAM_STR);
$query->execute();
if ($query->rowCount() > 0) {
$row = $query->fetch(PDO::FETCH_OBJ);
echo '<pre>';
print_r($row->u_login);
echo '</pre>';
return true;
}
else {
return false;
}
$query->closeCursor();
}
}
Here is my form code; this is from where I call the class method:
<?php
session_start();
if (isset($_POST['login_submit'])) {
if (!empty($_POST['login']) && !empty($_POST['password'])) {
$auth = new auth();
$auth->setLogin($_POST['login']);
$auth->setPassword(sha1($_POST['password']));
if ($auth->login('u_login,u_password,u_email,u_id_level', 'users', 'u_login', 'u_password')) {
$_SESSION['back_office'] = array(
'login' => $row->u_login, // Error, $row is undefined
'level' => $row->u_level,
'email' => $row->u_email
);
}
else {
message::showError('Compte non reconnu');
}
}
else {
message::showError('Veuillez remplir tous les champs');
}
}
?>
<form action="test.php" name="loginform" method="post">
<input type="text" name="login" />
<input type="password" name="password" />
<input type="submit" name="login_submit" value="Se connecter" />
</form>

In your auth function you need to return row
if($query->rowCount() > 0){
$row = $query->fetch(PDO::FETCH_OBJ);
return $row;
}else{
return false;
}
In your call assign the return value of login to $row
if (($row = $auth->login('u_login,u_password,u_email,u_id_level', 'users', 'u_login', 'u_password'))) {

You have to return $row instead of return true
$row = $query->fetch(PDO::FETCH_OBJ);
echo '<pre>';
print_r($row->u_login);
echo '</pre>';
return $row; // return true;
And you check like this
if($row = $auth->login('u_login,u_password,u_email,u_id_level',
'users', 'u_login', 'u_password') !== false)
Then you can set value of $row
$_SESSION['back_office'] = array(
'login' => $row->u_login,
'level' => $row->u_level,
'email' => $row->u_email
);

$row is not a global variable so you can't access from outside.
Between it's bad to make it global.
I will suggest you to put a variable called $authenticated_user for example.
Like that :
class auth {
// ...
protected $authenticated_user;
//...
public function login( // ... ) {
// ...
$authenticated_user = $query->fetch(PDO::FETCH_OBJ);
// ...
}
public getUser()
{ return $authenticated_user; }
}
In you Auth call part :
$row = $auth->getUser();
That's should be fine.

Related

Having trouble with PHP project login Issue

SO i have been trying with a php project and everything is working fine.Except a bit extra.
Login page redirects to Dashboard even with incorrect details .So basically login is bypassed regardless the login details. Also By putting "sitename/dashboard" directly also bypasses the login. Below Are my Code.
1.index(login page)
<?php
require('inc/dbPlayer.php');
require('inc/sessionManager.php');
$msg="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST["btnLogin"])) {
$db = new \dbPlayer\dbPlayer();
$msg = $db->open();
if ($msg == "true") {
$userPass = md5("hms2015".$_POST['password']);
$loginId = $_POST["email"];
$query = "select loginId,userGroupId,password,name,userId from users where loginId='" . $loginId . "' and password='" . $userPass . "';";
var_dump($query);
$result = $db->getData($query);
//var_dump($result);
$info = array();
while ($row = mysql_fetch_assoc($result)) {
array_push($info, $row['loginId']);
array_push($info, $row['userGroupId']);
array_push($info, $row['password']);
array_push($info, $row['name']);
array_push($info, $row['userId']);
}
//$db->close();
$ses = new \sessionManager\sessionManager();
$ses->start();
$ses->Set("loginId", $info[0]);
$ses->Set("userGroupId", $info[1]);
$ses->Set("name", $info[3]);
$ses->Set("userIdLoged", $info[4]);
if (is_null($info[0])) {
$msg = "Login Id or Password Wrong!";
}
else
{
}
if($info[1]=="UG004")
{
header('Location: http://localhost/hms/sdashboard.php');
}
elseif($info[1]=="UG003")
{
header('Location: http://localhost/hms/edashboard.php');
}
else
{
header('Location: http://localhost/hms/dashboard.php');
}
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>HMS</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="panel-body">
<form name="login" action="index.php" accept-charset="utf-8" method="post" enctype="multipart/form-data">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="E-mail/Login ID" name="email" type="text" autofocus required>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" value="" required>
</div>
<div class="checkbox">
<label>
<input name="remember" type="checkbox" value="Remember Me">Remember Me
</label>
Forget Password
<label id="loginMsg" class="red"><?php echo $msg ?></label>
</div>
<button type="submit" name="btnLogin" class="btn btn-lg btn-success btn-block"><i class="glyphicon glyphicon-log-in"></i> Login</button>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
2.dbplayer
<?php
namespace dbPlayer;
class dbPlayer {
private $db_host="localhost";
private $db_name="hms";
private $db_user="root";
private $db_pass="";
protected $con;
public function open(){
$con = mysql_connect($this->db_host,$this->db_user,$this->db_pass);
if($con)
{
$dbSelect = mysql_select_db($this->db_name);
if($dbSelect)
{
return "true";
}
else
{
return mysql_error();
}
}
else
{
return mysql_error();
}
}
public function close()
{
$res=mysql_close($this->con);
if($res)
{
return "true";
}
else
{
return mysql_error();
}
}
public function insertData($table,$data)
{
$keys = "`" . implode("`, `", array_keys($data)) . "`";
$values = "'" . implode("', '", $data) . "'";
//var_dump("INSERT INTO `{$table}` ({$keys}) VALUES ({$values})");
mysql_query("INSERT INTO `{$table}` ({$keys}) VALUES ({$values})");
return mysql_insert_id().mysql_error();
}
public function registration($query,$query2)
{
$res=mysql_query($query);
if($res)
{
$res=mysql_query($query2);
if($res)
{
return "true";
}
else
{
return mysql_error();
}
}
else
{
return mysql_error();
}
}
public function getData($query)
{
$res = mysql_query($query);
if(!$res)
{
return "Can't get data ".mysql_error();
}
else
{
return $res;
}
}
public function update($query)
{
$res = mysql_query($query);
if(!$res)
{
return "Can't update data ".mysql_error();
}
else
{
return "true";
}
}
public function updateData($table,$conColumn,$conValue,$data)
{
$updates=array();
if (count($data) > 0) {
foreach ($data as $key => $value) {
$value = mysql_real_escape_string($value); // this is dedicated to #Jon
$value = "'$value'";
$updates[] = "$key = $value";
}
}
$implodeArray = implode(', ', $updates);
$query ="UPDATE ".$table." SET ".$implodeArray." WHERE ".$conColumn."='".$conValue."'";
//var_dump($query);
$res = mysql_query($query);
if(!$res)
{
return "Can't Update data ".mysql_error();
}
else
{
return "true";
}
}
public function delete($query)
{
$res = mysql_query($query);
// var_dump($query);
if(!$res)
{
return "Can't delete data ".mysql_error();
}
else
{
return "true";
}
}
public function getAutoId($prefix)
{
$uId="";
$q = "select number from auto_id where prefix='".$prefix."';";
$result = $this->getData($q);
$userId=array();
while($row = mysql_fetch_assoc($result))
{
array_push($userId,$row['number']);
}
// var_dump($UserId);
if(strlen($userId[0])>=1)
{
$uId=$prefix."00".$userId[0];
}
elseif(strlen($userId[0])==2)
{
$uId=$prefix."0".$userId[0];
}
else
{
$uId=$prefix.$userId[0];
}
array_push($userId,$uId);
return $userId;
}
public function updateAutoId($value,$prefix)
{
$id =intval($value)+1;
$query="UPDATE auto_id set number=".$id." where prefix='".$prefix."';";
return $this->update($query);
}
public function execNonQuery($query)
{
$res = mysql_query($query);
if(!$res)
{
return "Can't Execute Query".mysql_error();
}
else
{
return "true";
}
}
public function execDataTable($query)
{
$res = mysql_query($query);
if(!$res)
{
return "Can't Execute Query".mysql_error();
}
else
{
return $res;
}
}
}
3.Session manager
<?php
namespace sessionManager;
class sessionManager {
public function Set($key,$value)
{
$_SESSION[$key] = $value;
// $_SESSION['start'] = time();
// $_SESSION['expire'] = $_SESSION['start'] + (30 * 60);
}
public function Get($key)
{
// session_start();
if(isset($_SESSION[$key])) {
return $_SESSION[$key];
}
else
{
return null;
}
}
public function isExpired()
{
//session_start();
$now = time();
if ($now > $_SESSION['expire']) {
session_unset();
session_destroy();
return true;
}
else
{
return false;
}
}
public function remove($key)
{
//session_start();
unset($_SESSION[$key]);
}
public function start()
{
session_start();
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (30 * 60);
}
}
A few hints:
require values should not be in brackets.
you should NOT be using mysql_ functions, this library is now CEASED and unavailable in PHP 7. Get up to date to 2012 and use mysqli_ or PDO. (Why?)
You should be using PHP 7. As a minimum. (Why?)
Do NOT use md5 for hashing passwords. Use PHP's built in password_hash() function(s). (How?)
STOP outputting errors to screen (aka return mysql_error();). You should be sending errors to an error log (error_log(print_r(mysql_error(),true));) so the public can't see the details of the error.
Read your PHP Error Log. What does it say?
Use Prepared Statements on your database interactions. ([How?(https://phpdelusions.net/mysqli))
Header("Location: ... "); functions should always be immediately followed by exit;/die();
NEVER trust user input. Even if the user tells you it's harmless. (Why?)
Read your PHP Error Log. What does it say?
Your classes should probably have class __constuct() functions. (why?)
You can use Boolean Values instead of strings; use return true; instead of return "true";
You STILL should NOT be using mysql_ functions, Why are you still using them? Stop reading this and update your codebase! Use mysqli_ or PDO. (Why?)
Learn the differences between the different PHP Comparison Operators. And apply what you learn to your code.
Use the PHP Manual to find out and use the multitude of functions available in PHP.
Please get in touch with me if you wish to purchase a copy of PHP 6 (rated 4.5/5 stars on TripAdvisor).
You have a lot of reading to do, and a lot to learn. I would say good luck, but you don't need any luck, you need to read and commit yourself to learning how to use PHP properly.
Have fun.
You need to apply a condition whether you have record in database or not. If not then you need to bypass to login page. Change this code as below:
if ($msg == "true") {
$userPass = md5("hms2015".$_POST['password']);
$loginId = $_POST["email"];
$query = "select loginId,userGroupId,password,name,userId from users where loginId='" . $loginId . "' and password='" . $userPass . "';";
var_dump($query);
$result = $db->getData($query);
//var_dump($result);
if (mysql_num_rows($result) > 0) { // means user is logged in
$info = array();
while ($row = mysql_fetch_assoc($result)) {
array_push($info, $row['loginId']);
array_push($info, $row['userGroupId']);
array_push($info, $row['password']);
array_push($info, $row['name']);
array_push($info, $row['userId']);
}
//$db->close();
$ses = new \sessionManager\sessionManager();
$ses->start();
$ses->Set("loginId", $info[0]);
$ses->Set("userGroupId", $info[1]);
$ses->Set("name", $info[3]);
$ses->Set("userIdLoged", $info[4]);
if (is_null($info[0])) {
$msg = "Login Id or Password Wrong!";
}
else
{
}
if($info[1]=="UG004")
{
header('Location: http://localhost/hms/sdashboard.php');
}
elseif($info[1]=="UG003")
{
header('Location: http://localhost/hms/edashboard.php');
}
else
{
header('Location: http://localhost/hms/dashboard.php');
}
}
}
But I will suggest you to use PDO as mysql is deprecated already. Also your code is widely open for SQL injection as well so read about it as well. Hope it helps you but make your code reliable.

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

CodeIgniter login using passwordHash and passwordSalt

My question..The variable $salted returns a random UUID then md5's it.What I need for the login to work though is for the variable $salted to return the value of passwordSalt field in my database from the auth table that corresponds to t1.PrincipalID = t2.UUID .How do I give the variable $salted this value?
Basically how do i give a variable a value from my database without user input.Thank you.
code snippets..the essential part of my code.
my view...
<?php echo validation_errors(); ?>
<?php echo form_open('verifylogin'); ?>
<form>
<input type="text" name="FirstName" placeholder="firstName">
<input type="password" name="passwordHash" placeholder="Password">
<input type="submit" name="login" class="login login-submit" value="Login">
</form></div>
my controller...
Function check_database($password)
{
//Field validation succeeded. Validate against database
$firstName = $this->input->post('FirstName');
$password = $this->input->post('passwordHash');
//query the database
$result = $this->users_model->login($firstName,$password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'PrincipalID' => $row->PrincipalID,
'FirstName' => $row->FirstName
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;
}
}
my model..
function login($firstName,$password)
{
$salted = sprintf('%s', md5(_uuid()));
$hash = md5(md5($password) . ":" . $salted);
$this->db->select('PrincipalID, FirstName')
->from('useraccounts AS t1, auth AS t2')
->where('t1.PrincipalID = t2.UUID')
->where('t1.FirstName', $firstName)
->where('t2.passwordHash', $hash);
$this -> db -> limit(1);
$query = $this -> db -> get();
if($query -> num_rows() == 1)
{
return $query->result();
}
else
{
return false;
}
}

Cookies and variables

I've created a login class for my web app and it does work, but now I've created that infamous "keep me logged in" - checkbox and don't get it to work. Here's my class for login:
<?php
error_reporting(E_ALL ^ E_NOTICE);
class Login {
private $error;
private $connect;
private $email;
private $password;
public $row;
public function __construct(PDO $connect) {
$this->connect = $connect;
$this->error = array();
$this->row = $row;
}
public function doLogin() {
$this->email = htmlspecialchars($_POST['email']);
$this->password = htmlspecialchars($_POST['password']);
$this->rememberme = $_POST['rememberme'];
if($this->validateData()) {
$this->fetchInfo();
}
return count($this->error) ? 0 : 1;
}
public function validateData() {
if(empty($this->email) || empty($this->password)) {
$this->error[] = "Täyttämättömiä kenttiä";
} else {
return count($this->error) ? 0 : 1;
}
}
public function fetchInfo() {
$query = "SELECT * FROM users WHERE email = :email AND activation_token IS NULL";
$stmt = $this->connect->prepare($query);
$stmt->execute(array(
':email' => $this->email,
));
if($stmt->rowCount() == 0) {
$this->error[] = "Väärä käyttäjätunnus tai salasana";
return 0;
} else {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['email'] = $row['email'];
$_SESSION['name'] = $row['name'];
$_SESSION['profilepic'] = $row['profilepic'];
if(isset($this->rememberme)) {
setcookie("loggedin", "yes", time() + 25200);
}
}
if (Register::cryptPass($this->password) != $row['password']) {
$this->error[] = "Virheelliset kirjautumistiedot";
} else {
return true;
}
return count($this->error) ? 0 : 1;
}
public function displayErrors() {
if(!count($this->error)) return;
echo "<div class='login_error'>";
foreach($this->error as $key=>$value) {
echo "<p>".$value."</p>";
}
echo "</div>";
}
public function doLogout() {
session_destroy();
}
}
?>
And here's a small part of my code from my another file where I'm checking if the session or cookie is set:
<?php
if (isset($_SESSION['email']) || isset($_COOKIE['loggedin'])) {
?>
<div id="header_container_isloggedin">
<div class="container_12">
<header id="header">
<div class="grid-12">
<ul id="menu">
<li class="profile-name">
<a href="profile.php?id=<?php echo $_SESSION['user_id']; ?>">
<span class="header_username">
<img src="images/thumbnails/<?php echo $_SESSION['profilepic']; ?>"
class="profile_evensmaller"/>
<span class="header_name"><?php echo $_SESSION['name']; ?></span></span></a>
</li>
</ul>
<?php } ?>
The problem is that everytime the cookie is set, it doesn't display my profile picture or name since they've saved inside of $_SESSION variable. So how should I approach this and get this to work. I know that right now it's not the safest method, since I'm not generating any hashes for that cookie, but right now the only thing I'm interested in, is to get this one to work.

Undefined variables errors

So i'm working on a project and i am running to to a few mysql & php errors.
First Error :
This is all code associated with First Error
// Database Class
class Database {
public $_link, $_result, $_numRows;
public function __construct($server, $username, $password, $db){
$this->_link = mysql_connect($server, $username, $password) or die('Cannot Execute:'. mysql_error());
mysql_select_db($db, $this->_link);
}
public function disconnect(){
mysql_close($this->_link);
}
public function query($sql){
$this->_result = mysql_query($sql, $this->_link) or die('Cannot Execute:'. mysql_error());
$this->_numRows = mysql_num_rows($this->_result);
}
public function numRows() {
return $this->_numRows;
}
public function rows(){
$rows = array();
for($x = 0; $x < $this->numRows(); $x++) {
$rows[] = mysql_fetch_assoc($this->_result);
}
return $rows;
}
}
// Setup.php
$is_set = 'false';
global $company_name, $ebay_id;
if( isset($_POST['ebay_id'], $_POST['company_name']) ){
$_ebay_id = $_POST['ebay_id'];
$_company_name = $_POST['company_name'];
$is_set = 'true';
} else {
// Silence is Golden!
}
$_service_database = new Database('localhost', 'root', 'password', 'chat-admin');
$_service_database->query("SELECT * FROM installs WHERE `identity` = '$mysqldb' AND `db_name` = '$mysqldb'");
if ($_service_database->numRows() == 0){
if($is_set == true){
$_service_database->query("INSERT INTO installs (ebay_id, name, db_name, identity) VALUES ('$_ebay_id', '$_company_name', '$mysqldb', '$mysqldb')");
}
} else {
// header("Location: index.php");
}
$_service_database->disconnect();
?>
<form name="setup" method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
<input placeholder="eBay Username" type="text" name="ebay_id">
<input placeholder="Company Name" type="text" name="company_name">
<input type="hidden" name="insert" value="true">
<input type="submit">
</form>
So what this does is checks if the variables defined are in the database if they are not then when the form is submitted it inserts our values, if they are in the database it redirects to index.php, ok so i am receiving the all mighty MySQL num_rows* expects parameter 1 to be resource, boolean given ..., now i have searched everywhere and only found that the die error should solve, that is why you can see it on line 16 in the function query, now although i get the error everything still works its not really good for me to turn error reporting off so any help would be great. Also if you see undefined variables like $mysqldb they are actually set but on a different page and they are valid
Second Error : = function made for simplicity of a templating system
This is all associated with Second Error
function get_content_type($value){
if (strpos($value,'title:') === 0 ) {
$title = explode("title: ",$value);
$value = $title[1];
} else if (strpos($value,'css:') === 0 ) {
$css = explode("css: ",$value);
$value = $css[1];
} else if (strpos($value, 'js:') === 0 ) {
$javascript = explode("js: ", $value);
$value = $javascript[1];
} else {
// Silence is Golden
}
if($value == $title[1]){
echo '<title>'.$value.'</title>';
} else if ($value == $css[1]) {
echo '<link rel="stylesheet" href="'.$value.'">';
} else if ($value == $javascript[1]) {
echo '<script src="'.$value.'"></script>';
}
}
// Calling
get_content_type('title: Welcome to my site');
get_content_type('css: http://something.com/style.css');
get_content_type('js: http://code.jquery.com/jquery-latest.min.js');
everything works as this outputs
<title>Welcome to my site</title><link rel="stylesheet" href="http://somesite.com/style.css"><script src="http://code.jquery.com/jquery-latest.min.js"></script>
Only when i set error_reporting(0);
The errors i get are undefined variables because obviously i'm setting one, then im unsettling that one and setting the other so eventually only 1 is true although its already outputted all of them correctly.
UPDATE
Second Error : Errors =
Notice: Undefined variable: css in C:\Server\www\hidie\libs\test.php on line 19
Notice: Undefined variable: title in C:\Server\www\hidie\libs\test.php on line 17
Notice: Undefined variable: title in C:\Server\www\hidie\libs\test.php on line 17
First Error : Errors =
ERROR: Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given
Ok so here's your problem:
First, as mentioned in the comment, mysql_num_rows only works on select and show. You have it in your query method, which is called by an insert. You can't do that.
public function query($sql){
$this->_result = mysql_query($sql, $this->_link) or die('Cannot Execute:'. mysql_error());
$this->_numRows = mysql_num_rows($this->_result); // <- BAD!
}
You call it on this line:
if($is_set == true){
$_service_database->query("INSERT INTO installs (ebay_id, name, db_name, identity) VALUES ('$_ebay_id', '$_company_name', '$mysqldb', '$mysqldb')");
}
You could make a second method for database and call it for all calls that write to the db:
public function execute($sql){
$this->_result = mysql_query($sql, $this->_link) or die('Cannot Execute:'. mysql_error());
}
which would be called like so:
if($is_set == true){
$_service_database->execute("INSERT INTO installs (ebay_id, name, db_name, identity) VALUES ('$_ebay_id', '$_company_name', '$mysqldb', '$mysqldb')");
}
Second, you need to implicitly define the variables $css and $title outside of those conditionals. Otherwise you are attempting to call undefined vars as indicated by the message...
$title = "";
$css = "";
if (strpos($value,'title:') === 0 ) {
$title = explode("title: ",$value);
$value = $title[1];
} else if (strpos($value,'css:') === 0 ) {
$css = explode("css: ",$value);
$value = $css[1];
} else if (strpos($value, 'js:') === 0 ) {
$javascript = explode("js: ", $value);
$value = $javascript[1];
} else {
// Silence is Golden
}

Categories