I want to use a MySQL Query in a function to retrieve information from a table:
function selectFromMemTable($a) {
$query="SELECT * FROM members WHERE username = '" . $a ."'";
$result = mysql_query($query) or die ("FOUT: " . mysql_error());
while (list($id, $a, $b, $c, $d, $e, $f) = mysql_fetch_row($result)){
$user_id = $id;
$user_usernaam = $a;
$user_voornaam = $b;
$user_achternaam = $c;
$user_email = $d;
$user_password = $e;
$user_admin = $f;
}
}
In the script I want to use the following code to retrieve the $user_id.
selectFromMemTable(username);
echo $user_id;
When loading page I receive the following error:
Fatal error: Call to undefined function selectFromTable() in test.php on line 28
Without the function it works correctly. What is the problem?
Sorry, the correct script is:
selectFromMemTable($_COOKIE["user"]);
echo $user_id;
You named your function selectFromMemTable but are calling selectFromTable. That's the wrong name.
Check the name of your function. The comiler says you try to call a function with a different name.
In your function selectFromMemTable you should return the selected values or global the vars. Because you cannot access them until they are private only.
Never trust incoming request vars! Yo should escape $_COOKIE["user"] for use in databse query (use mysql_real_escape_string or the newer mysqli_real_escape_string).
Since there matches only 1 user per username you should LIMIT the selected rows to 1.
Be aware of using the username directly from cookie to access private userdata. For security reasons you should use a individual session ID or a cryptographic stronger individual qualifier for use with cookies. That's because actually the user can change it's name in the cookie value and than he's logged in as another user.
You can fetch an assoc - it's easyer to access and you don't need to set tons of variables.
Function declaration:
function selectFromMemTable($a)
{
$query = sprintf("SELECT * FROM members WHERE username = '%s' LIMIT 1",
mysql_real_escape_string($a));
$result = mysql_query($query) or die ("FOUT: " . mysql_error());
return mysql_fetch_assoc($result);
}
Use the function:
$user = selectFromMemTable($_COOKIE["user"]);
if(!$user)
echo "no user";
else
echo $user['id'];
Edit: Maybe you have to change the id in $user['id'] to the right column name.
Related
I am using a HTTP query string to pass an id. The variable I assign it to works perfectly for the queries immediately following. However, it doesn't work within any of the functions which I define in the same file, although I declared the variable as global.
$circleID = $_GET['id'];
$circleID works well for this query:
// Retrieve circle data
$circleDataResult = mysqli_query($connection," SELECT name, description
FROM circle
WHERE circleID = '$circleID' ");
$circleData = mysqli_fetch_array($circleDataResult);
$circleName = $circleData['name'];
$circleDesc = $circleData['description'];
It doesn't work within the following function though. $circleID seems to be empty in this context:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'removeUser' : removeUser(); break;
case 'makeAdmin' : makeAdmin(); break;
case 'revokeAdmin' : revokeAdmin(); break;
case 'makeOwner' : makeOwner(); break;
}
}
function removeUser(){
global $connection;
global $circleID;
$thisUserID = $_POST['id'];
$removeUserFromCircle = " DELETE
FROM circle_participants
WHERE circleID = '$circleID' AND userID = '$thisUserID' ";
if (mysqli_query($connection, $removeUserFromCircle)) {
echo "You removed " . getName($thisUserID) . " from this circle";
} else {
echo "Error deleting record: " . mysqli_error($connection);
}
}
Apologies if this is a trivial question. I am new to php and spent a considerable amount of time trying to solve this, but I'm stuck.
In order to sum up the answer for anyone else encountering the problem:
It seems like the id value I wanted to retrieve via GET from the HTTP query string value was overwritten/set to null by the POST request, as user3411846 pointed out. Thus, when the code was executed via AJAX, circleID was set to null.
Using session variables in conjunction with if(isset){} solved the problem!
This is the bit of code I changed:
if(isset($_GET['id'])){
$_SESSION['circleid'] = $_GET['id'];
}
instead of:
$circleID = $_GET['id'];
And within the function:
function removeUser(){
...
$circleID = $_SESSION['circleid'];
...
}
instead of:
function removeUser(){
...
global $circleID;
...
}
See why this will not work
Suppose that you have sent an get request to a page
$a = $_GET['variable'];
echo $a ; // this will echo the variable
exit;
Now you are making once again the post request to this page
$a=$_POST['variable'];
echo $a; // will print data if there exist data in the given variable
exit;
Now since you want to access the previous get data in the post data you have to save the get data in the session since on the next request all the data from the previous request will be lost
so in starting of the page
session_start()
$circleid = $_GET['id'];
$_SESSION['cirlceid'] = $circleid;
and in the remove function
function removeUser(){
global $connection;
$circleID = $_SESSION['circleid']
$thisUserID = $_POST['id'];
$removeUserFromCircle = " DELETE
FROM circle_participants
WHERE circleID = '$circleID' AND userID = '$thisUserID' ";
if (mysqli_query($connection, $removeUserFromCircle)) {
echo "You removed " . getName($thisUserID) . " from this circle";
} else {
echo "Error deleting record: " . mysqli_error($connection);
}
}
I have this function
function getNick($uid)
{
$sqli = "SELECT nick FROM users WHERE userid='".$uid."'";
mysqli_real_escape_string($con,$sqli);
$resulti = mysqli_query($con,$sqli);
$rowi = mysqli_fetch_assoc($resulti);
if($resulti->num_rows > 0) return $rowi["nick"];
else return "(none)";
}
Basically it should return me nick based on user's id. Problem is that I only keep getting '(none)'. What is interesting I printed actual $sqli and copied it into phpMyAdmin and it worked as expected. I even tried to just print nick without IFs but I ended up with empty string. What might be the issue? Am I overlooking something? Thanks
<?php
$con = mysqli_connect("localhost","root","","test");
function getNick($uid,$con)
{
$sqli = "SELECT nick FROM users WHERE userid='".$uid."'";
mysqli_real_escape_string($con,$sqli);
$resulti = mysqli_query($con,$sqli);
$rowi = mysqli_fetch_assoc($resulti);
if($resulti->num_rows > 0) return $rowi["nick"];
else return "(none)";
}
echo getNick(1,$con);
?>
it works
variable scope problem
use above method to pass connection in method or
use $GLOBALS['con'] to access connection in method getNick
Is it needed to check if sid existed, casue this callback generates $sid if there is no $sid exists, so what I want to ask is, is there a possiblity that the $sid will be empty?
function read($sid) { //Callback function in session_set_save_handler
if(empty($sid)) {
//do something
}
}
Do you mean the function is called by session_set_save_handler?
If so, there is no need to worry. You can see these examples below from two different sites. They both not worry it.
Example
function read($SessionKey){
$sql = "SELECT uid FROM sessions WHERE session_id = '".$SessionKey."' limit 1";
$query =$this->db->query($sql);
if($row=$this->db->fetch_array($query)){
return $row['uid'];
}else{
return "";
}
}
Another example from http://php.net/manual/zh/function.session-set-save-handler.php:
function read($sessID) {
// fetch session-data
$res = mysql_query("SELECT session_data AS d FROM ws_sessions
WHERE session_id = '$sessID'
AND session_expires > ".time(),$this->dbHandle);
// return data or an empty string at failure
if($row = mysql_fetch_assoc($res))
return $row['d'];
return "";
}
function check_login($array_val)
{
$strQury = "Select * from tblsignup where usr_email ='".$array_val[0]."' and usr_password = '".$array_val[1]."'" ;
$result = mysql_query($strQury);
$row_user = mysql_fetch_array($result);
if(mysql_num_rows($result)>0)
{
$msg = "true";
}
else
{
$msg = "false";
}
return $msg ;
}
The return value is Object id #1true???? what is object id#1?
Change from:
echo $objUser.check_login($array_login);
to:
echo $objUser->check_login($array_login);
The . operator in PHP does string concatenation, while the arrow allows you to access object methods and attributes.
You're returning the strings "true" or "false" when you probably mean the boolean values true and false.
Oh, and your code is wide open to a visit from Little Bobby Tables. You really should use mysqli and proper prepared statements instead.
Try this:
function check_login($array_val)
{
$strQury = "Select * from tblsignup where usr_email ='".$array_val[0]."' and usr_password = '".$array_val[1]."'" ;
$result = mysql_query($strQury);
$row_user = mysql_fetch_array($result);
if(mysql_num_rows($result)>0)
{
return true;
}
else
{
return false;
}
}
Let us know what result you get when using that code.
user single quotes and things will start to work better. also check your query for sql injection bug as it does have it.
Change
echo $objUser.check_login($array_login);
to
echo $objUser;
echo check_login($array_login);
You should end up with the following result:
Object id #1
true
My guess is that $objUser was set earlier with something along these lines:
$objUser = new User;
As a result, it is an object (the first one declared) and will return Object id #1 when you just echo it. You will need to read up on classes to understand that more.
My aim is to have a simple, form based CMS so the client can log in and edit the MySQL table data via an html form. The login is working, but the edit page isn't returning the values from the MySQL table, nor am I getting any errors.
I'm still amateur, and I first started the following code for a class project, but now plan to implement it for a live site. From what I understand I shouldn't have to declare the next/previous/etc. variables at the top, which I tried unsuccessfully to do so anyway. Does anything stand out to any of you?:
<?php
echo "<h2>Edit Special Offer</h2><hr>";
if (isset($_COOKIE["username"]))
{
echo "Welcome " . $_COOKIE["username"] . "!<br />";
include "login.php";
}
else
echo "You need to log in to access this page.<br />";
if(isset($previous))
{
$query = "SELECT id, specialtitle, specialinfo
FROM special WHERE id < $id ORDER BY id DESC";
$result = mysql_query($query);
check_mysql();
$row = mysql_fetch_row($result);
check_mysql();
if ($row[0] > 0)
{
$id = $row[0];
$specialtitle = $row[1];
$specialinfo = $row[2];
}
}
elseif (isset($next))
{
$query = "SELECT id, specialtitle, specialinfo
FROM special WHERE id > $id ORDER BY id ASC";
$result = mysql_query($query);
check_mysql();
$row = mysql_fetch_row($result);
check_mysql();
if ($row[0] > 0)
{
$id = $row[0];
$specialtitle = $row[1];
$specialinfo = $row[2];
}
}
elseif (isset($add))
{
$query = "INSERT INTO special (specialtitle, specialinfo)
VALUES ('$specialtitle', '$specialinfo')";
$result = mysql_query($query);
check_mysql();
$id = mysql_insert_id();
$message = "Special Offer Added";
}
elseif (isset($update))
{
$query = "UPDATE special
SET specialtitle='$specialtitle', specialinfo='$specialinfo'
WHERE id = $id";
$result = mysql_query($query);
check_mysql();
$id = mysql_insert_id();
$message = "Monthly Special Updated";
}
elseif (isset($delete))
{
$query = "DELETE FROM special WHERE id = $id";
$result = mysql_query($query);
check_mysql();
$specialtitle = "";
$specialinfo = "";
$message = "Special Offer Deleted";
}
$specialtitle = trim($specialtitle);
$specialinfo = trim($specialinfo);
?>
<form method="post" action="editspecial.php">
<p><b>Special Offer</b>
<br><input type="text" name="specialtitle" <?php echo "VALUE=\"$specialtitle\"" ?>> </p>
<p><b>Special Info/Description</b>
<br><textarea name="specialinfo" rows="8" cols="70" >
<?php echo $specialinfo ?>
</textarea> </p>
<br>
<input type="submit" name="previous" value="previous">
<input type="submit" name="next" value="next">
<br><br>
<input type="submit" name="add" value="Add">
<input type="submit" name="update" value="Update">
<input type="submit" name="delete" value="Delete">
<input type="hidden" name="id" <?php echo "VALUE=\"$id\"" ?>>
</form>
<?php
if (isset($message))
{
echo "<br>$message";
}
?>
Login.php:
<?php
function check_mysql()
{
if(mysql_errno()>0)
{
die ("<br>" . mysql_errno().": ".mysql_error()."<br>");
}
}
$dbh=mysql_connect ("xxxxxxxxxxxxxxxxx","xxxxxxxx","xxxxxxxx");
if (!$dbh)
{
die ("Failed to open the Database");
}
mysql_select_db("xxxxxx");
check_mysql();
if(!isset($id))
{
$id=0;
}
?>
Please please please do a little bit more learning before attempting to build this thing.
You can do it the way you are doing it, but with just a small amount of extra knowledge about OO programming, and maybe about the Pear db classes you will have 3x cleaner code.
If you really choose not to, at the very least, pull each of your save, update, delete, etc procedures out into functions instead of just inlining them in your code. put them in a separate file, and include it in that page.
It may not be useful to you, but I am going to dump a generic table access class here in the page for you. It requires a simple db class API, but if you use this or something like it your life will be 5x easier.
If you don't understand this code when you look at it, that's ok, but please just come back and ask questions about the stuff you don't understand. That is what stackoverflow is for.
This is an older class that should just do basic stuff. Sorry it's not better I just wanted to dig something out of the archives for you that was simple.
<?php
// Subclass this class and implement the abstract functions to give access to your table
class ActiveRecordOrder
{
function ActiveRecordOrder()
{
}
//Abstract function should return the table column names excluding PK
function getDataFields()
{}
//Abstract function should return the primary key column (usually an int)
function getKeyField()
{}
//abstract function just return the table name from the DB table
function getTableName()
{}
/*
This function takes an array of fieldName indexed values, and loads only the
ones specified by the object as valid dataFields.
*/
function loadRecordWithDataFields($dataRecord)
{
$dataFields = $this->getDataFields();
$dataFields[] = $this->getKeyField();
foreach($dataFields as $fieldName)
{
$this->$fieldName = $dataRecord[$fieldName];
}
}
function getRecordsByKey($keyID, &$dbHandle)
{
$tableName = $this->getTableName();
$keyField = $this->getKeyField();
$dataFields = $this->getDataFields();
$dataFields[] = $this->getKeyField();
$results = $dbHandle->select($tableName, $dataFields, array($keyField => $keyID));
return $results;
}
function search($whereArray, &$dbHandle)
{
$tableName = $this->getTableName();
$dataFields = $this->getDataFields();
$dataFields[] = $this->getKeyField();
return $dbHandle->select($tableName, $dataFields, $whereArray);
}
/**
* Since it is *hard* to serialize classes and make sure a class def shows up
* on the other end. this function can just return the class data.
*/
function getDataFieldsInArray()
{
$dataFields = $this->getDataFields();
foreach($dataFields as $dataField)
{
$returnArray[$dataField] = $this->$dataField;
}
return $returnArray;
}
/**
* Added update support to allow to update the status
*
* #deprecated - use new function saveObject as of 8-10-2006 zak
*/
function updateObject(&$dbHandle)
{
$tableName = $this->getTableName();
$keyField = $this->getKeyField();
$dataArray = $this->getDataFieldsInArray();
$updatedRows = $dbHandle->updateRow(
$tableName,
$dataArray,
array( $keyField => $this->$keyField )
);
return $updatedRows;
}
/**
* Allows the object to be saved to the database, even if it didn't exist in the DB before.
*
* #param mixed $dbhandle
*/
function saveObject(&$dbhandle)
{
$tableName = $this->getTableName();
$keyField = $this->getKeyField();
$dataArray = $this->getDataFieldsInArray();
$updatedRows = $dbHandle->updateOrInsert(
$tableName,
$dataArray,
array( $keyField => $this->$keyField )
);
return $updatedRows;
}
}
"Welcome " . $_COOKIE["username"] . "!<br />"; [and many other places]
HTML-injection leading to cross-site security holes. You need to use htmlspecialchars every time you output a text value to HTML.
"INSERT INTO special (specialtitle, specialinfo) VALUES ('$specialtitle' [and many other places]
SQL-injection leading to database vandalism. You need to use mysql_real_escape_string every time you output a text value to an SQL string literal.
if (isset($_COOKIE["username"]))
Cookies are not secure, anyone can set a username cookie on the client-side. Don't use it for access control, only as a key to a stored or session user identifier.
You also appear to be using register_globals to access $_REQUEST values as direct variables. This is another extreme no-no.
Between all these security snafus you are a sitting duck for Russian hackers who will take over your site to push viruses and spam.
Be careful with your code there. Your not filtering your cookie value and you shouldn't be storing a username directly in there as it can be easily changed by the visitor. You should look into filter_input for filtering cookie data and eany form data that is being submitted - especially your $_POST['id']
this will save you a lot of heartache further down the line from attacks.
Your if else statements are checking if variables are set but you dont set next, previous, add etc
You are using submit buttons with those values so you would need to check for
if(isset($_POST['previous']))
instead of yours which is
if(isset($previous))
I can't see where you set your database details either unless you have an included file somewhere that you haven't posted. (don't post the real ones of course but i can't see anything)
I don´t know what's happening in login.php, but you're using $id before it is set. That´s just in the first part.
Edit: To clarify, you are using $id in every query statement and setting it afterwards, my guess would be that $id is null and that is why nothing gets returned.
Edit 2: What else is happening in login.php? If you never read your $_POST variables, nothing will ever happen.
Edit 3: Like I already partly said in a comment, your if(isset($previous)) section, elseif (isset($update)) section and elseif (isset($delete)) sections will never do anything as $id is always 0.
After authenticating your user you need to get and filter the posted variables, $_POST['id'], $_POST['previous'], etc.