I am querying a database for the latest row entered and get the id column only, so I am sure I will get one value. However, I am unable to print the variable unless it is in a foreach loop, not even accessing the 0th element is giving me any output.
I use this line of code for querying the latest row's id added: $id = $db->query("SELECT MAX(id) FROM FM;");
When I use the foreach loop, I get the following output:
Loop:
foreach ($id as $i)
print_r($i);
Output:
Array ( [MAX(id)] => 20 [0] => 20 )
However, when I use print $id[0]; or print $id["MAX(id)"]; I get the HTTP Error 500.
How can I get the single value id and put it in a variable, the id itself that is?
Thanks
I looked up in the PDOStatement reference which is returned fromt the query function, and found the fetchAll() method which returns an array of rows, and got the latest id by the following line of code: $id->fetchAll()[0][0];
Instead of selecting max(id) you have to use lastInsertId() method
$id = $db->lastInsertId();
right after calling insert query
Related
I have an array with different IDs which I get from my database.
$fotos_temp_list=explode(",",$fotos_temp["fa_id"][0]);
Result: fa_id => 15,16,17,18
Now I want to update all rows inside another table with the IDs 15,16,17,18 and insert a specific '$id' into a column called 'fa_ev_id'.
In this example I set:
$id=1;
Now my foreach-loop looks like this:
foreach ($fotos_temp_list as $key) {
UPDATE images SET fa_ev_id = Concat(fa_ev_id , ',' ,'".$id."') where fa_id='".$key."' ";
}
This part is working too.
Every row with my IDs (in my example: 15,16,17,18) gets updated.
Problem:
When I run the foreach-loop again, the '$id' will be saved again inside the row. See here:
Question:
How is it possible, that I can check if '$id' is already inside the row and if so, it gets skipped? Here is what I tried to do:
foreach ($fotos_temp_list as $key) {
if (!in_array($id,$key)===true) {
UPDATE fotoalbum SET fa_ev_id = Concat(fa_ev_id , ',' ,'".$id."') where fa_id='".$key."'
}
}
I think the in_array function checks if '$id' id already inside '$key' and if it is true, the UPDATE statement is done. Therefore I added '!in_array' but it doesn´t seems to work. Does anyone has an idea what I am doing wrong? I just want to check if the '$id' is already inside my database row and if so, it should not insert the '$id' again.
I appreciate any advice.
The in_array() function in php accepts an array as its second parameter, in (!in_array($id,$key)===true), https://www.w3schools.com/php/func_array_in_array.asp. The second parameter $key, passed in here isn't an array.
You could save the datatype of fa_ev_id as json, and retrieve and json_decode the value when you are about performing an update the field to know if that $id already exists using in_array() or you could retrieve the values, expolode them to form an array and then check if it exists with in_array().
This is probably a silly beginner question and i don't think it's limited to mysqli_fetch_assoc() so it's probably a general programming question.
Anyways, i have this PHP code for getting data from a database using mysqli
$sql = "SELECT name FROM table1";
$result = mysqli_query($conn, $sql);
if($result){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
echo "Name: " . $row["name"]. "<br>";
}
}
}
What i don't understand is how the while loop there works. How does it iterates to the next element and know when to end? mysqli_fetch_assoc() returns a associative array which is stored in row variable which means it is not null therefore true and let's the while loop run. What i don't understand is how it iterates through the rows and ends when there are no more rows left. I'm not specifically doing anything to change the row to the next one so how does it do it on it's own?
Also mysqli_fetch_assoc() returns a associative array so shouldn't "name" key contain 1 element? Or is it a array of all the rows in that column?
(I hope you can understand what i'm trying to say, i'm not the best at explaining .-.)
Edit: What i don't understand is how this code iterates through all the rows. Is it part of the "inbuilt code" in this function? (I couldn't find it anywhere to confirm)
Each time when
mysqli_fetch_assoc($result) is accessed, the pointer moves to the next record. At last when no records are found, it returns null which breaks the while condition.
Eventually, when mysqli_fetch_assoc($result) runs out of rows it will return NULL, which evaluates to false, which breaks out of the loop.
$row results in a single row in the database, so $row['name'] would be the value of 'name' for a particular row.
Let's break it down, with perhaps a dumbed down example of how it works internally (Please note, this works a lot more efficiently, and wont actually run multiple queries):
$result = ['currentRow' => 0, 'query' => 'SELECT name FROM table1'];
while ($row = mysqli_fetch_result($result)) {
}
//First iteration
mysqli_fetch_result queries 'SELECT name FROM table1 LIMIT 0, 1'
it increments internally $result['currentRow'] to 1
it returns the row that was found
//Second iteration
mysqli_fetch_result queries 'SELECT name FROM table1 LIMIT 1, 1'
it increments internally $result['currentRow'] to 2
it returns the row that was found
//Third iteration
mysqli_fetch_result queries 'SELECT name FROM table1 LIMIT 2, 1'
no rows returned! Just simply return null (This will cause your while loop to break out)
You always pass $result as an argument to mysqli_fetch_assoc. This argument holds the iterator information, which will be used by mysqli_fetch_assoc to advance each time you call this function to the next row.
During each iteration, $row['name'] will be a single string.
i'm still new towards php but after searching through multiple topics i can't seem to figure this one out.
$query2 = "SELECT COUNT(MAP_CODE2) FROM TCODE_MAPPING WHERE MAP_CODE2 = 'ABC123'";
$result2 = odbc_exec($connect,$query2);
echo $result2;
i have a query above that i'd like to use to get the total number of rows within the query that i've set, however for some reason i keep getting hit by the error
Array to string conversion in /var/www/html/xxx.php on line 85
Would highly appreciate if anyone could help out on what i'm doing wrong. Thank you!
Problem is:-
You are trying to echo a result-set object of array type.
Solution (check the code comments):-
$query2 = "SELECT COUNT(MAP_CODE2) AS MYCOUNT FROM TCODE_MAPPING WHERE MAP_CODE2 = 'ABC123'"; // given a name to the count
$result2 = odbc_exec($connect,$query2); //prepare and execute query
while (odbc_fetch_row($result2)) { //iterate over result-set object
echo odbc_result($result, "MYCOUNT"), "\n"; // echo count
}
What is happening here is you are echoing an array object type that is also a resource type and php echo only string and other primitive type variables.
so you need to use a loop to access the row or to get row count and access row just use a foreach($results as $result)
to get row count visit this sqlsrv-num-rows . on this official php link you can get more example how to fetch data.
I'm using the following code to find the number of rows returned:
global $wpdb;
$results = $wpdb->get_results("SELECT * FROM list WHERE queue = 1 ORDER BY id ASC LIMIT 0,1");
$rowcount = $results->num_rows;
echo $rowcount;
As you can see, the results are limited to 1 row, and when I run this query in SQL it returns 1 row just fine. But in PHP the $rowcount doesn't return any value at all.
Any ideas what might be wrong? I get no error.
I think you need to use count($results) since the method $wpdb->get_results returns a array of objects/arrays.
Another way to get the number of rows is to use $wpdb->num_rows. Apparently this works for
$wpdb->get_results.
From the docs (http://codex.wordpress.org/Class_Reference/wpdb), it says the following about get_results:
Generic, multiple row results can be pulled from the database with
get_results. The function returns the entire query result as an array.
Each element of this array corresponds to one row of the query result
and, like get_row, can be an object, an associative array, or a
numbered array. If no matching rows are found, or if there is a
database error, the return value will be an empty array. If your
$query string is empty, or you pass an invalid $output_type, NULL will
be returned.
.i have the following code:
$task_id = mysql_query("SELECT MAX(task_id) from it_task");
echo $task_id;
.what I want to do is to get the highest value from a field named task_id on the table it_task. Instead of getting a result which is an integer I get "Resource id #5". how do i get around this?
mysql_query generates a resource which you then have to read using another mysql_ function. In this case you'll need a 2nd line to read from the query's result:
$result = mysql_query("SELECT MAX(task_id) from it_task");
$task_id = mysql_result($result, 0, 0); // get the first row, first column
echo $task_id;
Any problem here??? In my postgres sql, I can have:
select max(task_id)+1 as max from it_task;
Yes, mysql_query always returns a resource (unless it returns false), which you have to work on using one of the mysql_ functions like mysql_fetch_assoc.