Below is some code that works fine, however it used mysql_* and i dont want that anymore. I have tried to redo this section in mysqli but it's not working. I can post my entire code if you wish, but i am certain i know where the issue lies. Below is the code:
Old:
public function verifyDatabase()
{
include('dbConfig.php');
$data = mysql_query("SELECT client_id FROM clients WHERE client_email_address = '{$this->_username}' AND client_password = '{$this->_pass_sha1}'");
if(mysql_num_rows($data))
{
list($this->_id) = #array_values(mysql_fetch_assoc($data));
return true;
}
else
{
return false;
}
}
New:
public function verifyDatabase()
{
include('dbConfig.php');
$data = $db->prepare("SELECT client_id FROM clients WHERE client_email_address = ? AND client_password = ? LIMIT 1");
$data->bind_param($this->_username, $this->_pass_sha1);
$data->execute();
$data->store_result();
if($data->num_rows)
{
list($this->_id) = #array_values($data->fetch());
return true;
}
else
{
return false;
}
}
I'm still learning mysqli and not quite ready for PDO stuff as i found that a little confusing. As i say, this whole script works perfectly with mysql_* but not so much with mysqli. When i try and log in my form doesnt display any errors nor does it push forward to the next page, so i know its this bit that is the issue
it is advised to use a helper function, either with old mysql or modern mysqli
public function verifyDatabase()
{
$sql = "SELECT client_id FROM clients WHERE email = ? AND password = ?";
return $this->db->getOne($sql ,$this->_username,$this->_pass_sha1);
}
Also note that dbConfig.php should not be included in the every method but, but only once. While DB handler should be assigned to a class variable in the constructor.
Change your code to this. I'm not saying it will fix problems but will be better.
public function verifyDatabase()
{
include('dbConfig.php');
$data = $db->prepare("SELECT client_id FROM clients WHERE client_email_address = ? AND client_password = ? LIMIT 1");
$data->bind_param($this->_username, $this->_pass_sha1);
$data->execute();
$data->store_result();
if($data->num_rows > 0)
{
$result = $data->fetch();
$this->_id = $result['client_id'];
return true;
}
else
{
return false;
}
}
You can also put var_dump($result); after the $result = $data->fetch(); line to print out what exactly is being returned.
Related
I am new and still lerning php and Im trying to set values that Im retrieving from postgresql database, but Im having problems with my code that i cant figure out and I hope someone here can help me. :)
This is the code:
public function __construct($username, $password)
{
$config = new Config();
$dbconn = pg_connect($config->getDbDsn()); // getDbDsn contains all the information that is needed to connect to the database.
$query = "SELECT username, password, id FROM user.member WHERE username = '$username'";
$result = pg_query($dbconn, $query);
$db = pg_fetch_all($result);
if($db)
{
foreach($db as $d)
{
if( $d['username'] == $username && $d['password'] == $password)
{
$this->verified = true;
$this->id = $d['id']; //save id does not work
$this->user = $d['username']; // save username does not work
}
else
{
$this->verified = false;
}
}
}
else
{
$this->verified = false;
}
}
Okay, this is what im trying to do. First im asking the database to give me the informationen from the table, that is a match to my users username and password. I am using a bool (verified) to verify the user. That works fine. But then, when Im trying to set the values of username and id for my user, that is impossible. If im creating a set_val-function (just to test my code, to try to find my error):
private $a = "";
private function set_val($data){ $this->a = $data; }
and I use that function to set value, in my construct-function:
$this->set_val('hello');
that works fine, until I put that function in my if($db)-statment, then it doesnt work anymore. (it works fine if I put it outside my if($db)-statement, like directly under $db = pg_fetch_all($result);).
$db = pg_fetch_all($result);
$this->set_val('hello'); // This works fine
if($db)
{
$this->set_val('hello'); // This does not work at all
foreach($db as $d)
$this->set_val('hello'); // And not this
}
For my get_val I have this code:
public function get_val(){
return $this->a;
}
(I also have the same get-functions for id and username)
And here Im trying to echo my value, which works fine, if I put the set_val-function outside my if-statement (and foreach-statement):
public function echo_val(){
echo $this->get_val();
}
I'm new to PHP (7), and I'm having issues understanding how to pass parameters to PHP functions, from the first php script, I make a call to the following function:
public static function UpdateDatos($UserPassword, $idUser, $OldUserPassword)
{
if (self::ObtenerDatosPorId($idUser)) {
try {
$consultar = "UPDATE Usuarios SET UserPassword = ? WHERE idUser = ? AND UserPassword = ?";
$resultado = Database::getInstance()->getDb()->prepare($consultar);
return $resultado->execute(array($UserPassword, $idUser, $OldUserPassword));
} catch (PDOException $e) {
return false;
}
} else {
return false;
}
}
when I call this method like this, while debugging, I can see that datos[] have the following values:
$datos["UserPassword"] = "newPassword"
$datos["idUser"] = "15"
$datos["OldUserPassword"] = "OldPassword"
Here everything is ok, but when I call the function with these values...
$datos = json_decode(file_get_contents("php://input"), true);
$respuesta = Registro::UpdateDatos( $datos["UserPassword"], $datos["idUser"], $datos["OldUserPassword"]);
Back in the function declaration, I see the arguments have been mapped wrongly, like this;
$datos["UserPassword"] = "15"
$datos["idUser"] = "OldPassword"
$datos["OldUserPassword"] = "newPassword"
Can someone please help me understand why this is happening? I know they're anonymus variables, but aren't they supposed to be received in the same order I sent them?.
Thank you in advance and sorry if this has already been asked, couldn't find any answer but turning it into an array,
I'm trying to implement these two functions in a separate file functions.php and call it in index.php
function is_field($column, $table, $requested) {
$is_field_query = "SELECT ".$column." FROM ".$table." WHERE ".$column."='".$requested."'";
$is_field_result = $mysqli->query($is_field_query);
$is_true = $is_field_result->num_rows;
$is_field_result->close();
return $is_true;
}
function get_content($column, $table, $requested) {
$get_content_query = "SELECT ".$column." FROM ".$table." WHERE ".$column."='".$requested."'";
$get_content_result = $mysqli->query($get_content_query);
$get_content_row = $get_content_result->fetch_array(MYSQLI_ASSOC);
$get_content_content = $get_content_row["content"];
$get_content_result->close();
return $content;
}
I have tried it over and over again and I have no idea why it wont work. The first one is returning 1 for valid or 0 for invalid. The second retrieves the content from a specific cell in the MySQL table. Any help would be much appreciated.
You're using $mysqli inside the function, but you never pass the MySQLi resource itself. Consider writing your function like this:
function is_field($mysqli, $column, $table, $requested) {
Or, create a class that takes a MySQLi resource and reference it with $this->mysqli inside your function.
Also, code like this may be another issue:
$is_field_result = $mysqli->query($is_field_query);
$is_true = $is_field_result->num_rows;
You're not checking whether $is_field_result is false; therefore, the next statement causes a fatal error, because a property can't be fetched from something that's not an object.
if (($is_field_result = $mysqli->query($is_field_query)) === false) {
die($mysqli->error);
}
$is_true = $is_field_result->num_rows;
It turns out the reason it was not working was I needed to add an extra field into the function to accept the passing of $mysqli from the connection.
function is_field($mysqli, $column, $table, $requested) {
$is_field_query = "SELECT * FROM $table WHERE $column='$requested'";
if (($is_field_result = $mysqli->query($is_field_query)) == false) {
die($mysqli->error);
}
$is_true = $is_field_result->num_rows;
$is_field_result->close();
return $is_true;
}
function get_content($mysqli, $column, $table, $requested) {
$get_content_query = "SELECT * FROM $table WHERE $column='$requested'";
if (($get_content_result = $mysqli->query($get_content_query)) == false) {
die($mysqli->error);
}
$get_content_row = $get_content_result->fetch_array(MYSQLI_ASSOC);
$get_content = $get_content_row["content"];
$get_content_result->close();
return $get_content;
}
class Application_Model_DbTable_Email extends Zend_Db_Table_Abstract
{
protected $_name = 'memberdetail';
function getUserid($email)
{
$subquery = $this->select()
->from('memberdetail', array('memberid'))
->where('email = ?', $email);
$select = $this->select()
->from('usertable', array('userid'))
->join('memberdetail', 'usertable.userid = memberdetail.memberid')
->where('usertable.userid = ?', $subquery);
$row = $select->query()->fetch();
if (!$row) {
echo "User id not found";
} else {
return $userid = $row['userid'];
}
}
}
Hi, I am trying to return the userid from the above queries. However, the queries does not seemed to be executed as I always get refreshed whenever I call this function.
P.S this set of queries were given to me by another member.
it looks like this is being over thought. According to the info provided usertable.userid = memberdetail.memberid with this being the case your function is simple.
/** this function assumes one and only one email will match a memberid
* this function can be improved by validating $email as existing in DB
* prior to querying DB, should be done at form level but could be accomplished here
* with Zend_Validate_Db_RecordExists()
*/
public function getUserIdFromEmail($email) {
$select = $this->select();
$select->where('email = ?',$email);
$row = $this->fetchRow($select);//fetch a single row
if (!is_null($row) {//fetchRow returns null if no row matched
return $row->memeberid;//return memberid as string/integer = usertable.userid
} else {
//handle error
}
}
It would have been useful to tell people you are using Zend framework.
You need to establish a connection to the database for $this as described in steps 1 and 2 in this link:
http://framework.zend.com/manual/en/zend.db.select.html/
You can try this, if it helps:
function getUserid($email){
$select = $this->select()
->setIntegrityCheck(false)
->from(array('m' => 'memberdetail'), array('b.userid'))
->join(array('b' => 'usertable'), 'b.userid = m.memberid')
->where('m.email = ?', $email);
$row = $this->getAdapter()->fetchAll($select);
if (!$row) {
throw new Exception("User id not found");
} else {
return $row->toArray();
}
}
I have build a website in Drupal, and I am trying to create a fun way to get members involved with the site by building a userpoint system, the system is all in place, but I'm trying to make a shop where they can buy 'titles'.
This is the script I wrote for the shop, with a bit of error handling, but I'm stuck with a problem,
In my JavaScript, I have the function buyitem( ) with 2 variables, which I want to use in my PHP functions which check everything in my database, is there a way to get those variables from JavaScript to the PHP function I wrote without going to an external PHP file?
<?php
include "php-scripts/DBConnection.php";
$con = getconnection();
mysql_select_db("brokendi_BD", $con);
function getKarma()
{
$result = mysql_query("SELECT * FROM userpoints WHERE uid='getUID()'");
$row = mysql_fetch_array($result);
$currentkarma = (int)$row['points'];
return $currentkarma;
}
function getUID()
{
global $user;
if ($user->uid)
{
$userID=$user->uid;
return $userID;
}
else
{
header('Location: http://brokendiamond.org/?q=node/40');
}
}
function hasRole($roleID)
{
$usersid = getUID();
$returnValue = false;
$result = mysql_query("SELECT * FROM users_roles");
while ($row = mysql_fetch_array($result))
{
if ($row['uid'] == $usersid)
{
if ($row['rid'] == $roleID)
{
$returnValue = true;
break;
}
}
}
return $returnValue;
}
function enoughKarma()
{
if ( getKarma() >= $requiredKarma)
{
return true;
}
else
{
return false;
}
}
function buyRole()
{
$currentKarma = getKarma();
$newkarma = $currentKarma - $requiredKarma;
$userID = getUID();
mysql_query("UPDATE userpoints SET points = '$newkarma' WHERE uid='$userID'");
mysql_query("INSERT INTO users_roles (uid, rid) VALUES ($userID, $roleID)");
}
?>
<script type="text/javascript">
buyItem(1 , 0);
function SetStore()
{
}
Function buyItem(itemID,reqKarma)
{
if (<?php enoughKarma(); ?>)
{
<?php buyRole(); ?>
}
else
{
alert('You do not have enough Karma to buy this title.');
}
}
</script>
PHP is a server side script and javascript is a client side, server side scripts are executed before the page loads, meaning your javascript cannot pass variables to it, BUT you can how ever pass php variables to your js.
Best solution in your case is to use ajax to send those variables to php and have the php set variables on it's side, this doesn't quite solve your problem, but with some creativity in your code you can make it happen.
you can either reload the page (which I doubt is what you'r looking for) or make an ajax call to your php script sending the 2 variables.
if you're using jQuery, this should give you an idea of how to do this