Error in php Database connection - php

I'm getting the error: No database selected
Here is the code:
<?php
$host = "localhost";
$user = "root";
$password = "";
$database_name = "Student";
mysql_connect($host, $user, $password);
mysql_select_db($database_name);
?>
This code is for php-connect.php class and for the form:
<!DOCTYPE html>
<html>
<body>
<?php
//load database connection
include("php-connect.php");
$id = "1";
$name = "Elena";
$city = "Lahore";
//Command to insert into table
$query = "INSERT INTO studentdata (id,name,city) VALUES ('$id','$name','$city')";
//run the query to insert the person.
$result = mysql_query($query) OR die(mysql_error());
//let them know the person has been added.
echo "Data successfully inserted into the database table ... ";
?>
</body>
</html>
This is the code for the form.. I've tried a lot of things to fix this error but it does not work. Is there any problem with my database?

Try this...
<?php
$host = "localhost";
$user = "root";
$password = "";
$database_name = "Student";
$mLink = mysql_connect($host, $user, $password) or die(mysql_error());
mysql_select_db($database_name , $mLink);
another file
<?php
require 'php-connect.php';
//...... etc..
but, read this first:
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information. Alternatives to this function include:
mysqli_select_db()
PDO::__construct() (part of dsn)
http://br.php.net/mysql_select_db

Related

separate db connection.php from db queries

I want to improve my non-existing PHP knowledge. To do so I created a MySQL DB and a connection.php file with an SQL query (please ignore SQL injection comments for now, I am aware of it). I trying to figure out, how I can split the connection from the actual query.
<?php
header("Access-Control-Allow-Origin: *");
$username = "root";
$password = "root";
$host = "localhost";
$database="test";
$connection = mysqli_connect($host, $username, $password, $database);
$myNodesQuery = "
SELECT * FROM nodes";
$query = mysqli_query($connection, $myNodesQuery);
if ( ! $query ) {
echo mysqli_error();
die;
}
$data = array();
for ($x = 0; $x < mysqli_num_rows($query); $x++) {
$data[] = mysqli_fetch_assoc($query);
}
//echo json_encode($data, JSON_FORCE_OBJECT);
echo json_encode($data);
mysqli_close($connection);
My thoughts were to create another PHP file and add $connection = mysqli_connect (require('connection.php')) to receive the connection string. Unfortunately, I receive a path error.
Keeping your code as is then:
File connection.php:
<?php
$username = "root";
$password = "root";
$host = "localhost";
$database="test";
$connection = mysqli_connect($host, $username, $password, $database);
The main file
<?php
header("Access-Control-Allow-Origin: *");
require 'connection.php';
$myNodesQuery = "
SELECT * FROM nodes";
// whatever follows
...
Please note that - unless you use a framework - it would be much better if you build your reusable connection class or connection-returning function. And BTW consider using the far superior PDO.

I can't update my MySQLi Database with PHP (no Errors)

I can't Update my Database with PHP. I don't get any errors but it doesn't change anything!
Here is my file:
<?php
include_once 'dbh.inc.php';
?>
<?php
$id = $_GET['verId'];
$name = $_GET['verName'];
echo $id;
echo $name;
$sql = "UPDATE allusers SET ver = '1' WHERE idUsers = '$id';";
?>
The variables are defined and work.
Here's the dbh.inc.php file:
<?php
$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "loginsystem";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
if (!$conn) {
die("Connection failed: ".msqli_connect_error());
}
?>
Other files that use dbh.inc.php work fine.
Thanks for your help.
You need to execute your SQL, but the way you are using MySQLi is very wrong. Let me show you how to get started with a simple query.
First in your dbh.inc.php (you should name it properly too) you should have the following code:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new \mysqli("localhost", "root", "", "loginsystem");
$conn->set_charset('utf8mb4');
Do not use root for connection. Create a valid MySQL user with a proper password.
Then in your main PHP file, you can use it as follows:
<?php
include_once 'dbh.inc.php';
$id = $_GET['verId'];
$name = $_GET['verName'];
echo $id;
echo $name;
// prepare -> bind data -> execute
$stmt = $conn->prepare("UPDATE allusers SET ver='1' WHERE idUsers=?");
$stmt->bind_param('s', $id);
$stmt->execute();
I used here what is called a prepared statement. You can learn more about MySQLi here: https://phpdelusions.net/mysqli_examples/update

