Using user-supplied database credentials across multiple pages - php

I am learning to use MySQL with PHP and while practicing, I tried to create a simple web application using Core PHP and MySQL. It is summarized below:
-It has a pretty simple html page where username(uname) and password(pword) for MySQL are input in a form and are sent by POST method to a PHP script called PHP1.php
-PHP1 makes connection to MySQL. The code is(skipping PHP tags):
//Get input username and password
$username = $_POST['uname'];
$password = $_POST['pword'];
//Server information
$server = "localhost";
//Connect
$conn = new mysqli($server, $username, $password);
//Check success/failure
if ($conn -> connect_error)
{
die("Connection failed".$conn->connect_error);
}
After connecting, PHP1 retrieves information about the databases stored in the respective account and displays radio buttons to select the database and sends the name of the selected database by GET method to another script PHP2.php
-In PHP2.php I want to display the TABLES in the selected database.
However, when control is transferred to PHP2.php, connection to MySQL is terminated. I first tried to include my PHP1.php file in PHP2.php and use the $conn variable but ofcourse it'll try to reconnect to MySQL due to the above mentioned code and at the same time, the first request containing uname and pword is lost resulting in an authentication error.
How can I overcome this problem?
EDIT:
I have seen other questions here but all of them have fixed usernmae/passwords and so the connection script can be placed in a separate file easily. I require to take username and password from the user.

Use Sessions which will persist the session variables across pages:
PHP1
session_start();
$_SESSION['username'] = $username = $_POST['uname'];
$_SESSION['password'] = $password = $_POST['pword'];
$server = "localhost";
$conn = new mysqli($server, $username, $password);
PHP2
session_start();
$username = $_SESSION['username'];
$password = $_SESSION['password'];
$server = "localhost";
$conn = new mysqli($server, $username, $password);
In PHP1 you're going to want to check that the $_POST values are set and in other pages you'll want to check that the $_SESSION variables are set. See isset.

Related

Display clicks for each user

So I learn PHP, and I want to try to build something like a small monetized url shortener, just for fun! So every time somebody clicks on a users link, one click should be added in the MySQL table (for the user). I tried a lot of scripts but they all don't work.
<html lang="en-US">
<?php
$servername = "***";
$username = "***";
$password = "***";
$dbname = "***";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_query("UPDATE users SET 'hits' = 'hits'+1 WHERE id = 1");
?>
And after then display the clicks in the users dashboard via $row['']... but it doesn't count the clicks when I onload the page... the number in the mysql database does'nt change... what am I doing wrong. Alsom do you have and more professional idea how to do that, cause I know that this isn't a good alternative... I also have something like that , but it doesnt work too...
$user_ip=$_SERVER['REMOTE_ADDR'];
$check_ip = mysqli_query("select userip from pageview where page='1' and userip='$user_ip'");
if(mysqli_num_rows($check_ip)>=1)
{
}
else
{
mysqli_query("insert into pageview values('1','1','$user_ip')");
mysqli_query("update users set 'hits' = 'hits'+1 where id=1 ");
}
If you're used to mysql_query, you need to do this differently, a connection handle is required, no longer implicit. The best way to avoid slipping up on this is to use the object-oriented calling method:
$conn->query(...);
This approach is often substantially less verbose.

Prepared statements using MySQL not inserting POST values to database table

I'll be honest in saying I'm a rookie coder who knows the basics but is trying to learn more, this issue is also the reason I made an account as well as it's really stumped me. Lots of my code is temporary and I'm planning to streamline it later as well as adding features such as asterisks replacing the password input.
The desired outcome of my code is that the value of the variables below should be compared against those in my database table depending on the value of $type. The problem I'm encountering is that no entries are added to my database table. I'm unsure of where the problem lies within my code and I could do with a point in the right direction, this is my first application of prepared statements so I might be using them incorrectly
Main script:
<?php
include connect.db;
//These are normally user inputs from a form in another file.
$type = "students";
$username = "usernametest";
$password = "passwordtest";
$email = "emailtest";
//the connect global initilizes a connection between my database.
$query = $GLOBALS["conn"]->query("SELECT * FROM '$type' WHERE (username = '$username') OR (password = '$password') OR (email = '$email')");
if (mysqli_num_rows($query) == false) {
$stmt = $GLOBALS["conn"]->prepare("INSERT INTO ? (username, password, email) VALUES (?,?,?)");
$stmt->bind_param("ssss", $type, $username, $password, $email);
$stmt->execute();
$stmt->close();
echo "User Registered";
}
else {
echo "Username, password or email are already used";
}
?>
Connection Script:
<?php
//Identifies the databases details.
//Identifies the servername the database is created in
$servername = "localhost";
//Identifies the databases username
$username = "htmltes7";
//Identifies the database password
$password = "(mypassword)";
//Identified the afformentioned databasename
$dbname = "htmltes7_dbname";
/*Creates a new global variable which opens a connection between my database
using the variables above */
$GLOBALS["conn"] = new mysqli($servername, $username, $password, $dbname);
/*IF the connection cannot be made then the equilivent of exit() occours
in the form of die(). An error message is displayed containing information
on the error that occoured using mysqli_connect_error.*/
if (!$GLOBALS["conn"]) {
die("Connection failed: " . mysqli_connect_error());
}
?>
edit: Sorry about my poor formatting and incorrect tag usage first time round, like I said I'm new to both sql and stack overflow and kinda jumped the gun to ask my question. I've made changes based on the feedback and won't reproduce the same mistake in future.
Try to see the errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}

