I'm working on some web code which uses codeigniter and the built in querybuilder to access a database.
I attempt to load data from the database for the current user
$userModel = $this->loadModel('ModelUser');
$name = $this->session->userdata('user');
$user = $userModel->getUser($name);
This is the code forgetUser:
function getUser($username)
{
$this->db->where('username',$username);
$query = $this->db->get('tblusers',1);
$res = $query->result();
if ($query->num_rows() > 0)
{
log_message('debug','Got user. ID = '.$res[0]->id);
foreach($res[0] as $key => $val)
{
$this->$key = $val;
}
return $this;
}
else {
log_message('info','failed to find user '.$username);
return NULL;
}
}
This works fine except when I let the session expire, in which case I get the details of another user.
These are the results of testing getUser:
$userModel->getUser("Admin"); //Got user. ID = Admin_ID
$userModel->getUser("john"); //Got user. ID = John_ID
$userModel->getUser(""); //Failed to find user
$userModel->getUser(null); //Failed to find user
When I log in as Admin then let the session timeout, the top snippet logs the message:
Got user. ID = John_ID
I would expect either Got user. ID = Admin_ID or Failed to find user
When $this->session->userdata('field') does not find an entry, it returns 0 instead of the "" or null that I was testing against.
Logging $this->db->last_query() showed this since the resulting query was:
SELECT * FROM tblusers WHERE username = 0 LIMIT 1;
MySQL will automatically convert strings to integers where the string starts with an integer. A string without an integer will be cast to 0 as explained in this answer. The query was returning the first entry it came across instead of finding no rows as any string that didn't start with 1-9 would match the WHERE clause.
I added a clause to getUser to return NULL if $username == ''. I did try === 0 but that yielded the same error so there's some type coercion going on that I'm not 100% certain of, but this covers the issue nicer than handling the case each time getUser is called.
I'm an old school developer and just getting in the WWW programming world. I'm developing an application with HTML, CSS, PHP and MSSQL Server 2008 R2 for the company i'm working with.
In my application I'm using stored procedures to insert, modify, delete or query information from/to the database. Not using TSQL instructions at all, just executing stored procedures from the PHP code.
I'm using PHP 5 and SQLSRV driver for database interaction.
Everything working fine so far, but now I'm stuck on the Insert piece... If everything is ok, the SP inserts the record, if not, it doesn't... but i'm not seeing the result until i query the table again just to see if the record is there or not.
Im using the following code in PHP to run the SP that inserts the record in the table:
function spinserta($tabla, $columnas, $valores, $cnct) {
$stmt = 'Exec spinsert #tabla=?,#columnas=?,#valores=?';
$params = array($tabla,$columnas,$valores);
$result = sqlsrv_query($cnct,$stmt,$params) ;
return $result;
}
if the transaction is not succesful, im not getting anything in the $result variable and would like to have the resulting message from the SP in order to display an error message to the user.
How to get the resulting message from the SP (no matters if it is an error or not)?
Thanks in advance!
This is some code that I have in one of my applications. See if it helps:
//Query SQL
$tsql = "Exec spinsert #tabla=?,#columnas=?,#valores=?";
$params = array($tabla,$columnas,$valores);
//Execute the stored query
$stmt = sqlsrv_query($conn, $tsql, $params);
if ($stmt === false)
{
echo "<h3>Error in query preparation or execution.</h3>";
ListErrors();
die;
}
else {
echo "Insert Successful";
}
// this should help for the non-insert/update case
$arr = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
var_dump($arr);
after hours of researching.... finally got the concept! here is the thing: the original PHP code was:
function spinserta($tabla, $columnas, $valores, $cnct) {
$stmt = 'Exec spinsert #tabla=?,#columnas=?,#valores=?';
$params = array($tabla,$columnas,$valores);
$result = sqlsrv_query($cnct,$stmt,$params) ;
return $result;
}
and the original SP was:
ALTER PROCEDURE [dbo].[spinsert]
#tabla varchar(50),
#columnas varchar(8000),
#valores varchar(8000)
AS
BEGIN
SET NOCOUNT ON;
declare #orden varchar(8000)
declare #return_value int
set #orden='Insert into ' + #tabla + ' (' + #columnas + ') values (' + #valores + ')';
execute (#orden);
return
END
very straight forward... When the php code was executed and the SP succeded, the variable $result was loaded with "Resource id#14", if the SP failed, the $result value was null.
Things were working well!!! But not the way i wanted. Then i found this article: http://msdn.microsoft.com/en-us/library/ms178592.aspx
Based on that I modified the SP:
ALTER PROCEDURE [dbo].[spinsert]
#tabla varchar(50),
#columnas varchar(8000),
#valores varchar(8000)
AS
BEGIN
SET NOCOUNT ON;
declare #orden varchar(8000)
declare #return_value int
begin try
set #orden='Insert into ' + #tabla + ' (' + #columnas + ') values (' + #valores + ')';
set #return_value=0;
execute (#orden);
end try
begin catch
DECLARE #ErrorMessage NVARCHAR(4000);
DECLARE #ErrorSeverity INT;
DECLARE #ErrorState INT;
SELECT #return_value = ERROR_NUMBER()
SELECT
#ErrorMessage = ERROR_MESSAGE(),
#ErrorSeverity = ERROR_SEVERITY(),
#ErrorState = ERROR_STATE();
RAISERROR (#ErrorMessage, -- Message text.
#ErrorSeverity, -- Severity.
#ErrorState -- State.
);
end catch
return #return_value
END
and the PHP code:
function spinserta($tabla,$columnas,$valores,$cnct) {
$tsql = 'Exec spinsert #tabla=?,#columnas=?,#valores=?';
$params = array($tabla,$columnas,$valores);
$stmt = sqlsrv_query($cnct,$tsql,$params) ;
$errors=sqlsrv_errors();
if ($stmt === false or $stmt===0) {
foreach( $errors as $error ) {
$stmt=str_replace("'","","Error: ". $error['code']. " - " . $error['message']);
}
} else {
$stmt="1";
}
return $stmt;
}
There were two problems with my original approach, 1 at database engine side, the SP was not really generating a system error, even though the statement failed. With the Try-Catch, technique, pluse the RAISEERROR concept, the SP was finally generating the system error when the statemente failed. After this, it was just matter of minor adjustments to the PHP code.
With this approach, the validation of information sent to the database, is done at Database Engine side, eliminating the need of writing a lot of code, just to validate the fields in the forms at the submission time. what is needed is to ensure database tables, relationships, constraints, integrity and others are well applied, and the database will protect itself against incorrect data. If errors with information provided in the form are submited, the database will reject them and the code will show to the user the proper errors behind.
I would like to see if something similar is doable with MySQL..., i think so!
Many thanks to Maximus2012!!! Cheers!!!
The following 2 queries are the result of an echo in php:
UPDATE glymping_userdata
SET current_location_gps = '51.9171115;4.484812'
WHERE id = 1
and
UPDATE glymping_user_has_appointments
SET status = 'enroute',
start_location_gps = '51.9171115;4.484812'
WHERE userId = 1
AND appointmentId = 47
Both queries work when entered manually in the database and all fields are filled correctly. When I let the php file run the queries, the queries are like shown above, but the "start_location_gps" and the "current_location_gps" are empty.
The values in the queries are strings and the database fields are a varchar(30). Yet the fields in the database are empty.
The location value is received from a post method.
Does anyone knows what I am forgetting or doing wrong?
EDIT:
php example
public function SendQuery($query)
{
$results = $this->mysqli->query($query);
return $results;
}
public function UpdateUserLocation($currentLocationGps)
{
$query = "UPDATE ".DB_PREFIX."userdata
SET current_location_gps = '{$currentLocationGps}'
WHERE id = ".$this->userId;
//echo $query;
$this->db->SendQuery($query);
}
Your current code doesn't check the return value of mysqli_query; the query might fail "silently". It could also be that the query does not affect any records in the database becaue of wrong values in the WHERE clause.
Try it with
if ( !$this->db->SendQuery($query) ) {
// query failed: syntax error, connection lost, access denied,duplicate entries, ...
trigger_error($this->mysqli->error);
}
else {
if ( 0 < $this->mysqli->affected_rows ) {
// WHERE clause doesn't match any record, no values changed, ...
trigger_error('no rows affected');
}
}
Your query might also be prone to sql injections, please check http://php.net/manual/en/security.database.sql-injection.php
I am developing a user/login system, wherein I have a small php function below that updates the user values in a DB when certain condition is met (i.e. when username and password matches). However, nothing seems to happen on the login page. I am using Ubuntu and on the terminal it shows that the variable $pk_user is empty. The problem is that I want to print the values of pk_user but echo, print_r, var_dump nothing prints anything on the browser. I have CSS styling, would that be the reason? The function is:
/* updateUserField - Updates a field, specified by the field parameter,
in the user's row of the database, given the pk_user */
public function updateUserField($userkey, $field, $value)
{
$q = "UPDATE users SET ".$field." = '$value' WHERE pk_user = '$userkey'";
pg_query($this->link,$q);
if(pg_last_error($this->link)) {
return -1;
}
return 1;
}
and the error message on command line is:
ERROR: invalid input syntax for
integer: "" at character 82 STATEMENT:
UPDATE users SET usr_userid =
'9bc44a3b3b0b911f7f932f06ab7d7b5c'
WHERE pk_user = ''
Of course I connect to DB with pg_connect and that part is working okay.
You're not supplying an integer as the $userkey variable when you call the function. Therefore, the query is failing. Check your code where you actually call the function to determine why an integer isn't being passed.
I have a very strange problem.
Situation: Session handling over MySQL, PHP 5.2.4, wildcard cookies, FF/Opera/Safari/Chrome works, IE7/8 not.
When I save a variable into the session, the value is lost. The DB shows after the write action only "N" instead of "123456".
Example:
$bar = 123456;
$_SESSION['foo'] = $bar;
But when I save a constant in the session, it works.
$_SESSION['foo'] = 123456;
This is not really a client problem, but only in IE it doesn't work.
Any ideas?
Edit:
This is the session write function:
function _write($id, $data) {
$write = "UPDATE session SET time='".time()."', data='".mysql_real_escape_string($data)."' WHERE id='".mysql_real_escape_string($id)."'";
$result = #mysql_query($write);
if(mysql_affected_rows()) return $result;
else {
$write = "INSERT INTO session (id, time, data) VALUES ('".mysql_real_escape_string($id)."', '".time()."', '".mysql_real_escape_string($data)."')";
return #mysql_query($write);
}
}
When I print the update query ($write) everything looks fine. I can execute the SQL manually and it works, also with variables.
Maybe sessionId in cookie every time is refreshing in IE?
SO every time - new session