save MySQL rows in an array and save it in session variable - php

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];

Related

How exactly does mysqli(a,b,c,d)->query(sql)->fetch_assoc() work?

I am new to php and mysqli and have been going through and trying to understand how a lot of these built in functions work. I have read the documentation and many tutorials/examples.
I have something like:
$conn = new mysqli(vars); <br />
$sql = "Select * from Users where name ='$name'";
$result = $conn->query($sql);
$pass = result->fetch_assoc()['Pass'];
//check password stuff
that works fine, however if I then try to use $result->fetch_assoc()['ID'] it returns null. If I swap the order of ID and Pass then the id returns and pass comes back null.
I don't understand why this is the case. What I think (which is clearly wrong) is that result should store the whole row (which it does) and then when i fetch assoc I should just be pulling data from the row. However it seems to be overwriting result when I fetch assoc. What's up with that?
My work around is to call the query multiple times for each data point i need to start a session and store variables, and I know I can use prepared statements, but I feel like there's a better way and I'm missing it.
Can someone please explain?
Every time you call fetch_assoc(), it fetches the next row. There'll presumably only be one user with a specific name, so the result of the second fetch_assoc() call will be null.
Store the value of $result->fetch_assoc() and you can do what you want with it afterwards.
$user = $result->fetch_assoc();
echo $user['ID'];
echo $user['Pass'];

Login issue , in $_SESSION[' IDONTKNOWHERE ']=$rowacc[0];

THIS code is solved but there some problem in the last code
$username=mysql_real_escape_string($_POST['user']);
$password=mysql_real_escape_string($_POST['pass']);
$sqlacc="SELECT * FROM members INNER JOIN accounts ON
account.mem_id =members.mem_id WHERE members.firstname='$username' and accounts.password='$password'";
$resultacc = mysql_query($sqlacc);
$countacc = mysql_num_rows($resultacc);
$rowacc = mysql_fetch_array($resultacc, MYSQL_NUM);
This is my problem i dont know what field name will put in $_SESSION[' '],
if($countacc==1){
$_SESSION[' IDONTKNOWHERE ']=$rowacc[0];
$_SESSION[' IDONTKNOWHERE ']=$rowacc[1];
header("location:content/index.php");
}
else{
header("location:login.php");
}
?>
Using numerical keys for fetching data from the record set is a bit confusing, so I would suggest you to use associative keys instead. Firstly, print your whole record set using the following code :
echo 'details = <br><pre>';
print_r($rowacc);
This will output your record set in a well formatted manner, so that you can get an exact idea of what data have been fetched by you SQL query. You will also be able to see the numerical as well as the associative keys. So for getting the data you can use something like :
$_SESSION['username'] = $rowacc['firstname'];
$_SESSION['password'] = $rowacc['password'];
Later you can access those stored session values as :
$username = $_SESSION['username'];
$password = $_SESSION['password'];
They are key indexes. Use any value so that later on you can access them. For example if you are storing username in session then that will be $_SESSION['username']. I suggest you to use print_r($rowacc); So that you know what value stored in your record set.
I guess, it should be:
$_SESSION['mem_id']=$rowacc[0];
$_SESSION['mem_firstname']=$rowacc[1];
If you can share the script where the login is being checked, we can provide a better solution.
You can make any variable name as your session variable.
Same as the naming convention for variables.
Session variables are named for later accessing, so be meaningful, identifiable and relates to its value.

Put all the associative array in one variable

I have some associative array whose values are inserted from a while{}.
//some sql select
$comar=array();
while($row=mysql_fetch_array($result)){
//another sql countrow
$rowdd=mysql_fetch_row($result);
$postuid=$row[2];
$comar[$postuid]= $rowdd[count(idnum)];
$_SESSION['comar']=$comar;
}
But this code just displays the idnum for last postuid. How do i add it all to one variable and then put that in a session.
Don't set your session variable in the while loop
count(idnum). This makes no sense. Is idnum a constant. If so your fetching the same row.
What do you mean another SQL countrow. You're trying to fetch a row for which you have alreay run a fetch_array on. This makes no sense, and is probably the root problem

Trying to define variables from the results of a query in php

I am trying to define variables from the results of a query, but I cannot manage to get this to work. I am trying to make my site multilangual, so I want to define a lot of text items (identifiers) that I have stored in a database. The table looks like this:
ID, Identifier, English, Dutch
1, Owned_by, "Owned by", "Eigendom van"
2, Owner_of, "Owner of", "Eigenaar van"
etc
etc
where the Column Identifier is the variable that I want to define and 1 of the 2 languages is the value that I want to give the variable. I have define a previous query from which the result is the language requested by the user, so $language_2 is the outcome from the previous query. So when $language_2 = "Dutch", I would like all the records in the table to be defined with the value in the column "Dutch".
When I use the code below the variables will be printed (echoed) but I cannot use them as an actual variable to use in my site.
$sql_3 = "SELECT Identifier, ".$language_2." as Language FROM translate";
$result_3 = mysql_query($sql_3) OR die (mysql_error());
while ($row_3 = mysql_fetch_array($result_3))
{
echo "$".$row_3['Identifier']." = '".$row_3['Language']."';<BR>";
}
How can I get them to actually become a variable that I can use in my site?
Add brackets arround the string that is the variable name:
${$row_3['Identifier']} = $row_3['Language'];
You can use mysql_fetch_assoc() to get an associated array if you must use the older mysql_* functions, then use variable variables to get what you want
$$row_3['Identifier'] = $row_3['Language'];
${$row_3['Identifier']} = $row_3['Language'];

Storing temp values in session array to use in mysql query

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.

Categories