I am conducting a query whereby I am retrieving all rows from a db table where a certain column = 'xx'.
Then I need to store the array retrieved from the result.
Then I need to delete all those rows from the DB, but i still need to access the stored array AFTER carrying out the delete. It might sound a bit strange but this is what I need to do.
So far:
$Get_Appointments = "SELECT *
FROM TempSchedule2
WHERE CreatedBy = 'xx'";
$stmt = mysqli_stmt_init($con);
mysqli_stmt_prepare($stmt, $Get_Appointments);
mysqli_stmt_execute($stmt);
if ($Apts = mysqli_stmt_get_result($stmt)){
$numRows = mysqli_num_rows($Apts);
echo 'numrows is '.$numRows.'<br>';
global $arrayToSave;
$arrayToSave = mysqli_fetch_array($Apts);
while($row=mysqli_fetch_array($Apts)){
//echo 'in the while?';
$scheduleID = $row['scheduleID'];
$DeleteApt_Query = "DELETE FROM tempschedule2 WHERE scheduleID = ?";
$stmt = mysqli_stmt_init($con);
mysqli_stmt_prepare($stmt, $DeleteApt_Query);
mysqli_stmt_bind_param($stmt, "i", $scheduleID);
if (mysqli_stmt_execute($stmt)){
//executed
echo 'deleted';
}
else {
echo 'not deleted because '.mysqli_error($con);
$ErrorForLog = date("Y-m-d") . "\r\n" . mysqli_error($con). "\r\nInfo Attempted to delete apt id : " . $scheduleID. "\r\n\r\n";
error_log($ErrorForLog, 3, "Logs.txt");
}
}
echo 'savedArray here is ';
var_dump($arrayToSave);
What's happening is one row is not deleting for some reason. And then after the loop that executes the delete queries, I am var_dumping the global $arrayToSave (which i hoped was the entire array), and the result is that one element of the array which had not been deleted. So it seems as thought the global array is being modified within the loop? This is the first time I've had to use global in php so I'm probably not using it right.
Try this:
Change $arrayToSave = mysqli_fetch_array($Apts); to $arrayToSave = array();
Then add $arrayToSave[] = $row directly after the start of the while loop.
mysqli_fetch_array grabs the next row and turns it into an array. It doesn't take the whole result set and turn it into an array. That is why you put it in a while statement. That loops through ALL the rows. So loop through and save the results, then run your delete afterward.
$results = array();
while($row = mysqli_fetch_array($apts){
$results[] = $row;
}
//Now Delete
$DeleteApt_Query = "DELETE FROM tempschedule2 WHERE scheduleID = ?";
$stmt = mysqli_stmt_init($con);
mysqli_stmt_prepare($stmt, $DeleteApt_Query);
mysqli_stmt_bind_param($stmt, "i", $scheduleID);
if (mysqli_stmt_execute($stmt)){
//executed
echo 'deleted';
} else {
echo 'not deleted because '.mysqli_error($con);
$ErrorForLog = date("Y-m-d") . "\r\n" . mysqli_error($con). "\r\nInfo Attempted to delete apt id : " . $scheduleID. "\r\n\r\n";
error_log($ErrorForLog, 3, "Logs.txt");
}
Also, you need to be careful running another query while you are still iterating through the result of a previous query. The data from the first query gets wiped out when you run another query.
global is useless in this place, you can safely delete it.
What you do is put the first retrieved row into $arrayToSave and iterate the over the rest of rows. What you probably want to do, is put all $rows into a two-dimensional array with something like $arrayToSave[] = $row; after the beginning of the while loop.
You fetch one row before the loop thereby removing it from the results $Apts:
$arrayToSave = mysqli_fetch_array($Apts);
So $arrayToSave only contains one row and that row is not looped over. You want to remove that and probably do something like this:
while($row=mysqli_fetch_array($Apts)){
$arrayToSave[] = $row;
Alternately use mysqli_fetch_all():
$arrayToSave = mysqli_fetch_all(($Apts);
foreach($arrayToSave as $row) {
//do stuff
}
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 rather new at php and mysqli and I've had some success but am currently facing a wall. Mostly because I dont know the terms to express what i'm trying to do.
I can select a row all day long but I seem to be stuck on the same row. I need to be able to select data from further down the column. Here is the code i'm working with.
$qry = "select * from products";
$rs = mysqli_query($conn,$qry);
$getRow = mysqli_fetch_row($rs);
$getRowAssoc = mysqli_fetch_assoc($rs);
echo "<img src=\"".$getRow['1'] . "\">";
i have several links to images in the picture column on my database but can't seem to figure out a simple way to display the links from other rows in that column. I may be way off base here but I dont think I am.
this is a layout of the db db pic
any help would be much appreciated
For each mysqli_fetch_assoc you get the result of the next row. As the index starts in -1, the first time you call it, it goes to the first row. So whenever you call it again, it goes to the next row. Use it inside of a loop and you will be all set.
while($row = mysqli_fetch_assoc($result)){
// $row will have new content each iteration
}
mysqli_fetch_assoc Fetch a result row as an associative array, but just 1 row, if you want to get all the result, you have to go through a loop to get everything for the result, example :
<?php
$query = 'SELECT `products`.* FROM `products`';
$mysqli = new Mysqli('localhost','test','root','password');
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo '<img src="' . htmlentities($row['pic']) . '" /><hr />';
}
unset($row);
$result->free();
$mysqli->close();
if you want to get all the rows in 1 step for later usage, you would use mysqli::fetch_all(), example :
<?php
$query = 'SELECT `products`.* FROM `products`';
$mysqli = new Mysqli('localhost','test','root','password');
$result = $mysqli->query($query);
$products = $result->fetch_all();
$result->free();
$mysqli->close();
print_r($products);
i have a little problem, i have a database with 2 tables, users and comments and i need to print the result with pdo.
if i try this code, everything works great:
$stmt = $dbConnection->prepare("SELECT comment_text, username FROM users, comments WHERE users.user_id = comments.user_id");
$stmt->execute();
$stmt->fetch(PDO::FETCH_ASSOC);
foreach ($stmt as $row) {
echo $row['comment_text'] . "<br>By " . $row['username'] . "<br>";
}
But if i try to add a variable which get the result of fetch i get a totally different result with only 2 rows and only the first letter of the value...
$stmt = $dbConnection->prepare("SELECT comment_text, username FROM users, comments WHERE users.user_id = comments.user_id");
$stmt->execute();
$comment = $stmt->fetch(PDO::FETCH_ASSOC);
foreach ($comment as $row) {
echo $row['comment_text'] . "<br>By " . $row['username'] . "<br>";
}
if i try this code, everything works great:
it is not.
this way you are losing the very first comment. So it should be just
$stmt->execute();
foreach($stmt as $row )
{
echo $row['comment_text']."<br>By ".$row['username']."<br>" ;
}
in case you want to save the result in array, you have to use the appropriate function for that:
$stmt->execute();
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($comments as $row )
{
echo $row['comment_text']."<br>By ".$row['username']."<br>" ;
}
while fetch() is getting you only one record, fetchAll() is doing what the name suggests
Both your samples aren't functionning properly :
In the first one you loop over every row except the first row, for which you did a fetch, and then did nothing with this first row.
In the second one you loop over every field of the first row, which produce some unexepected output.
$search = htmlspecialchars($_GET["s"]);
if(isset($_GET['s'])) {
// id index exists
$wordarray = explode(" ",$search);
$stringsearch = implode('%',$wordarray);
echo $stringsearch;
echo ",";
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
if (!empty($result)) {
echo sizeof($result);
echo ",";
Database has 3 rows with titles test,pest,nest with corresponding id's 1,2,3. when i request domain.com/?s=est
it echos something like this
est,2,
Now when i checked $result[0] and $result[1], $result[0] echoed 1 and $result[1] didn't echo anything. When I use foreach function, it is taking only value of $result[0]
and $result should be array of all the three indexes.
I cannot find any mistake,
when i type the same command in sql console it works, somebody help me, thanks in advance.
The problem is, if you're expecting multiple rows, then don't do this:
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
This only fetches the first row, you need to loop it to advance the next pointer and get the next following row set:
$result = $conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%' ");
while($row = $result->fetch_array()) {
echo $row[0] . '<br/>';
// or $row['ID'];
}
Sidenote: Consider using prepared statements instead, since mysqli already supports this.
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;