Help displaying data from a MySQL database - php

I want to display some basic data from a MySQL database. Here's the current code I have, but it doesn't seem to work. Could someone please explain why this doesn't work and offer a solution? Thanks!
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("cede") or die("Couldn't find database");
$result = 'SELECT * FROM 'users' ORDER BY 'DATE' DESC LIMIT 8';
echo = "'$result'"
?>

Providing your connection and structure information is correct, the following should work for you:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("cede") or die("Couldn't find database");
$result = 'SELECT * FROM `users` ORDER BY `DATE` DESC LIMIT 8';
$query = mysql_query($result) or die("Query Error");
while($row = mysql_fetch_assoc($query))
{
echo = "'" . $row['user'] . "'";
}
?>

You forgot to query the database!
You need to use mysql_query() to retrieve data from your DB server, then loop through it with a while() loop.
Also, you can't use quotes inside quoted strings - it breaks the string, meaning you'll get a syntax error with the SELECT ... line. You don't actually need to quote database fields in queries, so the following should work fine:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("cede") or die("Couldn't find database");
$query = 'SELECT * FROM users ORDER BY DATE DESC LIMIT 8';
$result = mysql_query($query); // Query the database.
// Loop through each returned row
while($row = mysql_fetch_assoc($result))
{
print_r($row); // Prints the current row
}
?>
To show any errors that PHP reports, put these two lines at the top of your script.
error_reporting(E_ALL);
ini_set('display_errors', '1');
They will output any errors you get, making problems much easier to solve.

After the selecting the database need
$stmt = mysql_query("SELECT * FROM users ORDER BY DATE DESC LIMIT 8");
while ($result = mysql_fetch_array($stmt, MYSQL_NUM))
{
var_dump($result);
}
mysql_free_result($stmt);

You should query your string and then echo the result, like this for example:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("cede") or die("Couldn't find database");
$query = 'SELECT * FROM `users` ORDER BY `DATE` DESC LIMIT 8';
$result = mysql_query($query);
echo = "'$result'"; // This may need a foreach loop
?>

You should escape the ' in your string, because you use them to open and close your string too. The syntax highlighter actually tells you that you are wrong ('users' and 'DATE' are black instead of maroon). :)
Please see the PHP.net documentation about strings:
After that, you'll need to further process $result. It is just a resource pointer and cannot be echoed that way. But that's a second step. :)

Related

i want to execute a saved query in the database

I want to execute a query that i saved in my database like this:
ID | NAME | QUERY
1 | show_names | "SELECT names.first, names.last FROM names;"
2 | show_5_cities | "SELECT cities.city FROM city WHERE id = 4;"
Is this possible ?
I am kinda noob in php so plz explain if it is possible.
If I understand you correctly, you have your queries saved in the database in a table and you want to execute those.
Break the problem down: you have two tasks to do:
Query the database for the query you want to run.
Execute that query.
It's a bit meta, but meh :)
WARNING: the mysql_ functions in PHP are deprecated and can be dangerous in the wrong hands.
<?php
if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
die('Could not connect to mysql');
}
if (!mysql_select_db('mysql_dbname', $link)) {
die('Could not select database');
}
$name = "show_5_cities"; // or get the name from somewhere, e.g. $_GET.
$name = mysql_real_escape_string($name); // sanitize, this is important!
$sql = "SELECT `query` FROM `queries` WHERE `name` = '$name'"; // I should be using parameters here...
$result = mysql_query($sql, $link);
if (!$result) {
die("DB Error, could not query the database\n" . mysql_error(););
}
$query2 = mysql_fetch_array($result);
// Improving the code here is an exercise for the reader.
$result = mysql_query($query2[0]);
?>
if you did create a stored procedure/function you can simply use:
mysql_query("Call procedure_name(#params)")
Thats will work. reference here: http://php.net/manual/en/mysqli.quickstart.stored-procedures.php
Querying the table to get the query, then executing that query and looping through the results and outputting the fields
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$RequiredQuery = intval($_REQUEST['RequiredQuery']);
$sql = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $sql);
if ($row = mysqli_fetch_assoc($result))
{
$sql = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $row['QUERY']);
while ($row2 = mysqli_fetch_assoc($result))
{
foreach($row2 AS $aField=>$aValue)
{
echo "$aField \t $aValue \r\n";
}
}
}
?>
just open the Table and get the individual query in a variable like
$data = mysql_query('SELECT * FROM <the Table that contains your Queries>');
while(($row = mysql_fetch_row($data)) != NULL)
{
$query = $row['Query'];
mysql_query($query); // The Query from the Table will be Executed Individually in a loop
}
if you want to execute a single query from the table, you have to select the query using WHERE Clause.

