PHP sql query isn't returning anything - php

The following PHP code:
$dbc = mysql_connect ('localhost','root','abcde');
if (!$dbc) {
die('Not Connected:' . mysql_error ());
}
$db_selected = mysql_select_db ('db_test', $dbc);
if (!$db_selected) {
die ("Can't Connect :" .mysql_error());
}
$query="SELECT * FROM 140423 WHERE GAME='Clash of Clans'";
//add "result"
$result=mysql_query($query);
if (!$query) {
die ("Can't Connect :" .mysql_error());
}
echo $result;
Doesn't return anything.
Should I be using print instead of echo?
Also, if I change
echo $result;
To
echo 'whatever';
it returns "whatever" on my post.
Help?

From the manual:
Identifiers may begin with a digit but unless quoted may not consist solely of digits.
http://dev.mysql.com/doc/refman/5.1/en/identifiers.html
Which is exactly what you're doing, and should not be doing.
Solution:
Choose a different name for your table, one consisting of letters preferably.
Use backticks around the table name.
Plus, if you wish to view data, you need to use a loop.
I.e.:
$query="SELECT * FROM `140423` WHERE GAME='Clash of Clans'";
while ($row = mysql_fetch_assoc($query))
{
$var = $row["column"]; // the column of your choice
}
echo $var;
Rewrite:
$dbc = mysql_connect ('localhost','root','abcde');
if (!$dbc) {
die('Not Connected:' . mysql_error ());
}
$db_selected = mysql_select_db ('db_test', $dbc);
if (!$db_selected) {
die ("Can't Connect :" .mysql_error());
}
$query="SELECT * FROM `140423` WHERE GAME='Clash of Clans'";
//add "result"
$result=mysql_query($query);
// as pointed out already
if (!$result) {
die ("Can't Connect :" .mysql_error());
}
echo $result; // this is up to you
// if you want to see data from your table, loop through it.
while ($row = mysql_fetch_assoc($query))
{
$var = $row["column"]; // the column of your choice
}
echo $var;
Footnotes:
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.

mysql_query returns a resource or false. You need to manipulate the resource with one of the various fetch functions.
Instead of looking if $query is false, you should be looking if $result is false.
if (!$result) {
die ("Can't Connect :" .mysql_error());
}

After that
$result=mysql_query($query);
if (!$query) {
die ("Can't Connect :" .mysql_error());
}
Use
while($row = mysql_fetch_array($result)) {
echo $row['YourTableFieldName'];
}
OR use
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['YourTableFieldName1'];
echo $row['YourTableFieldName2'];
}

Related

Creating Dropdown list from sql database in PHP

