I use this code to connect to a database:
#mysql_connect("localhost","root","") or die(mysql_error());
#mysql_select_db("ECOLE") or die (mysql_error());
#mysql_set_charset('utf8');
if(isset($_POST['profname_in'])){
$querycheck = "SELECT prof_som FROM prof_table
WHERE prof_som=$_POST[profsom_in];";
$_querycheck=mysql_fetch_array(mysql_query($querycheck));
if(isset($_querycheck['prof_som'])){
echo "0";
}else{
$query="INSERT INTO prof_table
VALUES('$_POST[profname_in]',
'$_POST[profcin_in]',
'$_POST[profsom_in]',
'$_POST[profville_in]',
'$_POST[profecole_in]',
'$_POST[profmat_in]',
'$_POST[profpass_in]');";
if(mysql_query($query)){
echo "1";
}
}
}
the echos is recupered by a javascript function (ajax):
function adding_prof_Reply() {
if(http.readyState == 4){
var response = http.responseText;
if(response==0){
document.getElementById('prof_validation').innerHTML = '<font color="red">'+response+'</font>';
}else if (response==1){
document.location.href="dir_paneau.php";
}else{
document.getElementById('prof_validation').innerHTML = '<font color="red">'+response+'</font>';
}
}
}
everything works good, the problem is when I use require('anyfile') in the php code then the test if(response==0) is always false even when respose==0 ; if I remove the line of require everything works as it should.
I need the require to not repeat the connection information, any ideas?
"i need the require to not repeat the connection information"
To only connect once, put the 'connection information' in a separate file, maybe dbConnect.php and use the function require_once('dbConnect.php') in the files which need a database connection.
This ensures you only connect to your database once, which may solve your problem.
Related
I can't change the state of a value with a href.
I have tried in all ways. Here is my code
Giallo
giallo.php=
<?php
// Create connection
$conn = new mysqli('localhost','root','','agenda');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$id = $_GET['id'];
$qry = mysqli_query($db,"select * from note where id='$id'"); // select query
// when click on Update button
if(isset($_POST['update'])) {
$colore=1;
$edit = mysqli_query($db,"update note set colore='$colore' where id='$id'");
if($edit) {
mysqli_close($db); // Close connection
header("location:udienze.php"); // redirects to all records page
exit;
} else {
echo mysqli_error();
}
}
if (mysqli_query($conn, $sql)) {
echo "<script>
alert('Nota inserita correttamente');
window.location.href='add-udienze.php';
</script>";
} else {
echo "<script>
alert('Errore');
window.location.href='add-udienze.php';
</script>";
}
mysqli_close($conn);
?>
What is wrong with my code? There are probably cleaner ways to do it. I have tried all ways that I know.
I think the problem is that you are calling the giallo.php script with multiple kind of params (POST and GET).
So when you click on the link, the "href" attribute redirects to giallo.php, but nothing happen because it miss the $_POST['update'] action.
Probably the solution fit your case can be edit the href attribute, adding a GET parameter for "update", like:
Giallo
And then edit the giallo.php file and consider the new $_GET["update"] and not the POST one.
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.
Developing a very simple UPDATE query page for users to change their account password, but have run into a bit of a brick wall with establishing the MySQLi connection (or so it would seem). I'm new to this line of programming and this is my first attempt to perform a dynamic query, so hopefully it's something that one of you can spot easily enough and you'd so kind as to offer some much-needed sage advice.
Here's the page in question: http://www.parochialathleticleague.org/accounts.html
Upon executing the form's PHP script, I was at first receiving nothing but a blank white screen. I scoured through my code and did everything I could think of to diagnose the problem. After eventually adding an "OR die" function to the require command, I am now greeted with this message:
Warning: require(1) [function.require]: failed to open stream: No such file or directory > in /home/pal/public_html/accounts.php on line 10
Fatal error: require() [function.require]: Failed opening required '1'
(include_path='.:/usr/local/php52/pear') in
/home/pal/public_html/accounts.php on line 10
I'm pretty stumped. Here's the script code:
<?php
// Show errors:
ini_set('display_errors', 1);
// Adjust error reporting:
error_reporting(E_ALL);
// Connect to the database:
require ('../mysqli_connect.php') OR die('Error : ' . mysql_error());
// Validate the school:
if (empty($_POST['school'])) {
echo "You forgot to enter your school.<br>";
$validate = 'false';
} else {
$school = mysqli_real_escape_string($db, trim($_POST['school']));
$validate = 'true';
}
// Validate the existing password:
if (empty($_POST['pass'])) {
echo "You forgot to enter your existing password.<br>";
$validate = 'false';
} else {
$pass = mysqli_real_escape_string($db, trim($_POST['pass']));
$validate = 'true';
}
// Validate the new password:
if (empty($_POST['new_pass'])) {
echo "You forgot to enter your new password.<br>";
$validate = 'false';
} elseif (empty($_POST['confirm_pass'])) {
echo "You forgot to confirm your new password.<br>";
$validate = 'false';
} elseif ($_POST['new_pass'] != $_POST['confirm_pass']) {
echo "Sorry, your new password was typed incorrectly.<br>";
$validate = 'false';
} else {
$new_pass = mysqli_real_escape_string($db, trim($_POST['new_pass']));
$validate = 'true';
}
// If all conditions are met, process the form:
if ($validate != 'false') {
// Validate the school/password combination from the database:
$q = "SELECT school_id FROM user_schools WHERE (school_name='$school' AND pass=SHA1('$pass') )";
$r = #mysqli_query($db, $q);
$num = #mysqli_num_rows($r);
if ($num == 1) {
// Get the school_id:
$row = mysqli_fetch_array($r, MYSQLI_NUM);
// Perform an UPDATE query to modify the password:
$q = "UPDATE user_schools SET pass=SHA1('$new_pass') WHERE school_id=$row[0]";
$r = #mysqli_query($db, $q);
if (mysqli_affected_rows($db) == 1) {
header("Location: confirm_accounts.html");
} else {
echo "Your password could not be changed due to a system error. Apologies for the inconvenience. If this problem continues, please contact us directly.";
}
}
}
mysqli_close($db);
exit();
?>
Lastly, here's the code from the connection script that it's requiring (with omitted account values, of course):
<?php
// Set the database access information as constants:
DEFINE ('DB_USER', '***');
DEFINE ('DB_PASSWORD', '***');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', '***');
// Make the connection:
$db = #mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' .mysqli_connect_error() );
// Set the encoding:
mysqli_set_charset($db, 'utf8');
I've been trying for the last couple of hours to troubleshoot this problem on my own. Google couldn't solve it. Looking through archives here couldn't solve it.
Here's what I do know for sure:
The script that it's requiring, mysqli_connect.php, does work on its own. I've tested it extensively to make sure that all of the log-in info is correct.
The script is also definitely in the parent directory that I've requested it from. I've tried moving it to the public directory and calling it from there. Same error message. Tried typing the entire file path. Same message.
Also, most of the script works fine on its own. When I omitted all of the MySQL lines and just left the basic validation code, it ran without a problem and sent me to the confirmation page as requested. It definitely seems to be a problem with making the connection.
Not sure where to go from here. Any assistance would be GREATLY appreciated! Many thanks in advance.
EDIT: #YourCommonSense - Here's the modified script, as per your suggestions. Still getting the blank screen. Am I following your advice incorrectly?
<?php
// Show errors:
ini_set('display_errors', 1);
// Adjust error reporting:
error_reporting(E_ALL);
// Connect to the database:
require ('../mysqli_connect.php');
// Validate the school:
if (empty($_POST['school'])) {
echo "You forgot to enter your school.<br>";
$validate = 'false';
} else {
$school = mysqli_real_escape_string($db, trim($_POST['school']));
$validate = 'true';
}
// Validate the existing password:
if (empty($_POST['pass'])) {
echo "You forgot to enter your existing password.<br>";
$validate = 'false';
} else {
$pass = mysqli_real_escape_string($db, trim($_POST['pass']));
$validate = 'true';
}
// Validate the new password:
if (empty($_POST['new_pass'])) {
echo "You forgot to enter your new password.<br>";
$validate = 'false';
} elseif (empty($_POST['confirm_pass'])) {
echo "You forgot to confirm your new password.<br>";
$validate = 'false';
} elseif ($_POST['new_pass'] != $_POST['confirm_pass']) {
echo "Sorry, your new password was typed incorrectly.<br>";
$validate = 'false';
} else {
$new_pass = mysqli_real_escape_string($db, trim($_POST['new_pass']));
$validate = 'true';
}
// If all conditions are met, process the form:
if ($validate != 'false') {
// Validate the school/password combination from the database:
$q = "SELECT school_id FROM user_schools WHERE (school_name='$school' AND pass=SHA1('$pass') )";
$r = mysqli_query($db, $q);
if (!$r) {
throw new Exception($mysqli->error." [$query]");
}
$num = mysqli_num_rows($r);
if ($num == 1) {
// Get the school_id:
$row = mysqli_fetch_array($r, MYSQLI_NUM);
// Perform an UPDATE query to modify the password:
$q = "UPDATE user_schools SET pass=SHA1('$new_pass') WHERE school_id=$row[0]";
$r = mysqli_query($db, $q);
if (!$r) {
throw new Exception($mysqli->error." [$query]");
}
if (mysqli_affected_rows($db) == 1) {
header("Location: confirm_accounts.html");
} else {
echo "Your password could not be changed due to a system error. Apologies for the inconvenience. If this problem continues, please contact us directly.";
}
}
}
mysqli_close($db);
exit();
?>
Two BIGGEST problems with your code and your "solution":
You have # operator all over the place. For which you have -1 vote to your question. # operator is the evil itself. IT is responsible for the blank page you see.
However, the remedy you choose made the things worse. This "OR die" thing is not a magic chant to solve any error reporting problem. And used improperly will cause errors like one you have. For which you have 1 in the error message.
First of all, your include is all right, so, leave it alone.
While to get an error from mysqli, follow these instructions:
Instead of adding "or die" randomly, you need more robust and helpful error reporting solution.
If you are using mysqli_query() all over the application code without encapsulating it into some helper class, trigger_error() is a good way to raise a PHP error, as it will tell you also the file and the line number where error occurred
$res = mysqli_query($mysqli,$query) or trigger_error(mysqli_error($mysqli)."[$query]");
in all your scripts
and since then you will be notified of the reason, why the object weren't created.
(If you're curious of this or syntax, I've explained it here - it also explains why you have (1) in the error message)
However, if you're encapsulating your query into some class, file and line from trigger error will be quite useless as they will point to the call itself, not the application code that caused certain problem. So, when running mysqli commands encapsulated, another way have to be used:
$result = $mysqli->query($sql);
if (!$result) {
throw new Exception($mysqli->error." [$query]");
}
as Exception will provide you with a stack trace, which will lead you the the place from which an erroneous query were called.
Note that you have to be able to see PHP errors in general. On a live site you have to peek into error logs, so, settings have to be
error_reporting(E_ALL);
ini_set('display_errors',0);
ini_set('log_errors',1);
while on a local development server it's all right to make errors on screen:
error_reporting(E_ALL);
ini_set('display_errors',1);
and of course you should never ever use error suppression operator (#) in front of your statements.
i have this simple php code. Locally, with a simple xampp 1.7.3 the echo returns correctly "false" or "true". When i put the code online (on a server, i mean, and i do not have really knowdledge of how the server is made) it returns always "1". Why?
<?php
include "connectionToDb.php";
$nome_utente=$_GET['nome_utente'];
$queryUserAvailable = "SELECT * FROM utente where nome_utente='$nome_utente'";
$rsUserAvailable = connetti($queryUserAvailable);
if(mysql_num_rows($rsUserAvailable) == 0){
$valid=true;
}
else{
$valid=false;
}
echo json_encode($valid);
?>
ConnectionToDb.php
<?php
function connetti($SQL){
$conn = mysql_connect("localhost", "root", ""); //(online this data are obviously different)
$db = mysql_select_db("dbName",$conn);
$risultato = mysql_query($SQL,$conn)
or die("Query non valida: " . mysql_error());
return ($risultato);
}
?>
As it seems from the comments, JSON is not included in the server's PHP configuration.
You might want to consult your host and check whether you can include this by just overriding settings via a .htaccess directive
Maybe you can also first try:
if (!extension_loaded('json')) {
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
dl('json.dll');
} else {
dl('json.so');
}
}
I currently have a PHP file which will search my MySQL database and see if a user is logged in. If they are logged in, it will echo "Welcome 'username'. Logout" and if they're not logged in it will echo "Login. Register."
If I view this PHP file directly, it will echo out the correct text, depending on whether or not I am logged in. However, if I put into my HTML file using include it will only echo out the logged out text, regardless of whether I'm logged in.
Is there some conflict between PHP and HTML which will stop it from printing out the correct text maybe? It seems strange that it will work opening the PHP file itself, but not when it's included in HTML.
HTML code:
<?php include "loginreg/check.php"; ?>
Would the fact it's in a subfolder make a difference? Haven't included the PHP code as that itself is working, but I have got it if you need to see it.
Cheers
PHP code:
// Gets IP address
$ip = visitorIP();
// Connect to database
mysql_connect(localhost, $username, $password);
#mysql_select_db($database) or die('Unable to select database');
$query = "SELECT * FROM loggedin WHERE userip='$ip'";
$result = mysql_num_rows(mysql_query($query));
if ($result == '0') {
mysql_close();
loggedOut();
return;
}
if (isset($_COOKIE['sid'])) {
$sessionid = $_COOKIE['sid'];
}
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
if ($row['sessionid'] == $sessionid) {
mysql_close();
loggedIn($row['id']);
} else {
mysql_close();
loggedOut();
}
}
function visitorIP() {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$TheIp = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$TheIp = $_SERVER['REMOTE_ADDR'];
}
return trim($TheIp);
}
function loggedIn($id) {
global $username, $password, $database;
mysql_connect(localhost, $username, $password);
#mysql_select_db($database) or die('Unable to select database');
$query = "SELECT * FROM users WHERE id='$id'";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
$fname = $row['fname'];
$sname = $row['sname'];
}
echo "<div class=\"fltrt\">Welcome, " . $fname . ". Logout</div>";
}
function loggedOut() {
echo "<div class=\"fltrt\">Login Register</div>";
}
Without seeing the code of both scripts this is just a guess, but a likely problem would be that you are outputting html (anything...) before you include your loginreg/check.php script.
That would render any session_start() statements in your included file useless as the headers already have been sent. And not being able to get to the session would lead to the error that you describe.
Edit: For cookies the same principle applies, they need to be set before the headers are sent so before you output anything to the browser.
Your issue is that you are setting cookies while inside a subdirectory. Use the path parameter of setcookie to ensure you're setting the cookie in the root folder of your website:
// Sets the cookie for the root of the domain:
setcookie("username", "foo", time() + 60 * 60, "/");
Correct me if I'm wrong here, but are you trying to use a PHP include in an HTML file? If so, that will never work (unless you've got some custom server config that will parse PHP code in HTML files).
PHP code is for PHP files. HTML code can work in HTML and PHP files. You cannot do a PHP include, in an HTML file.