I have an SQL query which I have recently turned into a prepared statement for security purposes. I have a query which returns many rows, each consisting of many columns. My question is how to echo the results using a while loop. My example I have so far:
$stmt = $conn->prepare("SELECT * FROM Customers
WHERE travel_Date >= ?
AND travel_Date <= ?
".$searchOption."
LIMIT ?
OFFSET ?");
$todayDateFrom = $todayDate." 00:00:00";
$todayDateTo = $todayDate." 23:59:59";
$stmt->bind_param("ssii", $todayDateFrom, $todayDateTo, $limit, $offset);
$stmt->execute();
while ($stmt->fetch()) {
//echo first name
//echo surname
//echo address
//echo number
//echo type
//15 other things i need to print off
}
I'm not sure what the best way to do this is. I have thought about:
$stmt->bind_result($firstName, $surname, $address, //etc);
But I'm wondering if there's another alternative similar to unprepared statements:
while($row = mysqli_fetch_array($query)){
echo $row['firstName'];
echo $row['surname'];
echo $row['address'];
//etc
}
try this:
$result = $stmt->get_result();
while ($row = $result->fetch_array())
{
echo $row['firstName'];
echo $row['surname'];
echo $row['address'];
}
try this -
$result_arr = array();
while($row = $stmt->fetch()){
$record = array();
$record['firstname'] = $row['firstname']; // if your db column contains firstname column other wise you can also use $row[0];
$record['name'] = $row[1]; // end so on .......
$result_arr[] = $record;
}
hope this will work for u...
Related
i want to Display the Result ('Positio: 2' or 'Position: 1') via a Echo
but $statement is a Object of class PDOStatement and not a String, how do i get it to see only the result of $statement? Thank you
<?php
$pdo = new PDO('mysql:host=localhost;dbname=testdb1', 'root', '');
$idV = $_GET['id'];
$statement = $pdo->prepare("SELECT position FROM idtabelle WHERE idnumber = ?");
$statement->execute(array($idV));
echo "Position: //$result_Of_Statement\\ ";
?>
Here's how I would do it:
$statement = $pdo->prepare("SELECT position FROM idtabelle WHERE idnumber = :idV");
$statement->bindParam(':idV', $idV);
$statement->execute();
while ($row = $statement->fetch(PDO::FETCH_ASSOC))
{
echo $row['position'];
}
You could also do away with the while loop if you wanted to.
I would fetch the result and use print_r or var_dump to see the result quickly.
$statement = $pdo->prepare("SELECT position FROM idtabelle WHERE idnumber = ?");
$statement->execute(array($idV));
$result = $statement->fetch(PDO::FETCH_ASSOC); //Or fetchAll()
echo "Position: ". print_r($result);
That's a quick and dirty way to inspect the result. If you want to add some formatting:
$result = $statement->fetch(PDO::FETCH_ASSOC);
for( $result as $key=>$value ){
echo ucfirst($key) .": $value \n";
}
If you want to get multiple rows wrap that in a loop where you fetch a new row each iteration
while( $result = $statement->fetch(PDO::FETCH_ASSOC) ){
echo "===New Row===";
for( $result as $key=>$value ){
echo ucfirst($key) .": $value \n";
}
}
i have a mysql table with 2 coloumns (firstname and lastname) and i want when i run the (select * from names) query all the values from firstname stored into an autoincrement variable like name1=john name2=george etc. and the same for lastname
surname1=williams surname2=james. i have written this but i cant get it to work
<?php
$name="";
$surname="";
$i =1;
$getinfo = "select * from names ";
$query = mysql_query($getinfo);
while ($row = mysql_fetch_array($query)) {
$name.$i. = $row['firstname'];
$surname.$i = $row['lastname'];
}
$i ++;
?>
To achieve what you want, you will need to use this syntax:
$i = 1;
while ($row = mysql_fetch_array($query)) {
${'name'.$i} = $row['firstname'];
${'surname'.$i} = $row['lastname'];
$i++;
}
But this is not a clean way to do so. I recommend you use arrays such as:
while ($row = mysql_fetch_array($query)) {
$names[] = $row['firstname'];
$surnames[] = $row['lastname'];
}
This is possible, but a pretty strange thing to do:
while ($row = mysql_fetch_array($query)) {
++$i;
$nameKey='name'.$i;
$surnameKey='name'.$i;
$$nameKey = $row['firstname'];
$$surnameKey = $row['lastname'];
}
Instead why don't you simply use numeric arrays?
while ($row = mysql_fetch_array($query)) {
$name[] = $row['firstname'];
$surname[] = $row['lastname'];
}
Or, even more elegant:
while ($row = mysql_fetch_array($query)) {
$persons[] = [
'name' => $row['firstname'],
'surname' => $row['lastname']
];
}
Here is the code that is giving me a problem:
$letter = $_POST['artistButton'];
$result = $mysqli->query("SELECT * FROM `Generic` WHERE `songName` LIKE '$letter%'");
$row = $result->fetch_array();
while ($row = $result->fetch_array()) {
$Artist = $row['Artist'];
$songName = $row['songName'];
$Duration = $row['Duration'];
$URL = $row['URL'];
$Genre = $row['Genre'];
echo "<input type='submit' value='$songName' name='artistButton'>";
echo "<br />";
}
The statement is correct I saved it to a variable and printed it to the screen, then ran it from the database and it printed the results I wanted so it definitively is not that. For some reason though it is not displaying. I am guessing it has something to do with something I messed up converting from mysql to mysqli. Thanks -Sam
Clearly some codes are cut, but try to remove that extra:
$row = $result->fetch_array();
And use:
while($row = $result->fetch_assoc()) {
Since you're interested on associative indices anyway.
Important note: Since you're using mysqli_*, use its parameterized queries instead. Don't directly use $_POST values on the query.
$letter = "{$_POST[artistButton]}%";
$stmt = $mysqli->prepare('SELECT * FROM `Generic` WHERE `songName` LIKE ?');
$stmt->bind_param('s', $letter);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$Artist = $row['Artist'];
$songName = $row['songName'];
$Duration = $row['Duration'];
$URL = $row['URL'];
$Genre = $row['Genre'];
echo "<input type='submit' value='$songName' name='artistButton'>";
echo "<br />";
}
$sql = "SELECT `description`,`auction_id` FROM `auctions` WHERE `description` REGEXP '(97(8|9))?[[:digit:]]{9}([[:digit:]]|X)'";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
$row = mysql_fetch_row($result);
echo "$row[1]";
is there any reason why echo "$row[1]"; returns every other row? the results i am getting is suggesting as such, I am trying to get every row
To actually answer your question, why it is occurring
$row = mysql_fetch_assoc($result); //this advances the internal data pointer by 1
$row = mysql_fetch_row($result); //this advances it by 1 more
Both are being executed in every iteration of your loop.
You should use one, not both.
Additionally, you shouldn't be using mysql_* functions in new code, as it is deprecated. Use PDO or MySQLi as stated in the comments.
You are calling the fetch function two times and hence it appears to skip one row each time.
while ($row = mysql_fetch_assoc($result)) {
$row = mysql_fetch_row($result); //This is not needed
echo "$row[1]";
}
Should be
while ($row = mysql_fetch_assoc($result)) {
echo $row[1];
}
Instead of having the loop as:
while ($row = mysql_fetch_assoc($result)) {
$row = mysql_fetch_row($result);
use:
while ($row = mysql_fetch_assoc($result)) {
You should use like this.
while ($row = mysql_fetch_assoc($result)) {
$desc[] = $row['description'];
}
If the query work properly in phpmyadmin then either you can use
while ($row = mysql_fetch_assoc($result)) {
echo $row['description'];
}
Or
$row = mysql_fetch_row($result);
echo $row[1];
or
while ($row = mysql_fetch_array($result)) {
echo $row['description']; //or
echo $row[1];
}
So I have some numbers that take the name "id" in my MySQL database. I tried this code:
while($row = mysql_fetch_array($result))
{
$id=$row['id'];
$user = $row['usrname'];
$fname = $row['fname'];
$lname = $row['lname'];
echo "<strong>User:</strong> ".$user." ".$fname." ".$lname."<br/>";
echo min($id);
}
On the last line I tried to echo the min value for id, but it didn't work. Any suggestions?
ANSWER: Use "ASC LIMIT 1"
while($row = mysql_fetch_assoc($sql)){
$id=$row['id'];
$user = $row['usrname'];
$fname = $row['fname'];
$lname = $row['lname'];
echo "<strong>User:</strong> ".$user." ".$fname." ".$lname."<br/>";
echo $id;
}
$sql = mysql_query("SELECT * FROM users ORDER BY id ASC LIMIT 1");
while($row = mysql_fetch_assoc($sql))
{
$id=$row['id'];
$user = $row['usrname'];
$fname = $row['fname'];
$lname = $row['lname'];
echo "<strong>User:</strong> ".$user." ".$fname." ".$lname."<br/>";
echo $id;
}
Try this:
$sql = 'SELECT min(id) as min FROM users';
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
$min_id = $row['min'];
In case you cannot change the query order (sort by names?), you can determine the lowest $id by using a helper variable:
$min = isset($min) ? min($min, $id) : $id;
And then print $min; after your loop.
If not able to use MIN() in MySQL, try this...
$smallestId = -PHP_INT_MAX;
while($row = mysql_fetch_assoc($sql)) {
...
$smallestId = min($smallestId, $id);
}
If you never have any negative ids (you shouldn't), you could just change -PHP_INT_MAX to 0.