*The condition for "die" had been left out of my code by mistake when I copied it to the question. I put it back in.
I know this question might seem repetitive, but I have not found an answer in any of the other questions. I am trying to create a drop-down list based off a column in a database. I have tried two different ways and neither gave me correct results. Does anyone know a correct way of doing this?
The first way I saw in other StackOverflow answers (Fetching data from MySQL database to html drop-down list, Fetching data from MySQL database to html dropdown list). My code is below:
<?php
$connect = mysql_connect('localhost', 'root');
if ($connect == false)
{
die ("Unable to connect to database<br>");
}
$select = mysql_select_db('ViviansVacations');
if ($select == false)
{
die ("Unable to select database<br>");
}
$query = "SELECT * FROM Destinations";
$result = mysql_query($query);
?>
<select name="select1">
<?php
while ($row = mysql_fetch_array($result))
{
echo "<option value='". $row['Europe'] ."'>" .$row['Europe'] ."</option>" ;
}
?>
</select>
NetBeans sends me an error saying that "Text not allowed in element 'select' in this context".
The second way I tried:
<?php
$connect = mysql_connect('localhost', 'root');
{
die ("Unable to connect to database<br>");
}
$select = mysql_select_db('ViviansVacations');
{
die ("Unable to select database<br>");
}
$query = "SELECT * FROM Destinations";
$result = mysql_query($query);
?>
<select name="select1">
<?php
while ($line = mysql_fetch_array($result))
{
?>
<option value="<?php echo $line['Europe'];?>"> <?php echo
$line['field'];?> </option>
<?php
}
?>
</select>
This code did not produce any errors. However, inside the form were the opening php lines followed by an empty drop down box:
"); } $select = mysql_select_db('ViviansVacations'); { die ("Unable to select database
"); } $query = "SELECT * FROM Destinations"; $result = mysql_query($query); ?>
So there are many problems with your approach. First of all you are using a deprecated mysql_* functions which is bad idea and second you are not debugging your database connection properly :
$connect = mysql_connect('localhost', 'root');
{
die ("Unable to connect to database<br>");
}
In above code the die statement will always execute stopping further execution.
Also make sure the database ViviansVacations and table Destinations and column Europe exists with correct names(Follow standards and try to use all small letters for database/table/column naming)
The correct mysqli_* approach is(tested locally and the select box forms correctly) :
<?php
$db = 'ViviansVacations';
$mysqli = new mysqli('localhost', 'root', '', $db);
if($mysqli->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
$query = "SELECT * FROM Destinations";
$result = mysqli_query($mysqli, $query);
?>
<select name="select1">
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['Europe'] . "'>" . $row['Europe'] . "</option>";
}
?>
</select>
There are couple of things, you to verify and correct.
First of all, your database connection code, that doesn't seems to be correct. I didn't see any condition on which you are suppose to invoke die.
$connect = mysql_connect('localhost', 'root');
{
die ("Unable to connect to database<br>");
}
From the above code, below line will execute all the time
die ("Unable to connect to database<br>");
You should correct your database connection code to below :
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
You can refer mysql_connect for the usage.
Also, verify your file extension is .php
Mainly your problem is database connection. Try this -
<?php
mysql_connect("localhost", "root", "") or
die("Could not connect: " . mysql_error());
mysql_select_db("your_db");
$result = mysql_query("SELECT * FROM your_table");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
print_r($row);
echo "<br>";
}
mysql_free_result($result);
?>
There could be few issues:
Use mysqli_connect instead of mysql_connect because mysql is depreciated
Make 3rd parameter as empty `mysqli_connect('localhost', 'root', '');//as per standards
Debug your code for example: (print_r($connect), execute your query in phpmyadmin, print_r($result) and then in loop print_r($row).
At end, I am sure you will get your desired result and also you will know in detail that what was happening.
You might want to try to use this ..The dept_id and the description u have to change according to your database .Hope this will help you
<?php
$sql = mysql_query("SELECT dept_id ,description FROM department
ORDER BY dept_id ASC");
db_select($sql,"dept_id",$dept_id,"","-select Department-","","");
?>

This mysql_connect Attribute seems to old how can I replace them?

I cannot connect to my Data Base using this way:
mysql_connect("localhost","root","") or die("1");
mysql_select_db("database") or die("2");
After the connection to the data base I would like to create a while loop with the elements of the data base, this is my code:
$carlistreq = mysql_query("SELECT * FROM cars WHERE brand="'.$_GET['marq'].'"") or die("3");
$count = mysql_num_rows($carlistreq);
if($count==0)
{
echo "No elements";
}
else
{
while($row= mysql_fetch_array($query))
{
//my code
}
}
The issue comes from my SQL attributes like:
mysql_connect
mysql_fetch_array
mysql_select_db
For example.
Here is the error:
Deprecated: mysql_connect(): The mysql extension is deprecated and
will be removed in the future: use mysqli or PDO instead in C:[....]
on line 2
use the mysqli-extension like this:
$mysqli = new mysqli("localhost","user","password","database") or die("1");
$sql = "SELECT * FROM cars WHERE brand='".$_GET['marq']."'";
$result = $mysqli->query($sql);
if($result){
while($row = $result->fetch_assoc()){
//do something with your $row here
}
}
http://php.net/manual/en/book.mysqli.php
Use PDO
$db = new PDO('mysql:host=localhost;dbname=databaseName', 'User' , 'password');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
Yes now servers are going to handel mysqli and PDO. Try implementing this code:
<?php
$con = mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
// Change database to "test"
mysqli_select_db($con,"test");
// ...some PHP code for database "test"...
mysqli_close($con);
?>
You can user http://php.net/manual/en/book.mysqli.php as reference to understand better how mysqli works.

how to Get the list of sites (domains) from MySQL database using PHP?

so I am new in StackOverflow :), I have a problem to answer a question in php5,
This is the question :
Create a PHP 5.4 script to check availability of many Sites (via Echo Protocol):
* Get the list of sites (domains) from MySQL database.
so I write this script and I want if it's the good answer :
<?php
$dbname = 'mysql_dbname';
if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}
mysql_free_result($result);
?>
try something like this
$con = mysqli_connect(‘hostname’, ‘username’, ‘password’, ‘database’);
$result = mysqli_query($con , "select column_name from table_name");
while($data = mysqli_fetch_array($result))
{
echo $data['column_name'];
}
this will tell you the databases that have rights to be connected to
mysql_connect('localhost') or die ("Connect error");
$res = mysql_query("SHOW DATABASES");
while ($row = mysql_fetch_row($res)) {
echo $row[0], '<br/>';
}
You need to select a database before you use mysql_query.
$connection = mysql_connect('mysql_host', 'mysql_user', 'mysql_password');
//Write code to Check the connection
mysql_select_db('database_name', $connection);
//Write code to query
But as Robin mentioned in the comment, mysql* apis are deprecated. Use Mysqli or Pdo_Mysql. details here: http://in3.php.net/mysql_select_db

Echoing MySQL query in PHP

I have been trying for the past while to echo out the result of a a MySQL query in PHP. I can't seem to get it to work so I am a bit lost. I know for a fact that the query works as I have done it in PHPMYADMIN and it is working fine, however whenever I load the webpage, nothing is outputted. For the purposes of this question I have generalized the things in the query as I obviously don't want anyone accessing my database. This is what I have tried:
<?php
$connect = mysql_connect('host', 'user', 'password', 'dbname');
if (!$connect) {
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('dbname')) {
die('Could not select database: ' . mysql_error());
}
$result = mysql_query('SELECT SUM(row name) FROM `table`');
if (!$result) {
die('Could not query:' . mysql_error());
}
echo mysql_result($result);
mysql_close($connect);
?>
I look forward to your replies.
mysql_result need the second parameter (The row number from the result that's being retrieved).
echo mysql_result($result, 0);
you have to change
echo mysql_result($result);
by
echo mysql_result($result,0);
or you can use
print_r(mysql_fetch_assoc($result));
Try this
echo mysql_result($result,0);
For more information, please give a look on http://www.php.net/mysql_result
or you can use mysql_fetch_row instead of mysql_result.
$row = mysql_fetch_row($result);
echo $row[0];
You may use this following format:
Give your Sql command like this:
$result = mysql_query('SELECT SUM(row name) as new_column_name FROM `table`');
then use this loop
while($fetched_values = mysql_fetch_array($result)){
echo $fetched_values['new_column'];
}
In your mysql_connect you have provided 4 parameters. it accepts 3 params
host, username and password. dbname is given inside mysql_select_db
as you can see from official docs. So remove the 4th param from mysql_connect function.
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
http://php.net/function.mysql-connect
$db_selected = mysql_select_db('foo', $link);
http://www.php.net/manual/en/function.mysql-select-db.php
but these mysql_* function will be deprecated use mysqli instead.
pass a row number as second parameter in mysql_result
echo mysql_result($result, 1);
or
use print_r(mysql_fetch_array($result));
where $result is your result resource
if you have any doubt you may refer my following example program.
<?php
$connect = mysql_connect('localhost', 'user_name', 'password', 'db_name');
if (!$connect)
{
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('db_name'))
{
die('Could not select database: ' . mysql_error());
}
$row = mysql_query('SELECT (Tamil+English+Maths) as total FROM table_name');
if (!$row)
{
die('Could not query:' . mysql_error());
}
while($fetched_row = mysql_fetch_array($row)){
echo $fetched_row['total'];
}
mysql_close($connect);
?>
here Tamil,English and Maths are the column values of my table

Basic mysql query giving no results

I got a simple query looking like this:
$con = mysqli_connect("host","username","password","default_database");
if(mysqli_connect_errno($con))
{
mysqli_connect_error();
}
else
{
$query = "SELECT * FROM `users_t`";
$result = mysqli_query($query) or die (mysql_error());
while($row = mysqli_fetch_assoc($result))
{
echo $row['email'];
}
}
Running this query gives me absolutely nothing. No errors but no result at the same time. I can't figure out whats wrong, help me please.
It looks like there may be a few things going on here:
According to the mysqli_connect_errno() Documentation, you should be checking for !$con rather than mysqli_connect_errno($con) in your if statement.
When a connection error is encountered, you're calling the error function but not printing it.
According to the mysqli_query() documentation, the first argument should be the database connection, the second being the query itself.
When a query errors out, you're calling mysql_error() when you should be calling mysqli_error(), passing it the connection. Again, according to documentation
Try this out and see if this resolves your problems:
<?php
$con = mysqli_connect("host","username","password","default_database");
if(!$con) {
print mysqli_connect_error();
} else {
$query = "SELECT * FROM `users_t`";
$result = mysqli_query($con, $query) or die (mysqli_error($con));
while($row = mysqli_fetch_assoc($result)) {
echo $row['email'];
}
}
$result = mysqli_query($query) or die (mysql_error());
Needs a mysqli resource link and also its not mysql_error()
if ($result = mysqli_query($con,$query))
{
while($row = mysqli_fetch_assoc($result))
{
echo $row['email'];
}
}
PHP is case-sensitive, so there is a very good change that your column in the database is actually named Email and then you have no result when you check $row['email'], because the E has to be upper case.
What you can do is make sure you use the right case in PHP, or select just the fields you want. MYSQL isn't case-senstive, so if you do the following it will work.
Also a good way to check if you have the right case: use var_dump($row) (I've added it to the code just to show you)
$con = mysqli_connect("host","username","password","default_database");
if(mysqli_connect_errno($con))
{
mysqli_connect_error();
}
else
{
$query = "SELECT email FROM `users_t`";
$result = mysqli_query($query) or die (mysql_error());
while($row = mysqli_fetch_assoc($result))
{
echo $row['email'];
var_dump($row);
}
}

Categories