mysql_select_db using POST variable - php

I am quite new to PHP, and still have long way to go. Probably, it is a logic failure or maybe I just dont know how exactly PHP works.
Anyway, The code I submited is from my admin control panel. I am trying to make a page to connect to db than show all db names and select one of them from radio buttons. And when pressed submit again to show tables.After showing table the next step will be to edit,add update them etc. I am not there yet. Because I could not make mysql_select_db to work. It gives error.
The error is;
Notice: Undefined variable: connect in /public_html/php/insert_delete_update_amend/mydata03.php on line 94
Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in /public_html/php/insert_delete_update_amend/mydata03.php on line 94
Could not connect to db
Any help will be much appreciated.
P.S.: Also when the first form is submitted,first form disappears and second one appears and so on.
<?php
// form variables
$DisplayDBinfoForm = true;
$DisplayDBform = false;
if (isset($_POST['db_info_submit'])) { //when user presses db info submit button
//select which form to hide or appear
$DisplayDBinfoForm = false;
$DisplayDBform = true;
$hostname = $_POST['db_name'];
$db_user_name = $_POST['db_user_name'];
$db_user_password = $_POST['db_user_password'];
$connect = mysql_connect($hostname,$db_user_name,$db_user_password);
if(!$connect) die("Could not connect");
echo "<p><b>connected successfully</b></p>\n";
}
if($DisplayDBinfoForm) {
?>
<form name="dbinfo" method="POST" action="mydata03.php" onsubmit="return validateForm();">
Host Name: <input type="text" name="db_name" /><br />
<br />
DB User Name <input type="text" name="db_user_name" /><br />
<br />
DB User Password: <input type="text" name="db_user_password" /><br />
<br />
<input type="submit" name="db_info_submit"value="Login"><br />
</form>
<?php
}
if($DisplayDBform) {
?>
<form name="delete_table" id="delete_table" action="mydata03.php" method="post">
<table width="30%" border="1">
<tbody>
<?php
$query = "SHOW DATABASES";
$resultSet = mysql_query($query);
while($database = mysql_fetch_array($resultSet)) { // go through each row that was returned in $result
$dbname = $database[0];
echo "<tr><th>Database Name</th>
<th>Select</th>
</tr>
<tr>
<td>$dbname</td>
<td><input name=\"radDB\" id=\"radDB\" type=\"radio\" value=\"$dbname\"</td>
</tr>\n";
}
?>
</tbody>
</table>
<p>
<input name="btnSelectDB" type="submit" value="Select" />
</form>
</p>
<?php
}
if(isset($_POST['btnSelectDB'])) {
$DisplayDBinfoForm = false; // hide form
$DisplayDBform = false; // hide form
$db_name = $_REQUEST["radDB"]; // the db na,e
echo "The " . $db_name . " is selected\n";
$select_db = mysql_select_db($db_name,$connect);
if(!$select_db) die("Could not connect to db". mysql_error());
echo "<b>connected successfully to db</b>";
}
?>

First off, don't use mysql_* functions. That time has passed. Instead, use mysqli_* or PDO.
With that said, it appears that the initial connection to the database server complete fine, as your code doesn't crap out on you at:
$connect = mysql_connect($hostname,$db_user_name,$db_user_password);
if(!$connect) die("Could not connect");
Although at the later stage, when trying to connect to an actual database: $select_db = mysql_select_db($db_name,$connect); it does.
This leaves me to believe that the variable in which you set the database name $db_name = $_REQUEST["radDB"]; is not pulling the data in correctly.

try
$connect = mysql_connect($hostname,$db_user_name,$db_user_password) or die("Could not connect");
if( $connect)
echo "<p><b>connected successfully</b></p>\n";
}
also check that the
if( isset($_POST['db_name'] ) && isset($_POST['db_user_name']) && isset($_POST['db_user_password']){
$hostname = $_POST['db_name'];
$db_user_name = $_POST['db_user_name'];
$db_user_password = $_POST['db_user_password'];
}
Use of this extension(MYSQL_*) is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used
Good Read
PDO Tutorial for MySQL Developers

The problem you have is that the database is only opened ($connect=) if you have done a post with 'db_info_submit', but you can still run line 94 if you have posted 'btnSelectDB'.
Simplest solution is to open the database outside the if ($_POST) statement at the top, in case it's needed below. Or wrap in either of the conditions required to open it (code shown below)
<?php
// form variables
$DisplayDBinfoForm = true;
$DisplayDBform = false;
if (isset($_POST['db_info_submit']) || isset($_POST['btnSelectDB'])) {
$connect = mysql_connect($hostname,$db_user_name,$db_user_password);
if(!$connect) die("Could not connect");
echo "<p><b>connected successfully</b></p>\n";
}
}
if (isset($_POST['db_info_submit'])) { //when user presses db info submit button
//select which form to hide or appear
$DisplayDBinfoForm = false;
$DisplayDBform = true;
$hostname = $_POST['db_name'];
$db_user_name = $_POST['db_user_name'];
$db_user_password = $_POST['db_user_password'];
}
if($DisplayDBinfoForm) {
?>
....
<?php
}
if(isset($_POST['btnSelectDB'])) {
$DisplayDBinfoForm = false; // hide form
$DisplayDBform = false; // hide form
$db_name = $_REQUEST["radDB"]; // the db na,e
echo "The " . $db_name . " is selected\n";
$select_db = mysql_select_db($db_name,$connect);
if(!$select_db) die("Could not connect to db". mysql_error());
echo "<b>connected successfully to db</b>";
}
?>
This isn't a direct answer, but it's the answer that's goign to help you the most.
If you have a function in your script that begins "myslq_" (except for 1 - mysql_real_esacape_string) then you're following an old example and are using code that is going to be depreciated. As you're just learning PHP and MySQL, get into the habits of using the more modern functions, either mysqli_ or PDO

