No result from query in PHP [closed] - php

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();
}
?>

Related

How do I obtain data through a MySQL Database using GET in PHP?

I've tried the solutions in this question, however mysql has been depricated for mysqli. Even with these changes it still doesn't return the information, instead returns an error, with nothing else (Nothing is heard from mysqli)
What i'm trying to do is kind of similar to the question linked, however it would look like this in the url: example.com?view-work=A01 It would search for A01 in the database, then return the Name, description, an image URL and date it was made live.
This is the code that i've been able to make using the answers from the question:
<?php
//Establishing a connection to the Artwork Database
mysqli_connect('localhost', 'dbuser', 'dbpassword');
mysqli_select_db('db');
$artworkidentifier = $_GET["view_work"];
//Returning the result, if there is one
$artworkidentifier = mysqli_real_escape_string($artworkidentifier);
$sql = "SELECT * FROM ArtDB WHERE art_refcode = '$artworkidentifier'";
$result = mysqli_query($sql);
if (!$result) {
echo "Something's gone wrong! ".mysqli_error();
}
$data = mysqli_fetch_assoc($result);
echo $data["Artwork_Name"];
echo $data["Artwork_Description"];
echo $data["Artwork_URL"];
echo $data["DateUploaded"];
?>
Seems like the cause of these errors was my own incompetence, also probably the fact I'm kind of new to PHP and MySQL in general. I learnt that I needed to reference my connection in some of the commands for them to successfuly process after adding the debug exception mentioned in the OP's comments.
As someone also pointed out, Yes this code is still vulnerable to other types of SQL injection, I'll be addressing these before the final version of the code goes live.
Fixed Code:
<?php
//Establishing a connection to the Artwork Database
$link = mysqli_connect('localhost', 'dbusr', 'dbpasswd', 'db');
//Exeptional Debugging
ini_set('display_errors', 1);
ini_set('log_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if (!$link) {
echo "Error: Unable to connect to MySQL!";
echo "Error No.".mysqli_connect_errno();
echo "Error in question: ".mysqli_connect_error();
exit;
}
$artworkidentifier = $_GET["view_work"];
//Returning the result, if there is one
$artworkidentifier = mysqli_escape_string($link, $artworkidentifier);
$sql = "SELECT * FROM ArtDB WHERE art_refcode = '$artworkidentifier'";
$result = mysqli_query($link, $sql);
if (!$result) {
echo "Something's gone wrong!"; //This line will be changed later to sound more professional
}
$data = mysqli_fetch_assoc($result);
echo $data["Artwork_Name"];
echo $data["Artwork_Description"];
echo $data["Artwork_URL"];
echo $data["DateUploaded"];
?>

php - MySQL Error 1040 "Too many connections"

I have this error, I have seen on several pages how to fix it, increasing the max connections variable, but I was wondering if there is any way to retry connecting 'n' number of times before throwing that error,
I am using mysqli to create my connection.
I would be very grateful for any help you could give me to get an idea of ​​how to do it if possible
update
con.php
<?php $con = new mysqli("localhost", "root", "", "grmv");
if($conexion->connect_errno) {
die ("Error: " . $con->connect_errno . "---" . $con->connect_error);
}
return $con;
?>
Products.php
<?php
include"con.php";
mysqli_query($con,"SET NAMES 'utf8'");
$result=mysqli_query($con,"select * from bio, carac where idprod=5");
while($data=mysqli_fetch_array($result)){
....
}
$conexion->close();
}
?>
More consistent way is to keep using OOP aproach, also good practice to use bind for any untrusted input, maybe not here specifically but still good practice.
$mysqli = new mysqli(
$connectionData['DB_HOST'],
$connectionData['DB_USER'],
$connectionData['DB_PASSWORD'],
$connectionData['DB_NAME']
);
$mysqli->set_charset('utf8');
$stmt = $mysqli->prepare("select * from bio, carac where idprod=?");
$stmt->bind_param('5');
$stmt->execute();
while ($result = $stmt->fetch()) {
// do stuff
}
$stmt->close();

moving my sql database localhost to live server

i want to move my sql database and i have exported and imported mysql.sql file from localhost to live server and now i m not getting the files and content from that database. what i do ? i did make sure connection to database if fine and successful
here's my page http://shooop23.byethost7.com
<?php
$db = mysqli_connect('','','','');
if(mysqli_connect_errno()){
echo'Database Connection Failed with following errors: '. mysqli_connect_errno();
die();
}
?>
Once you have successfully established a connection to MySQL, you need to perform a query specifying what you want to retrieve and then subsequently retrieve it.
The following example uses mysqli_fetch_row
You should explore the documentation to learn the basics.
$db = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
if(mysqli_connect_errno()){
echo'Database connection failed with the following error: '.mysqli_connect_errno();
exit;
}
if ($result = mysqli_query($db, "SELECT MyCol1,MyCol2 FROM MyTable")) {
while ($row = mysqli_fetch_row($result)) {
echo"{$row[0]} - {$row[1]}<br>");
}
mysqli_free_result($result);
}
mysqli_close($db);
$db = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
$sql="SELECT * FROM login";
here i connected and stored my database and set a sql command (which is now a string) into these two veriables.
if(mysqli_connect_errno()){
echo'Database connection failed with the following error: '.mysqli_connect_errno();
exit;
}
this is to check if the database is correctly connected, if not then it will show some errors.
$result = mysqli_query($db,$sql);
here i put the database and the sql command to run my query.
while($row = mysqli_fetch_array($result)){
echo $row['username'];
}
here finally outputting the usernames(username is one of the column in my table in this case) which matched with that query
i will suggest This Sql site to get a better understanding on sql queries and try to improve the secuirty because this is the basic point where hackers try to inject their attact most offenly.
Note : If your table's in the database are empty then it will not able to fetch anything

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

No idea why this code will not work [closed]

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());

Categories