Can anyone tell me why I am not getting the result of displaying the title on the browser when using the following script:
$sql =mysql_query( "SELECT * FROM 'Tour' WHERE 'Tour_No.'=1 LIMIT 0, 30 ");
echo $sql Title;
my connection is successful, but my desired result is not happening.
$sql = mysql_query( "SELECT * FROM `Tour` WHERE `Tour_No.`=1 LIMIT 0, 30 ");
while($row = mysql_fetch_object($sql))
{
echo $row->Title;
echo '<br />';
}
Maybe you can check this link for more example using mysql_query and mysql_fetch_object :
mysql_query: http://php.net/manual/en/function.mysql-query.php
mysql_fetch_object: http://www.php.net/manual/en/function.mysql-fetch-object.php
Your Query is invalid (single quotes are not used for tables / columns):
$result = mysql_query("SELECT Title FROM Tour WHERE Tour_No = 1 LIMIT 1");
You have to fetch the results:
$row = mysql_fetch_assoc($result);
Output the title:
echo $row['Title'];
Table and field names can be put in backtics, not in single quotes.
SELECT * FROM `Tour` WHERE `Tour_No.`=1 LIMIT 0, 30 // correct
SELECT * FROM 'Tour' WHERE 'Tour_No.'=1 LIMIT 0, 30 // wrong
if your getting 30 results you will need to loop through $sql, try the following.
$sql = mysql_query("SELECT * FROM `Tour` WHERE `Tour_No.` = 1 LIMIT 0, 30 ");
while($row = mysql_fetch_array($sql))
{
echo $row['Title'];
}
From http://php.net/mysql_query:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error....
The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data."
Try this:
$sql =mysql_query( "SELECT * FROM 'Tour' WHERE 'Tour_No.'=1 LIMIT 0, 30 ");
$row = mysql_fetch_assoc($sql);
echo $row['Title'];
I'm not sure exactly what your columns are named, but that should get you on the right track.
Related
I am trying to count all rows within the column field_161. However, it just returns the value of 0. The connection to the database is successful and the table and row are spelled correctly.
Here's my code:
$conn->query("SELECT COUNT(*) FROM app_entity_21 WHERE field_161 = 30 as $mytotaltasks");
echo "test" . $mytotaltasks;
You can't just do AS $mytotaltasks in mysql, and turn it into a PHP variable. You'll need to get the result from the query. The simplest way is to use fetchColumn():
$query = $conn->query("SELECT COUNT(*) FROM app_entity_21 WHERE field_161 = 30");
$mytotaltasks = $query->fetchColumn();
I think you should add the Group By at then end of query string
$conn->query("SELECT COUNT(*) FROM app_entity_21 WHERE field_161 = 30 group by field_161");
echo "test" . $mytotaltasks;
Try this!
$result=$conn->query("SELECT COUNT(field_161)AS field_cont FROM app_entity_21 WHERE field_161 = 30 as $mytotaltasks");
$data_cont=mysqli_fetch_assoc($result);
echo "This is the number of rows". $data_cont['field_cont'];
or a little bit different:
$result=$conn->query("SELECT COUNT(field_161)AS field_cont FROM app_entity_21 WHERE field_161 = 30 as $mytotaltasks");
$data_cont=mysqli_fetch_object($result);
echo "This is the number of rows". $data_cont->field_cont;
I know how to encode all the data from an SQL query into JSON using PHP, but don't know How to encode a partial set.
In Android (the client), I send an HTTP request which goes something like this:
public interface DataAPI {
#GET("/top500")
public void getResult(#Query("start") int start, #Query("count") int count,
Callback<Top500> response);
}
As you can see, I am using start and count in Android code.
I have around 500 records in my table and I have successfully encoded all the data into JSON, using below PHP Script:
<?php
$con = mysqli_connect(HOST,USER,PASS,DB);
$sql = "select * from Persons";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array(
'id'=>$row[0],
'name'=>$row[1]
));
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
JSON Result:
{"result": [{ ... }]}
But I need to encode mysql data 20 by 20 like this:
{"count": 20, "start": 0, "total": 500, "result": [{ ...}]}
What's missing is how to use the start and count parameters to get a partial set in order to get slices of the data.
You need to use LIMIT and OFFSET in your query. Applying some nasty logic in PHP is a bad solution. This is an operation that MySQL should do instead because you don't want to fetch all the rows if you don't need all of them.
If you run a query like this:
SELECT *
FROM Persons
ORDER BY Id
LIMIT 10 OFFSET 20
you will get a subset of the matching rows starting from the 20th and long 10 rows. You can then loop over the full results set.
Better to explicitly order by a field to ensure consistency across different pages.
You're final code (using PDO rather than mysqli):
$pdo = new PDO('mysql:dbname=db;host=127.0.0.1', $user, $password);
$count = $_GET['count'];
$start = $_GET['start'];
$stmt = $pdo->prepare('SELECT * FROM Persons ORDER BY Id LIMIT ? OFFSET ?');
$stmt->execute(array($count, $start));
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
// your logic that was inside the while
}
Use below code.
$con = mysqli_connect(HOST,USER,PASS,DB);
$count = "select count(*) as total from Person"; //query to get row count of your table
$count_res = mysqli_query($con,$count);
$count_row = mysqli_fetch_array($count_res);
$total = $count_row['total']; // get total no of records
$start = YOUR_START_VALUE; // from which offset you want to get record
$end = YOUR_VALUE // how many record want to fetch
$sql = "select * from Persons limit $start, $end";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array(
'id'=>$row[0],
'name'=>$row[1]
));
}
echo json_encode(array("count"=> $end, "start"=> $start, "total"=> $total,"result"=>$result));
mysqli_close($con);
?>
How about something like:
$start = 7;
$size = 3;
$count = 0;
while($row = mysqli_fetch_array($res)){
if($count>=$start && $count <$start+$size) {
array_push($result,array('id'=>$row[0],'name'=>$row[1]));
}
$count++;
}
The code should be self explanatory, but if you have any questions, feel free to comment.
Note: This is more of a PHP pseudo code, as I don't have an environment and haven't coded in PHP in a while.
I can think of 2 ways to solve this problem.
The first is using just MySQL:
SELECT SQL_CALC_FOUND_ROWS * FROM Persons LIMIT 0,20;
SELECT FOUND_ROWS();
With the first query you retrieve the batch of rows you want. With the second you get the total row count in the result set.
The second option is to use array_slice:
$total = count($result);
$batch = array_slice($result, 0, 20);
echo json_encode(array("total" => $total, "start" => 0, "count" => count($batch), "result"=>$batch));
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 tryng to select 5 mysql rows from the database and display them like $row[1] ect.... in php i am not sure how to do it an someone lead me down the right way please
Ok i hav looked a bit more
i wanted it to come out 1 - 5 and i wanted it to display the names
$result = mysql_query("SELECT * FROM table ORDER BY id DESC") or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
$name = $row['name'];
$arr = array("somearray" => array(1 => 5, 2 => 9, 3 => 42, 4 => 42, 5 => 42));
echo $arr["somearray"][1];
echo $arr["somearray"][2];
echo $arr["somearray"][3];
echo $arr["somearray"][4];
echo $arr["somearray"][5];
}
I think the OP wants five ROWS, not COLUMNS. Here is the correct code, assuming you already have a mysql connection open:
$sql = 'SELECT *
FROM table_name
ORDER BY col_name
LIMIT 5';
$result = mysql_query($sql);
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row[] = $line;
}
// print (access individual rows: $row[0] ... $row[4])
var_dump($row);
From php.net :
http://us3.php.net/manual/en/function.mysql-fetch-row.php
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
Try using MySQL's LIMIT clause to limit your results to 5 rows. And use PHP's mysql_fetch_assoc() (returns an associative array) instead of mysql_fetch_row() (returns a numerically indexed array). Also, it's good practice to free the memory associated with the result using mysql_free_result().
$result = mysql_query("SELECT * FROM mytable ORDER BY id DESC LIMIT 5") or die (mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$name = $row['name'];
echo $name;
}
mysql_free_result($result);
If you only need to select 5 rows from MySQL you can do this:
SELECT *
FROM Table
ORDER BY column
LIMIT 5
I want to get the number of rows in my MySQL table and store that number in a php variable. This is the code I'm using:
$size = #mysql_query("SELECT COUNT(*) FROM News");
$size ends up being "Resource ID #7." How do I put the number of rows directly into $size?
mysql_query returns a query resource id. In order to get values from it you need to use mysql_fetch_assoc on the resource id to fetch a row into an array.
$result = mysql_query("SELECT COUNT(*) FROM News");
$row = mysql_fetch_assoc($result);
$size = $row['COUNT(*)'];
You need to call mysql_fetch_row or one of its sister functions.
<?php
// untested
$result = #mysql_query("SELECT COUNT(*) FROM News");
// error handling
$row = mysql_fetch_row($result);
$count = $row[0];
?>
try the following:
$size = #mysql_query("SELECT COUNT(*) AS `total` FROM News");
$query = mysql_fetch_array($size);
echo $query['total'];
On a related note you can use the mysql_num_rows() function to obtain the number of rows from a given query. This is handy if you need to grab the data but also know the number of rows.
<?php
$result = #mysql_query("SELECT * FROM news");
$count = #mysql_num_rows($result);
?>