This question already has answers here:
Accessing random rows from database without repetition
(2 answers)
Closed 4 years ago.
from the past few days i have had this problem with a quiz scenario in created as part of my project. i wanted random questions to be asked but when i use the rand() function , the questions are being repeated. also i figured out that since its being done on the same page and every time the page refreshes, the random number is again selected thereby leading to this flaw! so i considered storing the value of the last random que_id in a session and generating a query like so:
enter code here <?php session_start();$jsqla=mysql_query("select que_id from mst_que");$jfeta=mysql_fetch_assoc($jsqla);session_start();$id=array($jfeta['id$_SESSION['id'][] = $id;$rs=mysql_query("SELECT * FROM `mst_que` WHERE que_id NOTIN ('id') ORDER BY RAND() ")
Please help me in this. I just want to create a session array where i want to store the previously generated random number and use it in query so that it is not repeated again. please
Store it in a variable and unset it from the array of questions:
function get_question($questions)
{
$question = rand($questions);
$questionKey = array_search($question, $questions);
unset($questions[$questionKey]);
return $question;
}
Try creating an array and then assign it to any session variable, for example:
$quizQuestions[] = $questionId;
$_SESSION['question'] = $quizQuestions;
In case you want to update the value, simply fetch it and assign new value and update it in the same variable again:
$quizQuestions = $_SESSION['question'];
$quizQuestions[] = $questionId;
$_SESSION['question'] = $quizQuestions;
Make sure that you have a session started first, add the following code to the very start of this script:
if(!isset($_SESSION)) {
session_start();
}
Related
This question already has answers here:
getting the value of the single field output using the codeigniter active record
(5 answers)
Closed 2 years ago.
hi want to get only one column from one result from my database. So i do it in this way
$this->db->select('myclolumn')->where('id',$id);
$query = $this->db->get('mytable');
$temp=$query->row_array();
$finalresult=$temp['mycolumn'];
Maybe there is a easier or faster way to do the same?
so based on DanishAli's comment
$this->db->select('myclolumn')->where('id',$id);
$query = $this->db->get('mytable');
$finalresult=$query->row()->mycloumn;
You can do it like this:
$finalresult = $this->db->select('myclolumn')
->where('id',$id)
->get('mytable')->row()
->mycolumn;
All in only one command instead of a lot of variables and extra code.
In case you need to provide a default value if the row is null, break the command to:
$row = $this->db->select('myclolumn')
->where('id',$id)
->get('mytable')
->row();
$finalresult = ($row)?$row->mycolumn:'your default value';
This question already has answers here:
How can I loop through a MySQL result set more than once using the mysql_* functions?
(7 answers)
Closed 6 years ago.
So basically I have the following loop to iterate database rows:
while($row = $mysql->fetch_assoc())
But I need to access the rows before this loop as well. So, I do this:
$inside = $mysql->fetch_assoc()
and $mysql loses its rows. When it gets to the while loop it simply does not enter it as the condition becomes NULL.
I tried the following
while($row = $inside)
but this just waits until timeout (loops indefinitely).
Any idea on how I could perform this, making up for the requirements above? Thank you very much for your help...
After you do this :
while ( $row = $mysql->fetch_assoc() )
The internal pointer of $resul is at the end. So you can move it to the beginning again :
$mysql->data_seek( 0 );
while ( $row = $mysql->fetch_assoc() )
All the rows are available again.
Use $mysql->data_seek(0) before to reset the row counter on your second loop iteration. It will allow you to loop through the rows again. See this helpful post for an example.
This question already has answers here:
fetch single record using PHP PDO and return result
(2 answers)
Closed 6 years ago.
I have not made the change from MySQL_ to PDO until today. Needless to say, the migration is more than a simple headache. So, I need a bit of help. I tried all the search terms I could before registering and asking this question.
My Problem
User types a numeric code into the search box, translates it to
.php?code=term
Script selects all columns from the database where the code is the
code term searched for.
PHP will Echo the results
My Code
if (isset($_GET["code"])) {
//IF USER SEARCHES FOR CODE, RUN THIS. ELSE SKIP.
$crimecode = $_GET["code"];
$crcode = $link->prepare("SELECT * FROM crimecodes WHERE code = :code");
$crcode->bindParam(':code', $crimecode);
$crcode->execute();
$coderesult = $crcode->fetchAll();
echo "<h4>CODE:</h4>";
echo $crimecode;
echo "<br /><h4>DEFINITION:</h4>";
echo $coderesult;
die();
}
Before, it was simple. All I had to do was:
$qcode = mysql_query("SELECT * FROM crimecodes WHERE code = $crimecode");
$fcode = mysql_fetch_assoc($qcode);
echo $fcode['definition'];
But, the ever evolving world has decided to fix something that wasn't broken so now the whole prior code is pointless and you gotta learn something new. Any help is appreciated to get this to work.
Right now, the above PDO code returns definition: ARRAY.
Like literally, the $coderesult prints Array.
The fetchAll() option returns an array containing all of the result set rows (http://php.net/manual/pt_BR/pdostatement.fetchall.php).
$coderesult prints Array because it's actually an array. If you do var_dump($coderesult) you'll see it.
I suppose that you are trying to get one row only. If that's the case, add this line after $coderesult = $crcode->fetchAll();:
$coderesult = $coderesult[0];
Then you can
echo $coderesult['definition'];
If you're trying to get more than one row, you need to use foreach to loop through the array.
I suggest you read the php manual for PDO Class or mysqli, wherever you prefer. There's a lot more options than mysql_.
Also, I think it's worth to mention that your previous code
$qcode = mysql_query("SELECT * FROM crimecodes WHERE code = $crimecode");
$fcode = mysql_fetch_assoc($qcode);
echo $fcode['definition'];
it's vulnerable to SQL Injection.
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.
So I am trying to display answers to a survey but first I want to separate the USER ids from each other. Right now Answers are stored similar to this....
SGpID, SGresult, SGFACemail
Essentially, I want to display a button for each Unique ID. So if I have 5 answers with an ID of 10, and 5 answers with an ID of 12. I want buttons saying "Results for ID 10" and "Results for ID 12".
What it is currently doing is displaying EVERY iteration where the select statement matches so essentially every answer... no bueno.
My thought was that I would go through a for each loop to separate the results and do something along the lines of...
"Each time SGpID is different", display a new button with that new SGpID.
I am just not sure really how to write it out. Here is what I have so far for the statement.
$query_db = ("SELECT SGpID FROM SGresult WHERE SGFACemail = '$email'");
$result = mysql_query($query_db) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
//insert for each loop here?
echo $row['SGpID'];
}
Thanks as always for any help or ideas on this one!
Change your SELECT command to:
SELECT DISTINCT SGpID FROM SGresult WHERE SGFACemail = ?
Note I have used ? in place of '$email' as you really should use prepared statements. Learn from Bobby Tables!