Related

php database connection/selection

I have a login.html in which the form is defined as follows:
<form method="post" action= "do_authorize.php" name="lform">
<span class="style1">First Initial Plus Last Name :</span>
<input type="text" name="user" size="25">
<input type="submit" value="login">
</form>
My do_authorize is as follows:
<?php
session_start();
require('../databaseConnectionFileFolder/dbconnection.php');
$user = $_POST["user"];
var_dump($user);
$_SESSION['username']=$user;
var_dump($user);
$sql="SELECT * FROM $table_name_users WHERE username = \"$user\"";
var_dump($sql);
$result=#mysql_query($sql,$connection) or die("couldn't execute query");
$num=mysql_numrows($result);
if ($num != 0) {
/*$cookie_name="$user";
$cookie_value="ok";
$cookie_expire=time()+86400;
$cookie_domain=".columbia.edu";
setcookie($cookie_name, $cookie_value, $cookie_expire, "/", $cookie_domain, 0);
*/
print "<script>";
print "self.location='somethingelse.php';";
print "</script>";
} else {
echo "<p>you're not authorized";
}
?>
My dbconnection.php file is as follows:
<?php
$db_server = "localhost";
$db_name = "DailyExerciseDB";
$db_user = "abc5"; //the database username
//$db_password = "123"; // the database user pasword
$connection=#mysql_connect($db_server,$db_user) or die("Could Not Connect to the Database : ". mysql_error());
var_dump($connection);
$db=#mysql_select_db($db_name, $connection) or die("Could Not Select the Database". mysqli_connect_error());
//var_dump($db);
?>
My Questions:
1) I keep on getting Could Not Select the Database, why does the warning/error message corresponding to . mysqli_connect_error() doesn't get printed on the browser?
2) I have manually entered the user with username abc5 in the database and still it's not able to connect.Does anyone know why?
3) Even if I don't enter anything in the login.html and press login button, the following files gets executed, how can I take user entered into account while verifying with database? I believe since its hardcoded right now abc5, all files are getting executed.
4) var_dump($connection); prints resource(4, mysql link)
mysql_connect() has a third parameter which I'm not seeing you use: the password. Consider the following line:
mysql_connect($db_server, $db_username, $db_password);
Also, you should probably be using mysqli extension instead of the mysql extension (mysql is deprecated in PHP 5.5.0).
I also see you're mixing the mysql and mysqli functions in your code. This is the reason why mysqli_connect_error() shows nothing.

Login issue with mySQL no database selected

