I have a view that needs updating with a list of id's. So I am storing the values that have been selected to remove from the view in a session variable that then goes into the mySQL query as below. Then when the form is reset the values are also reset out of the array.
But its not working... this is what I've got.
Any help would be appreciated.
if($_POST['flag']=='flag'){
//collect deleted rows
$_SESSION['delete-row'][] = $_POST['idval'];
//Split session array
$idavls = join(',' , $_session['delete-row'];
$sqlDelete = "CREATE OR REPLACE VIEW filtetbl AS SELECT * FROM `".$page['db-name']."`.`leads_tbl` WHERE ".$_SESSION['filter-view']." AND `lead_status` = '1' AND `lead_id` NOT IN (".$idvals.") ORDER BY `lead_added`";
$result = mysql_query($sqlDelete);
if($result){
echo true;
}
else{
echo mysql_error();
}
}
$_session isnt the same as $_SESSION for a start.
Also dont use mysql_query or similar (because it isnt safe) use PDO
This is hard to correct without more information (and there are several errors - probaby cut and paste) so I'll pull apart one by one and you can go from there.
1 - $_SESSION['delete-row'][] = $_POST['idval'];
If 'idval' comes from multiple inputs (i.e. ) then it is already an array, and you should have $_SESSION['delete-row'] = $_POST['idval']; If you are looping in an array of inputs (i.e. trying to append for many posts from then it is correct)
2 - $idavls = join(',' , $_session['delete-row'];
$_SESSION (you said this was a type) and you also need a bracket/bract ar the end
$sqlDelete = "CREATE OR REPLACE VIEW filtetbl AS SELECT * FROM ".$page['db-name'].".leads_tbl WHERE ".$_SESSION['filter-view']." AND lead_status = '1' AND lead_id NOT IN (".$idvals.") ORDER BY lead_added";
Firsly this is very insecure as pointed out by allen213. Even if you don't use PDO to make safe the variable, please cast all the inputs as (int) assuming the IDs are integers, or at least wrap the input in mysql_real_escape_string().
Secondly, the logic in the question doesn't quite make sense. You say you want to remove IDs from the view, but what you are doing is recreating the view with only those IDs in $_SESSION['delete-row'] removed - so this may re-introduce IDs previously removed from the view. You'd actually need to keep $_SESSION['delete-row'] and keep adding to it to ensure the next time the view was created, then all the IDs are removed.
I hope that helps. If not, more code may be required (i.e. the form you are using the send data, anythign else that affects sessions etc.
Related
I want to get rows from MySQL Database and save two specific values(row[0] & row[6]) in $_SESSION variable for comparison later on.
The code looks like below:
$sqlResult =mysql_query("SELECT * FROM questionbank WHERE quizName ='$quizNames' ORDER BY RAND() limit 6")
while ($row= mysql_fetch_array($sqlResult))
{
$questionPkId = $row[0];
echo $_SESSION['$questionPkId'] = $row[6];
}
The Problem is I can't get this values in other pages. Can I make an associative array with session variable (though i tried array_push(), But it did not work).
A couple issues with your code. First up, make sure you call session_start on any page that uses sessions. Without it, you will not be able to access the variables previously set.
Second up, when a variable is called inside single quotes it is taken literally, meaning your session define statement is always assigning the variable to same thing, and hence overwriting what it should be.
$_SESSION[$questionPkId] = $row[6];
And that will assign the value to the actual value of $questionPkId. Aside from those issues, your session items should work, and if they are not you will need to provide us with more of your code.
Try without single quotes:
$_SESSION[$questionPkId] = $row[6];
I'm using a SELECT query to obtain a variable using mysql_fetch_assoc. This then puts the variable into an UPDATE variable to put the returned value back into the database.
If I hard code the value, or use a traditional variable and it goes in just fine, but it doesn't work when using a value previously retrieved from the database. I've tried resetting the array variable to my own text and that works.
$arrgateRetrivalQuery = mysql_query(**Select Query**);
$arrGate = mysql_fetch_assoc($arrgateRetrivalQuery);
$arrivalGateTest = $arrGate['gatetype'];
$setGateAirportSQL = "UPDATE pilots SET currentgate = '".$arrivalGateTest."' WHERE pilotid = '".$pilotid."'";
$setGateAirportQuery = mysql_query($setGateAirportSQL);
// Close MySQL Connection
mysql_close($link);
This will just make the field to update have nothing in it, however whenever I remove the variable from the SELECT to one I define, array or not, it will work.
Hope this is clear enough. Thanks in advance.
Is arrivalGateTest a number or a string? How did you try to put another value in the query? If you are sure the previous query returns a value, try to write: $setGateAirportSQL = "UPDATE pilots SET currentgate = '$arrivalGateTest' WHERE pilotid = '$pilotid'";.
Just change your sql to inlcude a subquery.
You could use the following general syntax:
UPDATE pilots SET currentgate = (SELECT gate FROM airport WHERE flight='NZ1') WHERE pilotid='2';
which is demonstrated on this fiddle
This saves the extra query and more accurately describes what you are trying to achieve.
WARNING - test it carefully first!
usersim interested how do i select a text field form my mysql database, i have a table named users with a text field called "profile_fields" where addition user info is stored. How do i access it in php and make delete it? I want to delete unvalidate people.
PHP code
<?php
//Working connection made before assigned as $connection
$time = time();
$query_unactive_users = "DELETE FROM needed WHERE profile_fields['valid_until'] < $time"; //deletes user if the current time value is higher then the expiring date to validate
mysqli_query($connection , $query_unactive_users);
mysqli_close($connection);
?>
In phpmyadmin the field shows (choosen from a random user row):
a:1:{s:11:"valid_until";i:1370695666;}
Is " ... WHERE profile_fields['valid_until'] ..." the correct way?
Anyway, here's a very fragile solution using your knowledge of the string structure and a bit of SUBSTRING madness:
DELETE FROM needed WHERE SUBSTRING(
profile_fields,
LOCATE('"valid_until";i:', profile_fields) + 16,
LOCATE(';}', profile_fields) - LOCATE('"valid_until";i:', profile_fields) - 16
) < UNIX_TIMESTAMP();
But notice that if you add another "virtual field" after 'valid_until', that will break...
You can't do it in a SQL command in a simple and clean way. However, the string 'a:1:{s:11:"valid_until";i:1370695666;}' is simply a serialized PHP array.
Do this test:
print_r(unserialize('a:1:{s:11:"valid_until";i:1370695666;}'));
The output will be:
Array ( [valid_until] => 1370695666 )
So, if you do the following, you can retrieve your valid_until value:
$arrayProfileData = unserialize('a:1:{s:11:"valid_until";i:1370695666;}');
$validUntil = arrayProfileData['valid_until'];
So, a solution would be to select ALL items in the table, do a foreach loop, unserialize each "profile_fields" field as above, check the timestamp, and store the primary key of each registry to be deleted, in a separate array. At the end of the loop, do a single DELETE operation on all primary keys you stored in the loop. To do that, use implode(',', $arrayPKs).
It's not a very direct route, and depending on the number of registers, it may not be slow, but it's reliable.
Consider rixo's comment: if you can, put the "valid_until" in a separate column. Serializing data can be good for storage of non-regular data, but never use it to store data which you may need to apply SQL filters later.
I want to save in a session variable on php an auto increment value field from one SQL table, just next to do the insert on that table. Why it appears empty? What should I do?
Because I check my sql statement on the database and everything is correct, all of that and have values.
$usersetdataregister="INSERT INTO `questionnaire`.`tbluserset`(`UserIDFKPK`, `QuestionSetIDFKPK`) VALUES ('$UserId','0')";
mysql_query($usersetdataregister);
$query_usersetID= "SELECT tbluserset.UserSetIDPK
FROM tbluserset
INNER JOIN (SELECT US.UserIDFKPK, MAX(US.Timestamp) AS MaxTimestamp
FROM tbluserset AS US
WHERE US.UserIDFKPK ='$UserId'
GROUP BY US.UserIDFKPK) AS USL ON tbluserset.UserIDFKPK = USL.UserIDFKPK AND tbluserset.Timestamp = USL.MaxTimestamp";
$row_UserSetIDPK = mysql_query($query_usersetID);
$UserSetID= $row_UserSetIDPK['UserSetIDPK'];
$_SESSION['UserSetIDPK']= $UserSetID;
Next to do this i want use the value on a query statement and UserSetIDPK appears empty.
I think you forgot to start your session.
session_start();
$_SESSIONS['UserSetIDPK'] = $UserSetID;
You should also check what $row_UserSetIDPK is returning. If it's empty then there is something wrong with your query, or he can't find any results in your database.
If it's not empty, you should see if $row_UserSetIDPK['UserSetIDPK'] is the right way to get your value.
to debug try this:
var_dump($row_UserSetIDPK);die();
Hope this helps a bit, 'cause your post is quite a mess! :-)
I am trying to track pageviews on my site whether a user is logged in or not and so I'm capturing the sessionId in my log. I only want to show tracking results for session ids that have at some point logged in and so my flow is as follows:
$pagestats = $wpdb->get_results("SELECT * FROM wp_user_stats WHERE uid=".$_GET['viewstats']);
$sessionArray = array();
foreach($pagestats as $checkSession)
{
if( !(in_array($checkSession->sessionId, $sessionArray)))
{
$sessionArray[] = $checkSession->sessionId;
}
}
Next, I am trying to gather all of the stats concerning any session Ids generated by this particular user ...
$sessions = join(',',$sessionArray);
$pagestats = $wpdb->get_results("SELECT * FROM wp_user_stats WHERE `sessionId` IN($sessions)") or die(mysql_error());
This is the part that throws the error. The error is:
Unknown column 'sjhntmqhltknks8pbhr750voe7' in 'where clause'
I don't understand why it's trying to find a column that matches the session Id instead of a result within that column.
The session IDs probably aren't getting quoted so the query looks like WHERE sessionID IN(abc, def, ...).
One way to fix that would be to change a line in the first loop:
$sessionArray[] = "'".$checkSession->sessionId."'";
Or you could create a second array with the quoted values.
The problem is that the session id is not numeric and needs to be wrapped in quotes. Something like the following would add proper quote to your $sessions string:
$sessions = "'" . implode("', '", $sessionArray) . "'";
You should also make sure you are escaping any user supplied input (e.g. $_GET['viewstats']) before using them to help avoid SQL injection attacks. It wouldn't hurt to escape $checkSession->sessionId as you are adding it to the $sessionArray array either.
If you are using a framework (it looks like you may be using WordPress) read the manual for the database component as it may provide functions to handle some of this for you.
I think you need to put quote around your session values
$sessions = "'".join("','",$sessionArray)."'";
Right now it's like WHERE IN (a,b,c) instead of WHERE IN ('a','b','c').
$pagestats = $wpdb->get_results("SELECT * FROM wp_user_stats WHERE `sessionId`=$sessions") or die(mysql_error());
This isn't an answer to the specific issue, but isn't the second SELECT statement unnecessary? If it is all stored in one table (unless there is a typo...) then SELECT * FROM wp_user_stats WHERE uid=$_GET['view_stats'] would retrieve all sessions for that user. Perhaps you need it done for multiple users? Even at that, you could simply do a GROUP BY clause.
Maybe I'm missing something though -- if so, sorry.