I have 2 tables in a database and they have a foreign key relation thru the column called id.
So I have the id (representing a user and is the primary key in the user table) from one table and want to check weather that user has existing data in the other table.
So I wish to run the id against the column called id in the other table and if the id exists in that column return value true.
I´m not getting any error at the moment but the method does not return any value. So I must be doing something wrong... Any help appreciated!
This is the class and method I have in one file:
class test {
public function dataExists ()
{
$db = Database::getInstance();
$classUser = new user();
$userId = $classUser->getUserData($_SESSION['id']);
$user = $userId['id'];
$query = $db->prepare("`id` SELECT * FROM `data`");
if ($user == $query)
{
return true;
} else {
return false;
}
}
}
And the in my view file I have this:
$classTest = new test();
$exists = $classTest->dataExists();
if ($exists == true) {
echo '';
}
Currently you are checking if a mysqli_stmt object (returned from prepare()) equals a number. How do you think this comparison should work?
You can do this via num_rows, this is taken pretty straight forward from the manual
public function dataExists () {
//...
if ($statement = $db->prepare("SELECT * FROM `data` WHERE `id`=?")) {
$statement->bind_param("i", $user);
$statement->execute();
//...
return ($statement->num_rows > 0);
}
}
Since you are working with classes, you might want to store the results of the query somewhere - asking for their existence implies that you might want to use them.
I shortened the return statement as
if ($a==$b) {
return true;
} else {
return false;
}
is equal to
return ($a==$b);
Why not just use the query statement
SELECT count(*) FROM `data` where `id` = ?
and then just test for the value returned.
This has the benefit of only returning the number of records that match your query rather than matching and returning all the records that do. While that may be okay for a small number of records if your second table has 50,000 records that match you probably don't want to pull all of them just to find out that there are 50,000 of them!
Related
I am trying to check if there were any records (more than 0) in my database table:
$ifExists = DB::select('SELECT COUNT(*) FROM `characters` WHERE userid = ?', array(Auth::id()));
Now I am checking if there are more than 0:
if($ifExists > 0){
return Redirect('/board');
}
else{
return view('intro');
}
It always takes me to the /board. But there are many rows in this database table.
The echo $ifExists; shows me [{"COUNT(*)":0}]
How do I check this number?
Try it this way:
$ifExists = DB::table('characters')->where('userid', Auth::id())->count();
If you do it like in your question, you will receive an array of objects.
If you only want to check for existens of entries and do not need the count, you can just use the exists() function whitch will return you a boolean:
$ifExists = DB::table('characters')->where('userid', Auth::id())->exists();
if($ifExists){
return Redirect('/board');
}else{
return view('intro');
}
Been a while since I've done PHP, but from the looks of it you get a result object from the database. That object is 1 object.
I think that's why it's always redirecting to /board.
Not sure how to do this in PHP, but you want to get the value of "COUNT(*)" from the object for your if statement. Hope that helps :)
I have one script of php which should check if given user exists in Users table, and if not it creates it, if yes then it updates the existing user with new information.
Should I create all in one sql query to do the checks and insert/update or should I first use one php script to get row count and then use second script to insert/update new user?
I know SQL but only the basics, so it is not my strong side.
Also which solution is better towards client/server communication?
I really like to use this function:
function exists($detail, $table, $column, $value) {
$query = mysqli_query($this->connect, "SELECT `$detail` FROM `$table` WHERE `$column` = '$value'");
$count = mysqli_num_rows($query);
if($count >= 1) {
return true;
} else {
return false;
}
}
So if the user exists it will return true else false. After this check I would run another function / query to update a user.
the above function could look like this:
//SELECT `username` FROM `users` WHERE `username` = '$username'
if(exists('username', 'users', 'username', $username)) {
//run this code if true
} else {
//run this code if false
}
I am currently busy on a textbased RPG game, but I am stuck at one part right now.
In order to start a mission, the player does need some items, these are stored in a string: item:1x3-item:5x1 - (basicly item:IDxamount).I have already made a function that explodes the string into variables, but now the script needs to check if the player does have all the items listed.
I've tried to solve the issue with a foreach, but that returns positive or negative for every item, and I only need to know if the player has all items at once.
(don't mind the unsafe query)
$parseAmount is an array, containing all item ID's.
$uid is an variable containing userID
// check if player has all items
foreach($parseAmount as $itemID)
{
$check_query = mysql_query("SELECT * FROM `player_items` WHERE `player`='$uid' AND `item`=='$itemID' AND `value`>='$parseAmount[1]'");
if(mysql_num_rows($check_query)>=1)
{return true;}
else
{return false;}
}
If you want me to post the whole function, please let me know.
If I understood your question correctly you need something like:
foreach($parseAmount as $itemID) {
$sql = "SELECT COUNT(*) AS count
FROM player_items
WHERE player = '".mysql_real_escape_string($uid)."'
AND item = '".mysql_real_escape_string($itemID)."'
AND value >= ".intval($parseAmount[1]);
$row = mysql_fetch_array(mysql_query($sql));
if ($row['count'] == 0) {
return false;
}
}
return true;
You must not early return true. You know the result is true only after checking all the items. My code could be improved by selecting all the items at once, but it's up to you to build this.
Keep in mind my comment about the deprecation of the MySQL extension, using MySQLi and Prepared Statements it will look something like this (note that I never worked with MySQLi before and built it with help of the manual):
foreach($parseAmount as $itemID) {
$sql = "SELECT COUNT(*) AS count
FROM player_items
WHERE player = ?
AND item = ?
AND value >= ?"
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("ssi", $uid, $itemID, $parseAmount[1]);
$stmt->execute();
$row = $stmt->get_result()->fetch_array();
if ($row['count'] == 0) {
return false;
}
}
return true;
This question already has answers here:
How can I detect a create, update, delete query is successful in Codeigniter
(2 answers)
Closed 2 years ago.
I have a model function that updates a user in my CodeIgniter application:
// updates first of a user, return true if successful, false if not.
public function updateFirstName($userId, $newFirstName) {
$this->db->query("UPDATE users SET firstName='$newFirstName' WHERE id=$userId");
return // whether request was successful?
}
How do I return a boolean value that ensures the user of ID $userId has been updated? For instance, it should return false if no user was found with ID $userId.
As commented, have you tried $this->db->affected_rows()?
That will tell you how many rows were updated.
if ($this->db->affected_rows() > 0)
{
return TRUE;
}
else
{
return FALSE;
}
or
if ($this->db->affected_rows() > 0)
return TRUE;
else
return FALSE;
or
return ($this->db->affected_rows() > 0) ? TRUE : FALSE;
EDIT
also(much better)
return ($this->db->affected_rows() > 0);
A better solution I've found is to manage the difference between an ERROR and 0 affected rows. 0 affected rows is not necessarily a bad thing, but an error is something you do want to know about:
if ($this->db->_error_message()) {
return FALSE; // Or do whatever you gotta do here to raise an error
} else {
return $this->db->affected_rows();
}
Now your function can differentiate...
if ($result === FALSE) {
$this->errors[] = 'ERROR: Did not update, some error occurred.';
} else if ($result == 0) {
$this->oks[] = 'No error, but no rows were updated.';
} else {
$this->oks[] = 'Updated the rows.';
}
Just some quick hacking there - you should obviously make the code far more verbose if you have other people using it.
The point is, consider using _error_message to differentiate between 0 updated rows and a real problem.
Check this for more information. Active Records
public function updateFirstName($userId, $newFirstName) {
return $this->db
->where('id', $userId)
->update("users", array('firstName' => $newFirstName));
}
With this way you will also avoid sql injection that you had before
You can use $this->db->affected_rows() in Codeigniter this returns a numeric value when doing "write" type queries (insert, update, etc.).
In MySQL DELETE FROM TABLE returns 0 affected rows. The database class has a small hack that allows it to return the correct number of affected rows. By default this hack is enabled but it can be turned off in the database driver file. (From CI user guide). For deleted row in Ci it returns 1.
You may use $this->db->affected_rows(); to check whether query runs successfully or not
I have use this code for checking update query.
$status = $this->db->query("UPDATE users SET firstName='$newFirstName' WHERE id=$userId");
if($status)
return true;
else
return false;
public function updateInfo($newinfo) {
$this->db->update("some_table", $newinfo);
return ($this->db->affected_rows() > 0);
}
This will either return true or false
Use a stored procedure, you can check the result.
Below is a stored procedure example :
CREATE DEFINER=`root`#`localhost` PROCEDURE `usp_UpdateInfo`(tableId int,tableName varchar(100) charset utf8,description varchar(400) charset utf8)
BEGIN
declare exit handler for sqlexception select 0 as `result`;
update table
set `name` = tableName,
description = description
where id = tableId;
select 1 as `result` ;
END
PHP example code :
$this->load->database();
$rs = $this->db->query('call usp_UpdateInfo(?,?,?)',array($tableId,$tableName,$description));
$this->db->close();
return $rs->result_array();
Try this:
public function updateFirstName($userId, $newFirstName) {
$this->db->where('id', $userId);
$this->db->set('firstName', $newFirstName);
$sql = $this->db->update('users');
if ($sql) { return TRUE; } // $sql - boolean true or false
}
I want to make my own function which performs in a similar manner to the following actual code.. ie
if(mysql_num_rows($res) == FALSE) {
// DO SOMETHING BECAUSE THERE ARE NO RESULTS
}
In my code, i'm repeating an SQL statement a few times around the place, and if there are results, then I go ahead and do stuff.
What I'd like to do is create my own FALSE return in my own function ie
if(my_special_function($variable) == FALSE) {
// DO STUFF
}
Is this as simple as in my special function having something like...
function my_special_function($variable) {
$sql = 'SELECT field FROM table WHERE something=$variable';
$res = mysql_query($sql);
if(mysql_num_rows($res) == FALSE) {
return FALSE;
} else {
return TRUE;
}
}
?
You can make your special function even simpler:
function my_special_function($variable)
{
$sql = "SELECT field FROM table WHERE something='{$variable}'";
$res = mysql_query($sql);
return mysql_num_rows($res) > 0;
}
Yes, that is all for a function. Why don't you try such things first before asking whether it works or not?
You should add additional error checking for mysql_query and replace $sql = 'SELECT field FROM table WHERE something=$variable'; by:
$sql = 'SELECT field FROM table WHERE something='.$variable;
I'd revise it a bit
function my_special_function($variable) {
$sql = "SELECT field FROM table WHERE something=$variable";
$res = mysql_query($sql);
if(mysql_num_rows($res)) {
return TRUE;
}
return FALSE;
}
Changes
No need for the else { ... } as if the if evaluation is true, it won't go any further, if it isn't, then FALSE is returned.
Changed the if statement to if(mysql_num_rows($res)) as mysql_num_rows() will return FALSE on failure, and a number on everything else. So, if there's 0 affected rows, or an error you won't get the return TRUE.
Inside your $sql variable you had single quotes, the literal $variable would be passed rather than what was passed to the function
I can see a few problems.
Variable interpolation does not happen in single quotes, also its advisable to not to substitute variable directly into queries.
$sql = 'SELECT field FROM table WHERE something=$variable';
should be
$sql = 'SELECT field FROM table WHERE something='.mysql_real_escape_string($variable);
mysql_num_rows returns false when there is a problem, say when its parameter is not a valid resource. If you really want to check the case of "no rows returned" you need to check its value for 0