No idea why this code will not work [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
for some reason I get this:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/walterg/public_html/phptest.php on line 50
Warning: mysql_close(): 5 is not a valid MySQL-Link resource in /home/walterg/public_html/phptest.php on line 60
I'm just trying to do a simple sql query but i get errors
my code is :
$con = mysql_connect("localhost","walterg_kaden","nope");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("walterg_learning", $con);
$result = mysql_query("SELECT * FROM ralf");
while($row = mysql_fetch_array($result))
{
echo $row['name'];
}
mysql_close($con);

2 simple rules for you to get it right
First. Always run your queries this way, at least until you adopt some more intelligent way to deal with queries:
$sql = "SELECT * FROM ralf";
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
Second. Trust your eyes!
If database told you "there is no database selected" - so, it is. Means you are selecting wrong database in the earlier statement. Check spelling, database existence and such.
That's easy. You don't need no special knowledge for this - just a common sense.

larry, your sql is failing. it's always essential for debugging reasons - like the one you're experiencing today - to have a way of printing out any errors along the way through each sql execution a a fail safe so that if anything should go wrong you can make sure to print the error there and then as the error occurs so that you can locate and fix the problem right away
Your SQL query is failing. Use the mysql_error();. This will display the problem.
$result = mysql_query("SELECT * FROM ralf") or trigger_error(mysql_error());
There are Five steps to PHP database connections to follow:
// 1. Create a database connection
// (Use your own servername, username and password if they are different.)
// $connection allows us to keep refering to this connection after it is established
$connection = mysql_connect("localhost","root","OtlPHP07");
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
// 2. Select a database to use
$db_select = mysql_select_db("widget_corp",$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
?>
<html>
<head>
<title>Databases</title>
</head>
<body>
<?php
// 3. Perform database query
$result = mysql_query("SELECT * FROM subjects", $connection);
if (!$result) {
die("Database query failed: " . mysql_error());
}
// 4. Use returned data
while ($row = mysql_fetch_array($result)) {
echo $row["menu_name"]." ".$row["position"]."<br />";
}
?>
</body>
</html>
<?php
// 5. Close connection
mysql_close($connection);
?>

There must be two reasons.....
1. may be you have mistaken in assigning table naem while using select query or while assigning host,username,password,db
2. you must use this before while loop
if(mysql_num_rows($result)>0){ while($row = mysql_fetch_array($result))
{
echo $row['name'];
} }
hope that solves your problem

This will tell you why your query is failing:
$result = mysql_query("SELECT * FROM ralf") or die(mysql_error());

Related

mySQL dropdown using PHP does not display options from database [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Improve this question
I looked at some other questions online and on here related to this, but none seem to really encounter my error exactly.
I wrote my PHP code and implemented it into my HTML, I get the dropdown box appearing, but it doesn't actually want to display any values. Is there any implementations or fixes I should include in my code? How do I get it to work?
My database is called: Treatments
My column in the database that I want displayed is called: Treatment
treatment_dropdown.php
<?php
$hostname = 'host_name';
$dbname = 'database_name';
$username = 'username';
$password = 'password';
$con=mysql_connect($hostname,$username,$password,$dbname) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db($dbname,$con) or die("Failed to connect to MySQL: " . mysql_error());
$query = "SELECT * FROM `Treatments`";
$result = mysql_query($con, $query);
$options = "";
while ($row = mysql_fetch_array($result)){
$options = $options . "<option>$row[1]</option>";
}
?>
HTML:
<body>
<select>
<?php
echo $options;
?>
</select>
</body>
Consider changing this line:
$query = "SELECT * FROM 'Treatments'";
to use backticks instead of single quotes like so:
$query = "SELECT * FROM `Treatments`";
In my test query I got an error because of this, let me know if that helps.
Add <?php include 'treatment_dropdown.php'; ?> to the top of your HTML file. This should give you access to the the $options string so it can be used in that file. Note that in order for this to work, treatment_dropdown.php needs to be in the same directory as your HTML file. If it is not, the include statement will need to be changed to reflect the appropriate file path.
Do not use mysql_*() functions, they are deprecated. Use mysqli or PDO instead.
No matter which library use use to access mysql, always check for errors within the sql code separately. Errors in the sql code do not result in errors in the php code.
In this particular case the problem is that you included the table in single quotes instead of backticks.
The correct code:
$query = "SELECT * FROM `Treatments`";
Here's what your PHP file should look like:
<?php
$hostname = 'localhost';
$dbname = 'Treatments';
$username = 'root';
$password = '';
$con = mysql_connect( $hostname, $username, $password, $dbname) or die("Failed to connect to MySQL: " . mysql_error());
$db = mysql_select_db($dbname,$con) or die("Failed to connect to MySQL: " . mysql_error());
/* No single quotes needed for the table name. */
$query = "SELECT * FROM Treatments";
/* First parameter should be $query not $con */
$result = mysql_query($query, $con);
$options = "";
/* Check if no results exist. */
if ( !$result ) {
die( "NO results found." );
}
while ( $row = mysql_fetch_array($result) ) {
$options .= "<option>$row[treatment]</option>";
}
?>
Notes:
dont use mysql_* functions, they're not secure, use PDO instead.
your table name does not need to be wrapped in single quotes.
mysql_query expects parameter 1 to be the query not the DB connection.
you should probably check if no results are found.

Warning: mysql_query(): Access denied for user 'admin'#'localhost' (using password: NO) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
It seems as though my PHP is trying to log in to the MySQL database with a username I am not supplying.
The error I am getting is:
Warning: mysql_query(): Access denied for user 'radiocaf'#'localhost' (using password: NO) in /home/radiocaf/public_html/layout.php on line 16
Warning: mysql_query(): A link to the server could not be established in /home/radiocaf/public_html/layout.php on line 16
I am definitely supplying a password, and am not using "radiocaf" as the username in my connect file, so after 3 hours of staring, I still can't work out where I am going wrong.
Here is my code:
psl-config.php:
define("HOST", "localhost");
define("USER", "carl");
define("PASSWORD", "xxxxxxxxx");
define("DATABASE", "wlist");
db_connect.php
include_once 'psl-config.php'; // As functions.php is not included
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
and then finally, the main page which is where I am receiving the error (I have cut out the HTML between the PHP:
ini_set('display_errors',1);
error_reporting(E_ALL);
//Include Connection PHP and connect
include_once('includes/db_connect.php');
//Check Connection
if ($mysqli->connect_error) {
die('Connection failed: ' . $mysqli->connect_error);
};
if (!$query = mysql_query("SELECT * FROM (
(SELECT * FROM users)
UNION ALL
(SELECT * FROM members)
) results
ORDER BY Name DESC")){
die("Error: " . mysqli_error($mysqli));
}
if (!$result = $mysqli->query($query)){
printf("Error: %s\n", $mysqli->error);
}
<HTML>
echo "<table border='0' cellpadding='0' cellspacing='0'>";
$x=0;
while($row = mysql_fetch_assoc($result)):
if ($x<10){
echo "<tr><td width='400' height='30' background='../images/green1.jpg'>".$row["Name"]."</td></tr>";
}
$x++;
if ($x == 10){
echo "<tr><td width='400' height'30' background='../images/green1.jpg'>More...</td></tr>";
break;
}
endwhile;
echo "</table>";
<HTML>
$mysqli->close();
The surrounding HTML is just the layout of the page, essentially just a photoshop layout, sliced and exported to web.
I am fairly new to PHP and so I hope this question is as explained as possible.
Edit:
Thanks so much guys, I apologise that this question seemed poor to some of you that you flagged it. Unfortunately I wouldn't have seen the "typos" as I really didn't know that I was attempting to use both mysql and mysqli and that they couldn't "communicate" with each other. Another issue I found was Dreamweaver uploaded the code from layout.php as db_connect.php. This doesn't explain (to me at least) how any connection was being made to bring up the access denied error for 'radiocaf'#'localhost' though.
Here's the old code lines I changed (in layout.php):
if (!$query = mysql_query("SELECT * FROM (
while($row = mysql_fetch_assoc($result)):
changed to:
if (!$query = "SELECT * FROM (
while($row = mysqli_fetch_assoc($result)):
And that's all it took, but I am entirely grateful! Thanks again everyone!
You are conflicting MySQL and MySQLi. MySQL and MySQLi are two different methods
Warning is:
Warning: mysql_query(): .....
But you're connecting database with mysqli
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);.
Warning in php.net:
MySQL extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
//Include Connection PHP and connect
//include_once('includes/db_connect.php');
$con=mysqli_connect(HOST, USER, PASSWORD, DATABASE);
//Check Connection
if ($mysqli->connect_error) {
die('Connection failed: ' . $mysqli->connect_error);
};
if (!$query = mysqli_query($con,"SELECT * FROM (
(SELECT * FROM users)
UNION ALL
(SELECT * FROM members)
) results
ORDER BY Name DESC")){
die("Error: " . mysqli_error($mysqli));
}
if (!$result = $mysqli->query($query)){
printf("Error: %s\n", $mysqli->error);
}
?>
<HTML>
<body>
<?php
echo "<table border='0' cellpadding='0' cellspacing='0'>";
$x=0;
while($row = mysqli_fetch_assoc($result)):
if ($x<10){
echo "<tr><td width='400' height='30' background='../images/green1.jpg'>".$row["Name"]."</td></tr>";
}
$x++;
if ($x == 10){
echo "<tr><td width='400' height'30' background='../images/green1.jpg'>More...</td></tr>";
break;
}
endwhile;
echo "</table>";
$mysqli->close();
?>
</body>
<HTML>

No result from query in PHP [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have made code without error for connection and data fetching but i don't know why result for query is bool(false)
<?php
$con=mysql_connect("localhost","root","","xyz");
echo "Connection made";
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
The code to query and execution is
<?php
include ("includes/connection.php");
$query="SELECT * FROM userdata ";
$result=mysql_query($query);
var_dump($result);
?>
Help needed here
You should use either mysql or mysqli. This is the main problem for the error
<?php
$con=mysqli_connect("localhost","root","","xyz") or die ("error in connection".mysqli_error($con);
?>
and use $result= mysqli_query($con, $sql) where $sql contains your query
As i stated in the comments, your echo up there to tell you you connected to the mysql server is not effective. I pulled out an old function from me to show you how to do it and make it clear where the error is.
$con = mysql_connect('localhost','root','');
$db = mysql_select_db('xyz',$con);
function OpenConnection(){
global $con;
global $db;
if (!$con){
die('cannot connect to server!');
}else{
if(!$db){
die('cannot connect to database!');
}
}
}
If you dont get anything back, you ll be good to go.
Don't use mysql_* functions they are depracted use mysqli or pdo instead.
You need to fetch results of your query with fetch functions like mysql_fetch_array() or mysql_fetch_row() to get results of your query. There are plenty of examples in PHP manual.
In your cause it would be something like this:
<?php
$con=mysql_connect("localhost","root","") or die("didn't connect to db");
mysql_select_db('name_of_your_db', $con);
$query="SELECT * FROM `userdata` ";
$result=mysql_query($query); //this returns resource ID that needs to be fetched
while($row = mysql_fetch_row($result))
print_r($row);
If $result is false it means that query failed it can be caused by several issues for example there is no DB selected, there is no connection etc.
I'd also give you better solution with PDO
<?php
$dsn = 'mysql:dbname=nameofyourdb;host=127.0.0.1';
$user = 'root';
$password = 'yourpass';
try
{
$db = new PDO($dsn, $user, $password);
foreach ($db->query("SELECT * FROM `userdata`") as $row)
print_r($row);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>

Outputting contents of database mysqli

Hi I know this is a little general but its something I cant seem to work out by reading online.
Im trying to connnect to a database using php / mysqli using a wamp server and a database which is local host on php admin.
No matter what I try i keep getting the error Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given when i try to output the contents of the database.
the code im using is:
if (isset($_POST["submit"]))
{
$con = mysqli_connect("localhost");
if ($con == true)
{
echo "Database connection established";
}
else
{
die("Unable to connect to database");
}
$result = mysqli_query($con,"SELECT *");
while($row = mysqli_fetch_array($result))
{
echo $row['login'];
}
}
I will be good if you have a look at the standard mysqli_connect here
I will dont seem to see where you have selected any data base before attempting to dump it contents.
<?php
//set up basic connection :
$con = mysqli_connect("host","user","passw","db") or die("Error " . mysqli_error($con));
?>
Following this basic standard will also help you know where prob is.
you have to select from table . or mysqli dont know what table are you selecting from.
change this
$result = mysqli_query($con,"SELECT *");
to
$result = mysqli_query($con,"SELECT * FROM table_name ");
table_name is the name of your table
and your connection is tottally wrong.
use this
$con = mysqli_connect("hostname","username","password","database_name");
you have to learn here how to connect and use mysqli

Cannot Display Data from MySQL table

I've got a pretty standard call to a MySQL database and for some reason I can't get the code to work. Here's what I have:
$mysqli = mysqli_connect("localhost","username","password");
if (!$mysqli)
{
die('Could not connect: ' . mysqli_error($mysqli));
}
session_start();
$sql = "SELECT * FROM jobs ORDER BY id DESC";
$result = $mysqli->query($sql);
$num_rows = mysqli_num_rows($result);
Now, first, I know that it is connecting properly because I'm not getting the die method plus I added an else conditional in there previously and it checked out. Then the page displays but I get the errors:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in blablabla/index.php on line 11
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in blablabla/index.php on line 12
I've double-checked my database and there is a table called jobs with a row of "id" (it's the primary row). The thing that confuses me is this is code that I literally copied and pasted from another site I built and for some reason the code doesn't work on this one (I obviously copy and pasted it and then just changed the table name and rows accordingly).
I saw the error and tried:
$num_rows = $mysqli_result->num_rows;
$row_array = $mysqli_result->fetch_array;
and that fixed the errors but resulted in no data being passed (because obviously $mysqli_result has no value). I don't know why the error is calling for that (is it a difference in version of MySQL or PHP from the other site)?
Can someone help me track down the problem? Thanks so much. Sorry if it's something super simple that I'm overlooking, I've been at it for a while.
You didn't selected the database
$mysqli = mysqli_connect("localhost","username","password","database");
The problem is you haven't selected the database.
use this code for select database.
$mysqli = mysqli_connect("localhost","username","password");
mysqli_select_db("db_name",$mysqli);
You have to select database in order to fire mysql queries otherwise it will give you error.
I believe that schtever is correct, I do not think you are selecting the database. It isn't in the code snip and if you search online you see other people with similar errors and it was because the database wasn't selected. Please let us know if you selected a database before anything else is checked. Thanks.
Try this:
session_start();
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if ($mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
$mysqli->close();
}
$query ="SELECT * FROM jobs ORDER BY id DESC";
$values = $mysqli->query($query);
if($values->num_rows != 0)
{
while($row = $values->fetch_assoc())
{
//your results echo here
}
}
else
{
//if no results say so here
}
See this manual for mysqli_connect you can select the database right in this function.

Categories