How to display table data in reverse? (php)

I have simple code for displaying images. I created table with 4 columns (ID, location, capture, equence) and inserted there 18 records. My question is: how to display all records from table in reverse mode? I need to make that the last entry will be displayed first, and the first entry displayed last.
What I need: 18-1
What I have now: 1-18
I was searching for simple codes to do that, but notwing worked at all. So i'd be very grateful if someone will help me to solve that problem.
Heres the basic code of my display script:
<?php
mysql_connect("localhost", "***", "***") or die(mysql_error());
mysql_select_db("martinidb1337") or die(mysql_error());
$result = mysql_query("SELECT * FROM klpgalerija") or die(mysql_error()); while($row = mysql_fetch_array( $result )) {
echo '<p><img src="'.$row['location'].'"></p>';
}
You have to use MySQL ORDER BY clause for that,
SELECT * FROM klpgalerija ORDER BY id DESC
Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated.
So use either PDO or MySQLi (IMO PDO is way to go)
Changed query from "SELECT * FROM klpgalerija" to "SELECT * FROM klpgalerija ORDER BY ID DESC"
<?php
mysql_connect("localhost", "***", "***") or die(mysql_error());
mysql_select_db("martinidb1337") or die(mysql_error());
$result = mysql_query("SELECT * FROM klpgalerija ORDER BY ID DESC") or die(mysql_error()); while($row = mysql_fetch_array( $result )) {
echo '<p><img src="'.$row['location'].'"></p>';
}
add an order by desc clause in your sql query
$result = mysql_query("SELECT klpgalerija.* FROM klpgalerija order by klpgalerija.ID desc") or die(mysql_error());

Adding either DISTINCT or GROUP BY to my mysql_query is causing no values to be returned

I am using php to get records from a mysql database using the following code:
<?php
$username="";
$password="";
$database="";
$hostname="";
$con = mysql_connect($hostname, $username, $password);
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con);
if(isset($_POST['emp'])){
$emp = $_POST['emp'];
$result = mysql_query("SELECT * FROM contact_log", $con);
echo mysql_num_rows($result);
die();
while($row = mysql_fetch_array($result)){
$emp = $row['emp'];
echo $emp.'<br>';
}
die();
}
mysql_close($con);
?>
This works fine and returns the correct fields. The problem is that if I change the query to
$result = mysql_query("SELECT DISTINCT * FROM contact_log", $con);
or
$result = mysql_query("SELECT * FROM contact_log GROUP BY emp", $con);
no results are returned.
mysql_num_rows does not even return a value which indicates to me that those lines are breaking my code but I am unable to figure out how.
I doubt you want to do a distinct * on your first query. Looking at your code, you probably want:
"SELECT DISTINCT emp FROM contact_log"
And you can get more information about what is going wrong with mysql_error:
mysql_query("select * from table") or die(mysql_error())
Finally, are you sure that $_POST['emp'] is being sent? Put an echo right after that if to make sure. And just so you know, you aren't using the emp POST variable for anything other than a flag to enter that block of code. $emp = $_POST['emp']; is doing absolutely nothing.

show the maximum value of a column of mysql table in php?

