"no database selected" error even query is fine - php

I am new to mysql and php. I am working on database programming with php with mysql but getting "no data base selected" error continuously. I found this error quite famous on internet. I tried every answer which were given to others having the same problem but nothing worked.
Here is my code:
if(!#mysql_connect('localhost','root','') || !#mysql_select_db ('a_database') ){
die ('Connection Error !');
}
$query = "SELECT `food`,`calories` FROM `food` ORDER BY `id`";
if($query_run=mysql_query($query)){
while($query_row = mysql_fetch_assoc($query_run))
{
$food = $query_row['food'];
$calories = $query_row['calories'];
echo $food.' has '.$calories.' Calories'.'<br>';
}
} else {
echo mysql_error();
}
This is the code that gives error. After some search on net. I made some bit of changes, but the result was same.
Changes that I made to first 3 to 4 lines:
$link = mysql_connect('localhost','root','');
if(!$link || !mysql_select_db ('a_database', $link) ){
die ('Connection Error !');
}
Please tell me what should I do to get rid of this problem, Thank you.

Try with this
<?php
// Create connection
$con=mysqli_connect("localhost","root","","a_database");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Try this
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n"; // if everything is successful
And yes don't use mysql_* as it's deprecated, use mysqli_ or PDO.

Related

I have problem in insert data into database but didn't show any error

I have problem with inserting my data into database
usually if something wrong it's showing error but this one not showing error (I don't know if this count as error or not cause I'm still new with this php coding stuff)
<?php
/*proses*/
$conn = mysqli_connect('localhost','root', '','dsolo');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$id = $_POST['id'];
$bulan = $_POST['bulan'];
$gajipokok = $_POST['gajipokok'];
$totalbonus = $_POST['totalbonus'];
$potongan = $_POST['potongan'];
$totalgaji = $_POST['totalgaji'];
$pajak = $_POST['pajak'];
$tes="INSERT INTO gaji set id='$id',
bulan='$bulan',
gajipokok='$gajipokok',
totalbonus='$totalbonus',
potongan='$potongan',
totalgaji='$totalgaji',
pajak='$pajak',";
mysqli_query ($conn,$tes) or die ($tes);
?>
After I press save what is showing is this one instead
INSERT INTO gaji set id='yuki', bulan='2019-08', gajipokok='2000000', totalbonus='2000000', potongan='1000000', totalgaji='3000000', pajak='300000',
What I need to change in my code?
There is an extra , in your query, you can remove that and your code look like the below code..
<?php
$conn = mysqli_connect('localhost','root', '','dsolo');
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
else
{
$id = $_POST['id'];
$bulan = $_POST['bulan'];
$gajipokok = $_POST['gajipokok'];
$totalbonus = $_POST['totalbonus'];
$potongan = $_POST['potongan'];
$totalgaji = $_POST['totalgaji'];
$pajak = $_POST['pajak'];
$tes="INSERT INTO gaji set id='$id', bulan='$bulan', gajipokok='$gajipokok', totalbonus='$totalbonus',potongan='$potongan', totalgaji='$totalgaji', pajak='$pajak'";
mysqli_query ($conn,$tes) or die ($tes);
}
?>

Checking whether username exists in MySQLi Database and PHP

I have been working on a website which has a xampp server and a database called users with a table called AccountDetails. About a year ago I got it to work perfectly, but the server I was using then required MySQL not MySQLi. Now I have to use MySQLi and can't even get the simplest of sql's SELECT function to work, any ideas would be much appreciated.
<?php
$link = mysqli_connect("localhost:3306", "root","", "users");
if(mysqli_connect_errno($link)){
echo "MySql Error: " . mysqli_connect_error();
} else {
echo"Connection Successful <br></br>";
}
echo("Check if still working <br></br>");
// -----------------------------//
echo("Its running <br></br>");
$result = $link->query("SELECT ID, UserName FROM AccountDetails");
return $result->result();
var_dump($result);
mysqli_close($link);
?>
The Query itself works when I plug it into the phpmyadmin SQL section and it returns the values that I expect it too.
I've spent days looking online for different answers but none of them work, and the var_dump only gives me "bool(false)" which I don't think I should be getting.
You can try this code
<?php
$link = mysqli_connect("localhost:3306", "root","", "users");
if(mysqli_connect_errno($link)){
echo "MySql Error: " . mysqli_connect_error();
} else {
echo"Connection Successful <br></br>";
}
echo("Check if still working <br></br>");
// -----------------------------//
echo("Its running <br></br>");
$sql_select = "SELECT * FROM AccountDetails";
$result = $link->query($sql_select);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "UserName: " . $row['UserName']. "<br>";
}
} else {
echo "No Records";
}
$link->close();
?>

Check for specific entry in database