how to set mysql database connection name

I'm trying to figure out how can I put two differents MYSQL database connections name on the same page, one is for local PC and one is for hosting server.
Does is possible to have two different databases servers name on the same page so that way not to change connection database name in a script before upload.
I have code like this for local PC
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>
Can can i add another connection name in the server in same page without changing the connection database!
alidad
Yes, a single page may query as many different servers as needed:
<?php
$server1 = new mysqli("server1.example.com", "user1", "password1", "database1");
$server2 = new mysqli("server2.example.com", "user2", "password2", "database2");
$result = $server1->query("SELECT 'Hello user' AS _message FROM DUAL");
$row = $result->fetch_assoc();
echo htmlentities($row['_message']);
$result = $server2->query("SELECT 'Hello user' AS _message FROM DUAL");
$row = $result->fetch_assoc();
echo htmlentities($row['_message']);
The way is to have a config.ini file in your localhost, and a different one in your production environment. This way you will parse this file and get your credentials.
A better way to do that is using this library: https://github.com/vlucas/phpdotenv
It works basically on the same way, but is easy to maintain.

How to perform an inner join sql [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 6 years ago.
Improve this question
Attempting to try and join my table called 'UserCaseMessages' with my other table called 'Comments' using this exact sql command in php:
$sql = "
SELECT UserCaseMessages.DefendantID, Comments.CommentID
FROM UserCaseMessages
INNER JOIN Comments
ON UserCaseMessages.DefendantID = Comments.SenderID
";
$result = $conn->query($sql);
if ($result->num_rows > 0) // ERROR GETS THROWN ON THIS LINE {
}
Here is the connection part to my database (which occurs prior to the query):
$servername = "localhost";
$username = "username";
$password = "password";
// Get the username from the post
$userUsername = $_POST['string'];
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
I get the following error:
PHP Notice: Trying to get property of non-object
I cannot figure out what I am doing wrong here!! Everything is spelled correctly and a checked and checked for any syntax errors and I can't find any, however I am new to this particular method. Please help!
Since you haven't responded to my comments (some 20+ minutes prior to my submitting this), I am posting the following answer.
You didn't choose a database here:
$servername = "localhost";
$username = "username";
$password = "password";
$conn = new mysqli($servername, $username, $password);
so you need to add the database parameter:
$servername = "localhost";
$username = "username";
$password = "password";
$database = "your_DB";
$conn = new mysqli($servername, $username, $password, $database);
Read the manual on connecting with the MySQLi API:
http://php.net/manual/en/function.mysqli-connect.php
Check for errors on the query also:
http://php.net/manual/en/function.mysql-error.php
Plus, make sure the POST array does contain a value. Something in regards to the HTML form you didn't post.
The form's element must contain a matching name attribute:
name="string" and there must be a POST method for <form>.
method="post".
FYI: <form> is the equivalent to <form method="get"> as it defaults to a GET method if POST isn't implied.
Check for errors with error reporting also:
http://php.net/manual/en/function.error-reporting.php
Although, if your form does not have a POST method as I already mentioned, you won't get errors for it, strangely enough.
Sidenote about $userUsername.
That is ambiguous. If you are trying to run a query against that variable, you would need to use a WHERE clause.
I.e.: WHERE column = '$userUsername'

when changing database local to online page blank

I've recently made a new database that I had local. Everything worked fine and the scripts I've used (mysql and php codes) have been working properly. Since I've changed the database from local to online it has only caused problems with my script. Of course I've changed the details of connecting to MySQL database (having a password and such). Also, the content after the script won't work either.
Note: I haven't changed my script AT ALL. I've only changed the connection part.
$dbhost = "localhost";
$dbuser = "dbuser";
$dbpass = "dbpass";
$dbname = "compunll_itnj01";
$con = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$so = $con->prepare("SELECT * FROM besteloverzicht");
$so->execute();
--- rest of code
My apologies if I've forgotten to put anything further here. You can ask me and I'll respond asap!
Try to set the ip address of your db online
$dbhost = 'xx.xxx.xxx.xxx';

Categories