I want to show the maximum value of a particular column of mysql table in php. Here is my code:
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$var = $_POST['value'];
$sql = mysql_query(" SELECT MAX(column) FROM tableName WHERE variable='$var' ") or die(mysql_error());
$row = mysql_fetch_array($sql) or die(mysql_error());
echo "Maximum value is :: ".$row['column'];
?>
output:::
Maximum value is ::
Or you could be a bit creative:
$sql = mysql_query("SELECT `column` FROM tableName WHERE variable='$var' ORDER BY `column` DESC LIMIT 1") or die(mysql_error());
This is the same problem that I was searching for a solution. The approach below worked. The solution was using "MYSQLI_NUM". While the code below gives the intended result it still seems way too complex. Is there a way to "short-cut" using the "while" statement to search an array since there is only one returned value?
Selecting a max value only returns one number, yet PHP still seems to require a loop to evaluate an entire array. I was expecting something easy, like: max_value=result(0).
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error.' Sorry, could not connect to the database server');
$query = "SELECT MAX(IssueIDNUM) FROM tblIssueList";
$result =$conn->query($query);
if (!$result) die($conn->error);
while($row=mysqli_fetch_array($result, MYSQLI_NUM))
{
$maxresult=$row[0];
echo $maxresult;
}
$result->close();
$conn->close();
?>
With further experimentation, I was also able to adapt the code by Jim H. to develop the following solution. Though it works the code still seems too complex.
// Solution #2
$result =$conn->query("SELECT MAX(IssueIDNUM) `max` FROM tblIssueList");
if (!$result) die($conn->error);
while($row=mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo $row['max'];
}
The real name of column is MAX(column), try:
print_r($row);
You may either do:
$sql = mysql_query(" SELECT MAX(column) AS `column` FROM tableName WHERE variable='$var' ") or die(mysql_error());
Or:
$row = mysql_fetch_row($sql) or die(mysql_error());
echo "Maximum value is :: ".$row[0];
You have two choices. By Index or by Column Name. If you really want to use a column name, alias the column in your query.
$sql = mysql_query(" SELECT MAX(column) `max` FROM tableName WHERE variable='$var' ") or die(mysql_error());
Then you can use
$row['max'];
or
$row[0];
You are probably not returning any rows. You should try WHERE variable LIKE '%$var%';
$sql = mysql_query(" SELECT MAX(column) AS GIVE_A_NAME FROM tableName WHERE variable='$var' ") or die(mysql_error());
and
echo "Maximum value is :: ".$row['GIVE_A_NAME'];

Select latest entry from MySQL database error

<?php
mysql_connect("localhost", "user", "password") or die(mysql_error());
mysql_select_db("jmvarela_jacket") or die(mysql_error());
$query = 'SELECT * FROM `quote` ORDER BY `id` DESC LIMIT 1';
$row = mysql_fetch_array( $query );
echo $row['frase'];
?>
I cant get this to work.
I get this error:
Warning: mysql_fetch_array(): supplied
argument is not a valid MySQL result
resource in
/home/jmvarela/public_html/ihateyourjacket.com/latest/index.php
on line 7
I am trying to select the latest entry to the mysql database.
The table is called "quote"
There are three fields: id, frase and name.
Just to clarify (because this could be VERY bad coding) I am trying to get the "biggest" id and to display it's correspondant "frase".
you have not perform your query
$result = mysql_query($query);
$row = mysql_fetch_array( $result );
try this
Looks like you are not running the query.
// construct the query.
$query = 'SELECT * FROM `quote` ORDER BY `id` DESC LIMIT 1';
// run the query..THIS IS MISSING.
$result = mysql_query($query);
Also it's better to change SELECT * to SELECT frase, since you're interested only in the frase column. This will not bring all the unwanted columns from MySql to PHP, making your program perform better.
I´m not sure if this should be done but ill leave the complete running code for future refence.
<?php
mysql_connect("localhost", "user", "password") or die(mysql_error());
mysql_select_db("jmvarela_jacket") or die(mysql_error());
// construct the query.
$query = 'SELECT * FROM `quote` ORDER BY `id` DESC LIMIT 1';
$result = mysql_query($query);
$row = mysql_fetch_array( $result );
echo $row['frase'];
?>
Thanks to everyone!

Categories