I'm a beginner of PHP coding which I face this problem and I tried to fix it.
I have search through stackoverflow for answers but it stills no good.
This is my Login form.php file
<form name = 'LoginForm' method = 'POST' action = 'verifyUser.php'>
<br />
E-MAIL: <input type = "Textbox" Name = "App_Email"><br><br>
PASSWORD: <input type = "password" Name = "App_Password"><br><br>
<input type = 'Submit' name = 'Login' value = 'Log in'><br><br>
</form>
This form will goes to verifyUser.php and these are codes
include ('DBconnect.php');
$username = $_POST['App_Email'];
$pass = $_POST['App_Password'];
if($username=='' || $pass=='') {
header("Location:login.php?id=Some fields are empty");
}
$result = mysql_query("SELECT * FROM applicant_acct ");
if(!$result) {
die("Query Failed: ". mysql_error());
} else {
$row = mysql_fetch_array($result);
if ($username==$row['App_Email']) {
if($username==$row['App_Email'] && $pass==$row['App_Password']) {
header("Location: index.html?id=$username");
} else {
header("Location:login.php?id=username or your password is incorrect. Please try again");
}
}
}
And final DBconnect.php
<?
$dbc = mysql_connect('localhost','root','root') OR die('Wrong Connection!!!!!!!');
mysql_select_db('onlinerecruitment') OR die ('Cannot connect to DB.');
?>
I really have no idea why it shows "Query Failed: No database selected"
I think the problem is in verifyUser.php but have no idea where.
And another thing, after I logged in how can I generate the text "Welcome - "Username"" and provide them the logout button?
Please help.
Thank you.
Generally you may want to research a graphical user interface such as XAMPP or MySQL workbench until you are more comfortable with Database systems.
Here it seems like most of the improvements can be made in you DBConnect.php file. You are beginning and I can appreciate that. Consider something along the following lines that incorporates additional the security of PDO:: static calls.
<?php
public function _dbconnect($hostpath, $database, $username, $password){
try {
$this->conn = new PDO("mysql:host = {$hostpath};
dbname - {$database};
charset = utf8",
$username,
$password);
} else { exit(); }
?>
If this particular code block doesn't help I would highly recommend that you continue by investigating PDO:: calls.
<?php
include ('DBconnect.php');
if(isset($_POST['Login'])){
$username = $_POST['App_Email'];
$pass = $_POST['App_Password'];
if(empty($username) || empty($pass) || ctype_space($username) || ctype_space($pass)){
header("Location:login.php?error=1");
} else {
$result = mysql_query("SELECT * FROM applicant_acct");
if(!$result) {
die("Query Failed: ". mysql_error());
} else {
$row = mysql_fetch_array($result);
if($username==$row['App_Email'] && $pass==$row['App_Password']) {
header("Location: index.php?id=$username");
} else {
header("Location:login.php?error=0");
}
}
?>
I have a lot to say about your code.
Use isset function . This function check if something was done.
Check your database details again. Maybe you wrote something
wrong (misclick or something)
Use $_GET['error'] to get errors. I set 1 = for empty characters and 0 for 0 match between database and inputs.
Use sessions for after login message. You can also use Session to handle your errors.
EDIT: I recommend you to start to learn MySQLi or PDO.

Isset function not working

I'm working on PHP at the moment.
I have a form seen below with a submit button.
I then created a function below also.
As you can see the first thing the function does is checked the submit button is pressed, but it goes into this if upon loading the page(i don't need to press the button), and it out puts the "Entry Submitted" p tag autmoatically, where it shouldn't even be entering the first if statement.
Any help appreciated,
<p>
<input type="submit" name="Submit" id="Submit" value="Submit" tabindex="100"/>
<br />`enter code here`
</p>
</form>
<?php
if (isset($_POST['Submit'])){
$conn_error = 'Could not connect.';
$mysql_host = 'localhost';
$mysql_user = 'auser';
$mysql_pass = 'auser';
$mysql_db = 'ourwebdb';
// Connect to database
if (!#mysql_connect($mysql_host, $mysql_user, $mysql_pass) || !#mysql_select_db($mysql_db)) {
die ($conn_error);
}else {
//echo 'Connected';
// Perform database insert
$name = $_POST["Name"];
$email = $_POST["email"];
$teamSupported = $_POST["radioGroup"];
$comment = $_POST["comment"];
$query = "INSERT INTO visitors (Name, Email,[Supported Team], Comment)
VALUES ('{$name}', '{$email}', '{$teamSupported}', '{$comment}')";
$result = mysql_query($query);
if ($result) {
// Success
$id = mysql_insert_id();
echo '<p> Entry Submitted</p>';
// Do something
} else {
die ("Database query failed. ". mysql_error());
}
}
}
mysql_close();
Change your 1st PHP line
if (isset($_POST['Submit'])){
to
if (isset($_POST['Submit']) && $_POST['Submit']=='Submit' ){
there is nothing wrong in your code (except cut out portion of form). so there is two possible scenario 1. you are refreshing browser url with re-submit 2. there are some onload javascript/jquery function which submit the page (form.submit()..)
Solution for 1. is easy just open the url in new tab. for scenario 2. you need to check Or submit your full code here

Php page with html form inside execute php code before form is completed

This might be a stupid problem but i'm new to this (this is a homework ^^) and i can't find a solution :)
i have a .php file with an html form plus some php code to execute a query and insert the values from the form in my DB. And it works, but every time the page is loaded the php code is executed and this insert in the DB a "blank" line, because obviously the form was not filled yet. This is the code
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="AlterVista - Editor HTML"/>
<title></title>
</head>
<body>
<form action="myPage.php" method="post">
ID: <input type="text" name="id" /> <br />
<input type="submit" name="Submit" value="Go" /> <br />
</form>
<?php
$user = "DB";
$password = "";
$host = "";
$database = "my_DB";
$connessione = mysql_connect($host, $user, $password);
#mysql_select_db($database, $connessione) or die( "Unable to select database");
$id = $_REQUEST['id'];
$query = "INSERT INTO myTable (ID) VALUES ('".$id."')";
mysql_close();
?>
</body>
</html>
Is there a way to execute the php code only once the "Go" button on the form is executed?
Try:
if(isset($_POST['Submit'])) {
$user = "DB";
$password = "";
$host = "";
$database = "my_DB";
$connessione = mysql_connect($host, $user, $password);
#mysql_select_db($database, $connessione) or die( "Unable to select database");
$id = $_REQUEST['id'];
$query = "INSERT INTO myTable (ID) VALUES ('".$id."')";
mysql_query($query, $connessione);
mysql_close();
}
PHP will work before the page is rendered. You need to set up a condition to stop the PHP you don't want running until you submit the form.
if(isset($_POST['myform'])) {
// process the form
}else{
// html for form goes here
}
Hope that helps.
Assuming the form points to the script itself, there are numerous options :) Among others:
This first example just checks if a form was posted. If a normal (GET) request is received, it will do nothing, because it will not fall into your if-clause
// your form here
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// your php code
}
And this example checks if a variable with the name 'Submit' has been posted, and if so, if it has the value 'Go' in it. It is a slightly stricter check, but in your current example behaviour is exactly the same (so you can pretty much choose which one you like most ;))
// your form here
if(array_key_exists('Submit', $_POST) && $_POST['Submit'] == 'Go') {
// your php code
}

Data not being inserted into database from form, what am i doing wrong?

I have the following 2 files and a database that is running in the background. When ever I submit the form. The data is not being inserted into the database. It connects to my database successfully but it does not insert:
update.html
<html>
<head><title>Test Page</title></head>
<body>
<h2>Data Collection</h2><p>
<form action="update.php" method="post">
<table>
<tr><td>id</td><td><input type="text" name="id" /></td></tr>
<tr><td>title</td><td><input type="text" name="title" /></td></tr>
<tr><td>name</td><td><input type="text" name="name" /></td></tr>
<tr><td>hello</td><td><input type="text" name="hello" /></td></tr>
<tr><td colspan="2" align="center"><input type="submit" /></td></tr>
</table>
</form>
</body>
</html>
update.php
<?php
$GLOBALS['title'];
$GLOBALS['id'];
$GLOBALS['name'];
$GLOBALS['hello'];
$hostname="localhost:3036";
$username="root";
$password="";
$con = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
// Check connection
if (mysql_error())
{
echo "Failed to connect to MySQL: " . mysql_error();
}
mysql_select_db('website');
$sql="INSERT INTO articles (id, title, name, hello)
VALUES('$id','$title','$name','$hello')";
mysql_close($con);
echo "test";
All help is appreciated.
You are not executing the query at all and as correctly stated in the comments, you weren't setting the variables correctly;
change your code to match:
$title = $_POST['title'];
$id = $_POST['id'];
$name = $_POST['name'];
$hello = $_POST['hello'];
$hostname="localhost:3036";
$username="root";
$password="";
$con = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
// Check connection
if (mysql_error())
{
echo "Failed to connect to MySQL: " . mysql_error();
}
mysql_select_db('website');
$sql="INSERT INTO articles (id, title, name, hello)
VALUES('$id','$title','$name','$hello')";
mysql_query ( $sql, $con);
mysql_close($con);
Please try this code:
Note: i just ignore your deprecated msqyl function
<?php
$hostname="localhost:3036";
$username="root";
$password="";
$title = $_POST['title'];
$id = $_POST['id'];
$name = $_POST['name'];
$hello = $_POST['hello'];
$con = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
// Check connection
if (mysql_error())
{
echo "Failed to connect to MySQL: " . mysql_error();
}
mysql_select_db('website');
$sql=mysql_query("INSERT INTO articles (id, title, name, hello)
VALUES('$id','$title','$name','$hello')") or die(mysql_error());
mysql_close($con);
echo "test";
First you are not defining the variables that are inserting. '$id','$title','$name','$hello'.
Define previous to insert, when the $_POST is accepted, use
else {$id'= $_POST['id'];}
Second. and more important, don't ever use this code which by the way is old, deprecated and very unhealthy. It's prone to SQL INJECTION.
Instead use PDO, and sanitize user submitted values.
Also avoid use of $GLOBALS, the same, old, deprecated, unsafe.
Please refer to PHP sanitize which explains how to clean your user submitted data. Check this:
$id=filter_var($_POST['id'], FILTER_SANITIZE_STRING);

Categories