I want to check whether a specific entry is present in my database or not. If present then condition,if not then condition. I tried this code but got errors
<?php
$con=mysqli_connect("localhost","root","","student");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classname = mysqli_real_escape_string($con, $_POST['class']);
$result = mysql_query("SELECT * FROM subjectinfo WHERE class = '{$classname}'", $con);
if(mysql_num_rows($result) == 0)
{
echo "No Such Entry In Table. Please ADD it First.";
}
else
{
echo "Entry Available";
}
}
mysqli_close($con);
?>
Errors :
Warning: mysql_query() expects parameter 2 to be resource, object given in C:\xampp\htdocs\pages\test.php on line 11
Warning: mysql_num_rows() expects parameter 1 to be resource, null given in C:\xampp\htdocs\pages\test.php on line 13
No Such Entry In Table. Please ADD it First.
Like your comments. Make sure you don't mix up mysqli and mysql. mysql is deprecated so you're better off using mysqli.
$con=mysqli_connect("localhost","root","","student");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classname = mysqli_real_escape_string($con, $_POST['class']);
$result = mysqli_query($con, "SELECT * FROM subjectinfo WHERE class = '{$classname}'");
if(mysqli_num_rows($result) == 0)
{
echo "No Such Entry In Table. Please ADD it First.";
}
else
{
echo "Entry Available";
}
}
mysqli_close($con);
?>
You are mixing MySQL APIs - mysql_ + mysqli_ they do not mix together. Plus, your DB connection's backwards in your query. The connection comes first.
Here:
<?php
$con=mysqli_connect("localhost","root","","student");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classname = mysqli_real_escape_string($con, $_POST['class']);
$result = mysqli_query($con,"SELECT * FROM subjectinfo WHERE class = '{$classname}'");
if(mysqli_num_rows($result) == 0)
{
echo "No Such Entry In Table. Please ADD it First.";
}
else
{
echo "Entry Available";
}
}
mysqli_close($con);
?>
Also use or die(mysqli_error($con)) to mysqli_query()
Plus, add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
Look into using prepared statements, or PDO with prepared statements, they're safer.
An insight:
Make sure your form element is indeed named.
I.e.:
<input type="text" name="class">
otherwise, you will receive an Undefined index class... warning.

mysql_connect doesn't return anything

Heres my code. Simple.
<?php
echo 'start<br>';
//Do the conntection
$checkconnection = mysql_connect('localhost', 'root', 'rootpass');
//Check if it's valid
if(!$checkconnection) {
echo 'CheckFailed';
} else{
echo 'CheckSucess';
}
echo 'end'; ?>
but I only can see 'start'. There is no 'CheckFailed', 'CheckSucess', 'end'
What should I do?
I already install mysql, create database, create tables, of course.
<?php
// Create connection
$con=mysqli_connect("localhost","root","root","database");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return false;
}
$result = mysqli_query($con, "SELECT * FROM table;");
?>

php not displaying results on database

I have a database with 4 tables. (products,purchase,customer,user). When I tried to display all rows in products, no results. But in the user table, it displays. What should be the problem? Is it on my database?tables?php code?
Here's my code:
<?php
$db = mysqli_connect("localhost","root","", "prodpurchase");
if (!$db) {
die('Could not connect: ' . mysqli_error());
}
$sql = mysqli_query($db, "select * from user");
if( $sql === FALSE ) {
die('Query failed returning error: '. mysqli_error());
} else {
while($row=mysqli_fetch_array($sql))
{
echo $row['username']. "<br>";
}
}
?>
Hope you could help me.
Did you check the letters uppercase and lowercase in table columns?
You have inventory in your code, but in your question you named the table products, Is it this simple?
echo $row['item']. "<br>";
What is 'item'? Shouldn't you be selecting them by $row[0] or $row['products'].. or one of your other columns.
check your variables, for your example, try renaming your vairable $sql to something else, because you might have a similar variable somewhere in your code that you did not show.
try this :
<?php
$db = mysqli_connect("localhost","root","", "prodpurchase");
if (!$db) {
die('Could not connect: ' . mysqli_error());
}
$sqlstackoverflow = mysqli_query($db, "select * from user");
if($sqlstackoverflow === FALSE ) {
die('Query failed returning error: '. mysqli_error());
} else {
while($row=mysqli_fetch_array($sqlstackoverflow))
{
echo $row['username']. "<br>";
}
}
?>
Your code references an inventory table but you said your database has a products table (and no inventory table). Because of this, the query is failing.
Just Try With The Following :
<?php
$db = mysqli_connect("localhost","root","","prodpurchase");
if (!$db) {
die('Could not connect: ' . mysqli_error());
}
$sql = mysqli_query($db,"select * from user");
if( $sql === FALSE ) {
die('Query failed returning error: '. mysqli_error());
} else {
while($row=mysqli_fetch_array($sql,MYSQLI_ASSOC))
{
echo $row['username']."<br>";
}
}
?>
I think this may help you to resolve your problem.

Categories