I'm using sqlsrv driver, and I'm trying to make a query like this:
$query = "select * from products";
$result = sqlsrv_query($conn,$query);
echo $result;
This returns me nothing. What is wrong with the query or PHP code?
This is how it would be done with a mysql connection. I haven't used sqlsrv driver, so it may not work as is but you get an idea.
Bruno posted a link with sqlsrv driver detailed code.
The real issue is that you can't just echo $result. It's an array and you have to do it row by row or write a function that echoes the complete $result. That way you can also filter rows or columns and format every field as you like.
$query = "select id, title, price from products";
$result = mysql_query($conn,$query);
$num=mysql_numrows($result);
$i=0;
while ($i < $num)
{
$id=mysql_result($result,$i,"id");
$title=mysql_result($result,$i,"title");
$price=mysql_result($result,$i,"price");
echo "<b>id: $id</b> Product: $title , Price: $price<br>";
$i++;
}
I agree with that the real problem is that you can't echo a result - you have to iterate through the results. Just so you have an example with the sqlsrv extension, here's how I'd do it:
$query = "select id, title, price from products";
$result = sqlsrv_query($conn, $query);
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
echo "<b>id: $row['id']</b> Product: $row['product'], Price: $row['price'];
}
-Brian
Related
I am trying to get rows from a table when a condition is satisfied (status = 'no transit') but nothing shows up even when rows are supposed to show up (count is 1 and more).
if($query['num'] == 0){
echo "<p>No shopping orders on transit</p>";
}else{
$sql = "SELECT *, FORMAT(total, 0) AS total, FORMAT(grand_total, 0) AS grand_total FROM shipping_details WHERE status = 'no transit' ORDER BY order_id DESC";
foreach ($db->query($sql) AS $query){
echo" Show some results ";
$select = "SELECT * FROM shipping_order WHERE order_id = :order_id";
foreach ($db->query($select, array('order_id' => $query['order_id'])) AS $items){
echo"
Some results
";
//Foreach ends
}
}
}
You don't show enough that we can tell which codebase you use to connect to your DB (MySQLi, mysql_, or PDO), so the code below may need some tweaking.
The problem is basically that you never retrieve your database results. Instead you try to loop through the query execution itself.
Change
$sql = "SELECT *...";
foreach ($db->query($sql) AS $query)...
To
$sql = "SELECT *...";
$result = $db->query($sql); //execute the query
if(!$result) die($db->error); //exit and show error if query failed
//now we can fetch the results one at a time and loop through them
//this line may need to be adjusted if you're not using MySQLi
while($row = $result->fetch_assoc())...
Within the while loop, $row will contain the values from the DB record. Use print_r($row) to learn its shape.
It is not working, because you forgot to use prepare and execute methods from pdoStatemnt class.
See below:
$stmt = $db->prepare("SELECT * FROM shipping_order WHERE order_id = :order_id");
$stmt->execute(array('order_id' => $query['order_id']));
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)){
echo"
Some results
";
//Foreach ends
}
I have a database table that has 4 records with a column _id that auto increments. When I run a query to get all records, it works but it doesn't echo out all the ids, it only points to the first rows and echos it four times. I am using PHP and MySQLi. Here is my code
Code for querying
$sql = "SELECT * FROM att_table";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
Code for display
do{
echo result['_id'];
}while($query->fetch_assoc());
It outputs 1111 instead of 1234. Please what is wrong?
You're fetching each of the 4 results, so it loops the appropriate number of times; but you're only assigning the fetched result to $result once, so that's the only _id value that gets echoed
do{
echo $result['_id'];
}while($result = $query->fetch_assoc())
You also can use a foreach loop :
$sql = "SELECT * FROM att_table";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
foreach($result as $data){
echo $data['_id'];
}
$sql = "SELECT count(id),soft_name from table_name GROUP BY soft_name";
$d = mysqli_fetch_assoc(mysqli_query($db_name, $sql));
$c = array_shift($d);
The result is always 2, but the database contains more than 3000 items. What could be the problem?
Records are not pulled the way you are pulling for that you have to use similar to following code:
if($result = mysqli_query($db_name, $sql)){
while($d = mysqli_fetch_assoc($result){
echo $d['count'];
}
}
More reference here.
I'm tring to diplay results in php from sql database
MySQL statement is correct and does what i want in phpMyAdmin but for some reason my code breaks in the webpage
here is the code
require_once('db.php');
$sql="SELECT * FROM modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) ) FROM modul1open)
ORDER BY idM1O LIMIT 1"
$result = mysql_query($sql);
echo [$result];
and here is what i get
In general I need random number limited from min to max by the table id
You need to fetch the data from each row of the resultset obtained from the query. You can use mysql_fetch_array() for this.
// Process all rows
while($row = mysql_fetch_array($result)) {
echo $row['column_name']; // Print a single column data
echo print_r($row); // Print the entire row data
}
Change your code to this :
require_once('db.php');
$sql="SELECT * FROM modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) ) FROM modul1open)
ORDER BY idM1O LIMIT 1"
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo $row['fieldname'];
}
You need to do a while loop to get the result from the SQL query, like this:
require_once('db.php');
$sql="SELECT * FROM modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )
FROM modul1open) ORDER BY idM1O LIMIT 1";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
// If you want to display all results from the query at once:
print_r($row);
// If you want to display the results one by one
echo $row['column1'];
echo $row['column2']; // etc..
}
Also I would strongly recommend not using mysql_* since it's deprecated. Instead use the mysqli or PDO extension. You can read more about that here.
You cannot directly see the query result using mysql_query(). It just fires the query in mysql, nothing else.
For getting the result you have to add a lil things in your script like
require_once('db.php');
$sql="SELECT * FROM modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) ) FROM modul1open) ORDER BY idM1O LIMIT 1";
$result = mysql_query($sql);
//echo [$result];
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
print_r($row);
}
This will give you result.
Strangely, none of the while loops in the other answers worked for me, they did not throw an error, but their echo was empty. It worked when using foreach instead:
foreach($result as $row) {
//echo $row['column_name']; // Print a single column data
echo print_r($row); // Print the entire row data
}
Idea from: PDO looping through and printing fetchAll
I had to change
$result = mysql_query($sql);
to
$result = $conn->query($sql);
and then use the foreach (thanks to questionto42)
$result = $conn->query($sql);
foreach($result as $row) {
echo $row['column_name'];
}
Don't know if it matters but, I'm on a hosting company with:
Apache Version 2.4.51
PHP Version 7.3.33
MySQL Version 5.6.41-84.1
$query ="
SELECT
*
FROM
users
";
die($query);
In this case your query print on the browser copy this query and run on SQL Server.
I am trying to get pagination working on my website. Everything should be working but this only displays one product, however that should be 8 products. Anybody know what's wrong?
Thanks in advance.
else {
$query = "SELECT COUNT(*) FROM products";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_fetch_row($result);
$pages = new Paginator;
$pages->items_total = $num_rows[0];
$pages->mid_range = 9;
$pages->paginate();
$query = "SELECT serial, name, description, price, picture FROM products WHERE serial != '' ORDER BY serial ASC $pages->limit";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result);
{
echo '<div style="margin-bottom:10px;display:inline-block;background-color:#E3E3E3;width:190px;height:200px;"><img style="padding-top:10px;padding-left:25px;width:150px;height:150px;" src="'.htmlspecialchars($row[4]).'"><br><div align="center"><b>'.htmlspecialchars($row[1]).'</b><br><h6>€'.htmlspecialchars($row[3]).'</h6></div></div>';
};
echo ' ';
echo '<br><br><div style="margin-left:330px;">';
echo $pages->display_pages();
echo '</div>';
}
?>
mysql_fetch_row() only fetches one row at a time. You need to call it repeatedly to display all rows, like this:
while ($row = mysql_fetch_row($result)) {
// handle single row
}
I suggest you consider using mysql_fetch_array() instead. Then you will not have to rely on the order of the columns anymore and your code becomes more legible:
$row[0] becomes $row["serial"] etc.
Try reading the articles that #Kush linked. See here for a PHP-specific discussion.
You do not seem to be using mysql_fetch_row() properly
The following code is vulnerable to SQL injection because $page->limit does not appear to be sanitized
$query = "SELECT serial, name, description, price, picture FROM products WHERE serial != '' ORDER BY serial ASC $pages->limit";
Stop using mysql_* functions as they're deprecated. Use PHP database objects (PDO) instead because PDO allows parameter binding which protects you from sql injection.
You can read up on using PDO here
because of this line
$row = mysql_fetch_row($result);
should be
while($row = mysql_fetch_row($result)){...
Change the line
$row = mysql_fetch_row($result);
to
while ($row = mysql_fetch_row($result))