Alternative to PHP $mysql->fetch_assoc()? [duplicate] - php

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.

Related

Faster way to fetch a single data from db with codeigniter [duplicate]

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

fetch data from mysql table and display [duplicate]

This question already has answers here:
fetch(PDO::FETCH_ASSOC only returning one row
(2 answers)
Closed 3 years ago.
I am trying to fetch image name stored in database and display it but it is not working? Can anyone please tell me what is wrong in below code:
<p class="phase-title-en">
<?php
$title="SELECT DISTINCT record_step_one FROM phase_one_data";
$vartitle=$dbh->prepare($title);
$vartitle->execute();
$result= $vartitle->fetch();
?>
</p>
<?php foreach($result as $fn_title) {
echo "<p> '".$fn_title['record_step_one']."'</p>";
}
?>
My database looks like this:-
Your main problem is that you are using the PDO fetch() method, which returns only the next row of the result set (in your case, the first row).
This way, when you do a foreach, you are actually iterating over the columns of your first row (and not over all the rows, as you intended).
So your code is probably throwing lots of error messages (actually E_NOTICES) telling you that you are trying to use a string as an array, because each of the values in the loop ($fn_title) are strings containing the values for the first row (5, 2, eagle, etc).
EDIT: Sorry, but in my original reply I didn't notice the DISTINCT keyword in your query. So actually, the foreach would run only once, and the value would be the string eagle. But still, the problem is the same, there is no index record_step_one inside the string eagle.
The first step towards your solution would be to replace fetch() with fetchAll(), and check for any other errors that may arise (for instance, we can't see where $dbh is being instantiated in your code, which may or may not be a problem).

How to add randomize row values in php without repeatition [duplicate]

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();
}

Get any of the item from the Array with whereIn in Laravel 5.3 [duplicate]

This question already has answers here:
Split a comma-delimited string into an array?
(8 answers)
Closed 10 months ago.
I'm using laravel 5.3 and trying to build a query with multiple where and wherein function. Here is my code:
$posts_id = "1,3,4"; //from my query
$results = Post::select('*');
$results->whereIn('posts_id', [$posts_id]);
$resutls->get();
There is 1 post which have an id of 4 in my database, but my query doesn't returning anything. Though there is 4 in my post ids $posts_id = "1,3,4";.
Need help, to get posts from any of the id, which I've included in my $posts_id variable.
Thanks in Advance!
You need to pass an array to whereIn() method:
$results = Post::whereIn('posts_id', explode(',' $posts_id))->get();
Note that you don't need to call each method in a separate line. You can chain them. Also, the select('*') is not required.
You can create your array in any way you want, no need to use explode().
$ids = [1, 2, 3];
$results = Post::whereIn('posts_id', $ids)->get();
It may be good to check if the array isn't empty before making that query.

Using $_GET to get search term, turn array into requested column [duplicate]

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.

Categories