Having trouble while receiving data in database

I am trying trying to receive data by making a html form and then adding receiving data by $_GET method.Whenever I try to submit my data I get an error saying 'Your file was not found' in my chrome browser,so I tried opening my php page in chrome by typing "localhost/...." in my address bar and there it was displaying 'Database NOT Found'
here is my php code:-
<html>
<?php
$user_name = "root";
$password = "";
$database = "mysql"; //mysql is name of my database
$server = "localhost";
$db_handle = mysql_connect($server , $user_name, $password,"addresbook"); //adressbook is where all the tabels are
$db_found = mysql_select_db($database, $db_handle);
if (!$db_found) {
print "Database Found ";
$x=$_GET['fname'];
$y=$_GET['sname'];
$z=$_GET['address'];
$sql="INSERT INTO addresbook(First_Name,Surname,Address) VALUES('".$x."','".$y."','".$z."')";
mysql_query($sql,$db_handle);
}
else {
print "Database NOT Found ";
}
?>
</html>
here is mt html code:-
<form action="practic.php"method="get">
Firstname:<input type="text" name="fname"><br>
Lastname:<input type="text" name="sname"><br>
Address:<input type="text" name="address"><br>
<input type="submit">
</form>
btw i am using wamp server.Thanks in advance.
$db_found will be true on success, so your condition should be
if ($db_found) { // make DB changes etc.
and switch to MySQLi or PDO and use prepared statements as already mentioned, refer to the manual:
http://php.net/manual/en/mysqli.prepare.php
use mysqli_connect because mysql_connect is now deprecated.
$db_handle = mysqli_connect($server , $user_name, $password,$database);
refer here for connection
http://www.w3schools.com/php/func_mysqli_connect.asp
Hi change your code to use MysqLi or use PDO
<?php
$user_name = "root";
$password = "";
$database = "mysql"; //mysql is name of my database
$server = "localhost";
$con = mysqli_connect($server,$user_name,$password,'adresbook');//adresbook is where all the tabels are
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
// Change database to "adresbook"
$db_found = mysqli_select_db($con,'adresbook');
if ($db_found) {
print "Database Found ";
$x=$_GET['fname'];
$y=$_GET['sname'];
$z=$_GET['address'];
$sql="INSERT INTO addresbook(First_Name,Surname,Address) VALUES('".$x."','".$y."','".$z."')";
mysqli_query($con, $sql);
}
else {
print "Database NOT Found ";
}
?>
Your phpMyadmin should look like this with the database addresbook with a single s.

php insert to mysql multiple inputs over 100

I've created a user form in which once the submit button is pressed I would like to send/insert the data to mysql database adding a new record. The form has over 100 input fields. How can I accomplish this. Here is my sample php code.
<html>
<head>
</head>
<body>
<?php
if (isset($_POST['submit'])){
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "hostname";
$username = "username";
$password = "password";
$dbname = "dbname";
$mystuff = "tenant_lname","tenant_fname","tenant_mname","ssn","dl_number","dl_state","birthday","tenant_hphone","tenant_wphone","tenant_cphone","curr_street","curr__unit","curr_city","curr_state","curr_zip","how_long_from","how_long_to","last_rent_mnt","last_rent_amt","own_man_name","own_man_tel","curr_reason","pre_street","pre_unit","pre_city","pre_state","pre_zip","pre_from","pre_to","pre_last_rent","pre_amt","pre_owner","pre_owner_tel","pre_reason","sec_pre_street","sec_pre_unit","sec_pre_city","sec_pre_state","sec_pre_zip","sec_pre_from","sec_pre_to","sec_pre_last_paid_mnt","sec_pre_amt","sec_pre_owner","sec_pre_owner_tel","sec_pre_reason","curr_emp_name","curr_emp_add","curr_emp_phone","curr_emp_pos","curr_emp_bus_type","curr_emp_sup","curr_emp_from","curr_emp_to","curr_emp_salary","pre_emp_name","pre_emp_add","pre_emp_phone","pre_emp_pos","pre_emp_bus_type","pre_emp_sup_name","pre_emp_from","pre_emp_to","pre_emp_salary","move_date","addntl_occ_name","addntl_occ_age","addntl_occ_relation","addntl_ft","addntl_pt","addntl_occ1_name","addntl_occ1_age","addntl_occ1_relation","addntl_occ1_ft","addntl_occ1_pt","addntl_occ2_name","addntl_occ2_age","addnt2_occ1_relation","addntl_occ2_ft","addntl_occ2_pt","addntl_occ3_name","addntl_occ3_age","addntl_occ3_relation","addntl_occ3_ft","addntl_occ3_pt","credit_yes","credit_no","det_yes","det_no","evict_yes","evict_no","bnkry_yes","bnkry_no","fel_yes","fel_no","pet_yes","pet_no","pet_numb","pet_type","furn_yes","furn_no","ins_cov_yes","ins_cov_no","ints_yes","ints_no","ints_type","smoke_yes","smoke_no","occ_smoke_yes","occ_smoke_no","explain_smoke","bnk_name","bnk_add","checking","checking_bal","saving","saving_bal","bnk_name1","bnk_add1","checking1","checking_bal1","saving1","saving_bal1","other_income","credit_name","credit_add","credit_city","credit_acct","credit_bal","credit_payment","credit_name1","credit_add1","credit_city1","credit_acct1","credit_bal1","credit_payment1","credit_acct2_name","credit_add2","credit_city2","credit_acc2","credit_bal2","credit_payment2","credit_acc3_name","credit_acc3_add","credit_acc3_city","credit_acc3_number","credit_acc3_bal","credit_acc3_payment","emer_contact_name","emer_contact_add","emer_relation","emer_phone","reg_owner_yes","reg_owner_no","reg_who","vehicle_year","vehicle_make","vehicle_model","vehicle_color","vehicle_license","veh_state","vehicle2_year","vehicle2_make","vehicle2_model","vehicle2_color","vehicle2_license","veh2_state";
$con = mysql_connect("$hostname","$username","$password");
if (!$con){
die ("Can not connect:" . mysql_error());
}
mysql_select_db("dbname",$con);
$sql = "INSERT INTO dbname ($mystuff) VALUES ('$_POST[$mystuff]')";
mysql_query($sql,$con);
mysql_close($con);
}
?>
</body>
</html>
I will suggest simply write this manually. Don't be so lazy. And use PDO instead of mysql_query because it is future safe. Read the documentation on http://php.net.
Change $mystuff to an array and use foreach to loop through the array and generate post data.
$mystuff = array("tenant_lname","tenant_fname","tenant_mname","ssn","dl_number","dl_state","birthday","tenant_hphone","tenant_wphone","tenant_cphone","curr_street","curr__unit","curr_city","curr_state","curr_zip","how_long_from","how_long_to","last_rent_mnt","last_rent_amt","own_man_name","own_man_tel","curr_reason","pre_street","pre_unit","pre_city","pre_state","pre_zip","pre_from","pre_to","pre_last_rent","pre_amt","pre_owner","pre_owner_tel","pre_reason","sec_pre_street","sec_pre_unit","sec_pre_city","sec_pre_state","sec_pre_zip","sec_pre_from","sec_pre_to","sec_pre_last_paid_mnt","sec_pre_amt","sec_pre_owner","sec_pre_owner_tel","sec_pre_reason","curr_emp_name","curr_emp_add","curr_emp_phone","curr_emp_pos","curr_emp_bus_type","curr_emp_sup","curr_emp_from","curr_emp_to","curr_emp_salary","pre_emp_name","pre_emp_add","pre_emp_phone","pre_emp_pos","pre_emp_bus_type","pre_emp_sup_name","pre_emp_from","pre_emp_to","pre_emp_salary","move_date","addntl_occ_name","addntl_occ_age","addntl_occ_relation","addntl_ft","addntl_pt","addntl_occ1_name","addntl_occ1_age","addntl_occ1_relation","addntl_occ1_ft","addntl_occ1_pt","addntl_occ2_name","addntl_occ2_age","addnt2_occ1_relation","addntl_occ2_ft","addntl_occ2_pt","addntl_occ3_name","addntl_occ3_age","addntl_occ3_relation","addntl_occ3_ft","addntl_occ3_pt","credit_yes","credit_no","det_yes","det_no","evict_yes","evict_no","bnkry_yes","bnkry_no","fel_yes","fel_no","pet_yes","pet_no","pet_numb","pet_type","furn_yes","furn_no","ins_cov_yes","ins_cov_no","ints_yes","ints_no","ints_type","smoke_yes","smoke_no","occ_smoke_yes","occ_smoke_no","explain_smoke","bnk_name","bnk_add","checking","checking_bal","saving","saving_bal","bnk_name1","bnk_add1","checking1","checking_bal1","saving1","saving_bal1","other_income","credit_name","credit_add","credit_city","credit_acct","credit_bal","credit_payment","credit_name1","credit_add1","credit_city1","credit_acct1","credit_bal1","credit_payment1","credit_acct2_name","credit_add2","credit_city2","credit_acc2","credit_bal2","credit_payment2","credit_acc3_name","credit_acc3_add","credit_acc3_city","credit_acc3_number","credit_acc3_bal","credit_acc3_payment","emer_contact_name","emer_contact_add","emer_relation","emer_phone","reg_owner_yes","reg_owner_no","reg_who","vehicle_year","vehicle_make","vehicle_model","vehicle_color","vehicle_license","veh_state","vehicle2_year","vehicle2_make","vehicle2_model","vehicle2_color","vehicle2_license","veh2_state");
$post_data = '';
$post_array = implode(',',$mystuff);
foreach($mystuff as $value)
{
$post_data .=($post_data)? ",'".$_POST[$value]."'" : "'".$_POST[$value]."'" ;
}
$sql = "INSERT INTO dbname ($post_array) VALUES ($post_data)";

php include is not working

I'm trying to get my config.php file to work but everytime i use it with my login.php it just gives me a white page rather than continuing through my login.php file towards my members.php page. I put my connection info into my login.php script and it works properly listed below is what i been trying to do.
config.php
<?php
$con = mysql_connect("mysql","DBUSER","DBPASS");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("DBNAME", $con);
/* WHAT I ORIGINALLY WANTED TO USE
$localhost = "mysql";
$dbuser = "DBUSER";
$dbpass = "DBPASS";
$dbname = "DBNAME";
$connect = mysql_connect($localhost, $dbuser, $dbpass);
mysql_select_db("$dbname", $connect);
*/
?>
login.php
<?php
// I ALSO USED includes"config.php";
require("config.php");
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysql_query("SELECT * FROM member WHERE username = '$username' AND password = '$password'");
$data = mysql_fetch_assoc($query);
if(mysql_num_rows($query)){
session_start();
$_SESSION['username'] = $data['username'];
header("Location: members.php");
exit;
}
header("Location: index.php");
?>
I'm new to PHP so don't laugh at my code please thanks for the help!
On top of your code turn on errors:
ini_set("display_errors","On");
and make sure you can see your mysql errors:
$query = mysql_query(...) or die("Error: ".mysql_error());
And one last thing: although mysql_* functions are being deprecated, if you use them always escape your data before you use it in your query; you can be victim of SQL injection.
try to use:
include "config.php";
it should be include not includes

Categories