I need to print one row from a table so a while loop isn't necessary, is there any other method?
You need not while.
Just do your while condition outside while 1 time.
i.e
$a=mysql_fetch_row($sql);
//use $a
instead of
while($a=mysql_fetch_row($sql)){
//use $a
}
if (($dbResult = mysql_query("SELECT ... FROM ... LIMIT 1")) !== false)
{
$row = mysql_fetch_array($dbResult);
echo $row['Column_Name'];
}
Just fetch one row, no need to always loop a retrieval.
$results = mysql_query("SELECT * FROM my_table WHERE user_id = 1234");
$row = mysql_fetch_assoc($results);
echo ($row['user_id']);
Do what you would have done inside the condition of your loop, and you'll be fine.
Related
So I have fetched data from a MySQL database and I want to assign it to a variable based on an nth row. Only the bottom three rows are filtered and I want to assign values from the firs and last row to two variables.
$sql3 = "SELECT * FROM login_attempts WHERE login_attempt_user_id=? AND login_attempt_result=? ORDER BY login_attempt_id DESC LIMIT 3;";
$stmt3 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt3, $sql3)) {
echo 6;
exit();
} else {
mysqli_stmt_bind_param($stmt3, "ss", $login_attempt_user_id, $login_attempt_success);
mysqli_stmt_execute($stmt3);
$result2 = mysqli_stmt_get_result($stmt3);
if (mysqli_num_rows($result2) > 0) {
while ($row2 = mysqli_fetch_assoc($result2)) {
$test1 = $row2['login_attempt_time'][0];
$test2 = $row2['login_attempt_time'][2];
echo $test1.$test2;
exit();
}
} else {
//echo 4;
exit();
}
}
The section of code is within the while loop and I realize that what I am attempting is for arrays. I want to do something similar to achieve my goal.
My code is not assigning the database entry to the variable: $test = $row2['login_attempt_time'] assigns the last value of the fetched row, however $test = $row2['login_attempt_time'][0] only returns the value 1.
Would anyone please be able to help with this?
Fetch all (three) rows into an array (2-dimensional) with mysqli::fetch_all(). Then get the first and the last elements (rows) with reset() and end().
Change
while ($row2 = mysqli_fetch_assoc($result2)) {
$test1 = $row2['login_attempt_time'][0];
$test2 = $row2['login_attempt_time'][2];
echo $test1.$test2;
exit();
}
to
$data = $result2->fetch_all(MYSQLI_ASSOC);
$variable1 = reset($data); // first row
$variable2 = end($data); // last row
Remember, this mysqli_fetch_assoc($result2)) will fetch one row from the database. So the first time, $row2 will be the contents of the first row, the second time $row2 is the second row, etc. Perhaps add a counter to the loop to know when to populate $test1 and $test2, as with an if condition.
I've seen the question about "doing mysql_fetch_array" multiple times solved by stocking the result in another variable, or by resetting the mysql_fetch_array loop index for example...
But that's not what I need. I need to use 2 mysql_fetch_ array, one in another, like this :
$sql = mysql_query("SELECT step FROM cyclone_cities ORDER BY uid");
$inc = 0;
while ($row = mysql_fetch_array($sql,MYSQL_NUM)){
$selected = $row[0];
while ($row2 = mysql_fetch_array(mysql_query("SELECT ".$selected." FROM cyclone_players ORDER BY uid"))){
print_r($row2);
}
}
How can I make it to use two differents mysql_fetch_array indexes ?
The $pKeyArray only prints first row from the database which meets the WHERE clause, why isn't showing all rows which meets the WHERE clause, I don't want to put it in any loop, i just need is an array of P_Key of all rows.
$getPKey = "SELECT P_Key FROM likersTable WHERE executed=0";
$PKeyDetails = mysqli_query($dbConnect,$getPKey)
or die('Some error in post id');
$pKeyArray = mysqli_fetch_array($PKeyDetails);
print_r($pKeyArray);
You need to call mysqli_fetch_array() for each row.
while ($pKeyArray = mysqli_fetch_array($PKeyDetails)) {
print_r($pKeyArray);
}
Use mysqli_fetch_all:
$array = mysqli_fetch_all( $PKeyDetails);
You have to use a loop because the mysqli_fetch_*() functions only returns one row per call.
Use this code:
$getPKey = "SELECT P_Key FROM likersTable WHERE executed=0";
$PKeyDetails = mysqli_query($dbConnect,$getPKey)
or die('Some error in post id');
while ($row=mysqli_fetch_array($PKeyDetails))
{
// Do something with $row
}
Or use mysqli_fetch_all():
$result = mysqli_fetch_all($PKeyDetails, MYSQLI_ASSOC); // or use MYSQLI_NUM
while($pKeyArray = mysqli_fetch_array($PKeyDetails)) {
print_r($pKeyArray);
}
I have a small problem and since I am very new to all this stuff, I was not successful on googling it, because I dont know the exact definitions for what I am looking for.
I have got a very simple database and I am getting all rows by this:
while($row = mysql_fetch_array($result)){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
Now, my question is: how do I filter the 2nd result? I thought something like this could work, but it doesnt:
$name2= $row['name'][2];
Is it even possible? Or do I have to write another mysql query (something like SELECT .. WHERE id = "2") to get the name value in the second row?
What I am trying to is following:
-get all data from the database (with the "while loop"), but than individually display certain results on my page. For instance echo("name in second row") and echo("id of first row") and so on.
If you would rather work with a full set of results instead of looping through them only once, you can put the whole result set to an array:
$row = array();
while( $row[] = mysql_fetch_array( $result ) );
Now you can access individual records using the first index, for example the name field of the second row is in $row[ 2 ][ 'name' ].
$result = mysql_query("SELECT * FROM ... WHERE 1=1");
while($row = mysql_fetch_array($result)){
/*This will loop arround all the Table*/
if($row['id'] == 2){
/*You can filtere here*/
}
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
if($counter == 2){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
}
This While loop will automatically fetch all the records from the database.If you want to get any other field then you will only need to use for this.
Depends on what you want to do. mysql_fetch_array() fetches the current row to which the resource pointer is pointing right now. This means that you don't have $row['name'][2]; at all. On each iteration of the while loop you have all the columns from your query in the $row array, you don't get all rows from the query in the array at once. If you need just this one row, then yes - add a WHERE clause to the query, don't retrieve the other rows if you don't need them. If you need all rows, but you wanna do something special when you get the second row, then you have to add a counter that checks which row you are currently working with. I.e.:
$count = 0;
while($row = mysql_fetch_array($result)){
if(++$count == 2)
{
//do stuff
}
}
Yes, ideally you have to write another sql query to filter your results. If you had :
SELECT * FROM Employes
then you can filter it with :
SELECT * FROM Employes WHERE Name="Paul";
if you want every names that start with a P, you can achieve this with :
SELECT * FROM Employes WHERE Name LIKE "P%";
The main reason to use a sql query to filter your data is that the database manager systems like MySQL/MSSQL/Oracle/etc are highly optimized and they're way faster than a server-side condition block in PHP.
If you want to be able to use 2 consecutive results in one loop, you can store the results of the first loop, and then loop through.
$initial = true;
$storedId = '';
while($row = mysql_fetch_array($result)) {
$storedId = $row['id'];
if($initial) {
$initial = false;
continue;
}
echo $storedId . $row['name'];
}
This only works for consecutive things though.Please excuse the syntax errors, i haven't programmed in PHP for a very long time...
If you always want the second row, no matter how many rows you have in the database you should modify your query thus:
SELECT * FROM theTable LIMIT 1, 1;
See: http://dev.mysql.com/doc/refman/5.5/en/select.html
I used the code from the answer and slightly modified it. Thought I would share.
$result = mysql_query( "SELECT name FROM category;", db_connect() );
$myrow = array();
while ($myrow[] = mysql_fetch_array( $result, MYSQLI_ASSOC )) {}
$num = mysql_num_rows($result);
Example usage
echo "You're viewing " . $myrow[$view_cat]['name'] . "from a total of " . $num;
$tmp = mysql_query("SELECT commercial FROM Channels WHERE name='".mysql_real_escape_string($_POST['name'])."'");
while( $row = mysql_fetch_assoc($tmp))
{
echo $row['commercial'];
}
I only want to access the first element.
not in a while loop
You can use mysql_fetch_row to retrieve the value like that ...
$row = mysql_fetch_row($tmp);
$commercial = $row['commercial'];
Well, just remove your while loop then. This will get the first (actually current) row:
$tmp = mysql_query("SELECT commercial FROM Channels WHERE name='".mysql_real_escape_string($_POST['name'])."'");
$row = mysql_fetch_assoc($tmp);
echo $row['commercial'];
Another option is to use mysql_result:
$tmp = mysql_query('..');
$row = mysql_result($tmp, 0);
echo $row['commercial'];
Side note: If you only need one row, add LIMIT 1 to your query.
If you need just the first element, why don't you append LIMIT 1 to your query ?