Ok, so I've successfully linked a Contact Form for my website to a MySQL database and I'm super stoked about figuring it out, however on my registration page my code isn't working. I ran this connection check:
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
echo "It's Working!";
}
and it says: "It's working!" So i know i've established a connection to my SQL database.
Let me try to clarify further:
I've got 2 main files for this particular program (obviously we won't be needing to care about styles.css or the linked files for other pages in my site): register.php and db.php. Here is my code for both. It's simply a project website so i don't care if people see/use my code... It's not working anyway so knock yourselves out, LOL!
First, db.php:
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'forms1');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
Now here's the php in register.php, which I've place at the top BEFORE any HTML at all:
include ("db.php");
$msg = "";
if(isset($_POST["submit"]))
{
$name = $_POST["name"];
$lname = $_POST["lname"];
$a1 = $_POST["a1"];
$a2 = $_POST["a2"];
$city = $_POST["city"];
$state = $_POST["state"];
$zip = $_POST["zip"];
$phone = $_POST["phone"];
$email = $_POST["email"];
$password = $_POST["password"];
$name = mysqli_real_escape_string($db, $name);
$lname = mysqli_real_escape_string($db, $lname);
$a1 = mysqli_real_escape_string($db, $a1);
$a2 = mysqli_real_escape_string($db, $a2);
$city = mysqli_real_escape_string($db, $city);
$state = mysqli_real_escape_string($db, $state);
$zip = mysqli_real_escape_string($db, $zip);
$phone = mysqli_real_escape_string($db, $phone);
$email = mysqli_real_escape_string($db, $email);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
$sql="SELECT email FROM users WHERE email='$email'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
$msg = "Sorry...This email already exist...";
}
else
{
$query = mysqli_query($db, "INSERT INTO users(name,lname,a1, a2, city, state, zip, phone, email, password) VALUES ('$name', '$lname', '$a1', '$a2', '$city', '$state', '$zip', '$phone', '$email', '$password')");
if($query)
{
$msg = "Thank You! you are now registered.";
}
}
}
mysqli_close($db);
I should probably mention that JavaScript is included in the HEAD section of my HTML:
(function(H){H.className=H.className.replace(/\bno-js\b/,'js')})(document.documentElement)
$(document).ready(function() {
$('form.required-form').simpleValidate({
errorElement: 'em',
ajaxRequest: true,
completeCallback: function($el) {
var formData = $el.serialize();
}
});
});
$("form[name='form1']").submit(function(){
.... JS code ....
return error;
});
</script>
<script type= "text/javascript">
var RecaptchaOptions = {
theme: 'clean'
};
Well, I tried to include the HTML code for the form but it wasn't appearing properly, but believe me when i tell you that ALL the inputs of the the form fields have a name="" that corresponds to the fields within my table within my database within MySQL. The HTML is most certainly not the problem. I've check syntax and spelling over and over. It's not the HTML. Somewhere there is an error, though.
PLEASE HELP!!!
Thank you all very much.
-Maj
P.S. I purposely deleted the opening and closing php/html tags here in these examples so it'd be easier to read, but i have them placed in my original code.
After that if($query){ } block try adding else { print(mysqli_error($db)); }
perhaps there's an error, but what is the response you got from register.php?
you should start to debug your source code, but if you don't use a debugger, put some "die(SOME VARIABLE);" to locate your trouble area and without javascript, for the first. Just use some simple html-formular and to get row datas, put the answer into <PRE> tags ( or use curl in a terminal, i like this way, but for you it is not necessary ).
If you don't debug your php-code or you your browser-relevant-code, means "html, css, javascript, ..." (you can see with firebug, what data you are sending and what is coming back), you can use echo "INSERT .... BLA ...$VAR ...;" and copy-paste the SQL-Statement and testing it in PhpMyAdmin, to see you get a proper statement, maybe there is a type-converting-problem or many other thinks are possible.
If everything is going well, it is probably some trouble in your javascript-code. But probably you need to convert a type of some variable, you should copy and paste your SQL-Statement and execute it in phpmyadmin to make a verification of your SQL-Statements which you put in your Php-Code. Cheers.
Related
I am trying to achieve two things:
(1) Get text from a contenteditable div, use javascript to send that text to php, use php to send that data to a MySQL database and save it
(2) retrieve the saved data/text and reinsert it into a contentedtiable div
All of this whilst NOT using jQuery
What I've got so far:
index.html
<body>
<div contenteditable="true" id="editable"></div>
<button onClick="send_data();">Save text</button>
<button onClick="retrieve_data();">Get text</button>
</body>
javascript.js
function send_data() {
var php_file = "connection.php";
var http_connection = new XMLHttpRequest();
http_connection.open("POST", php_file, true);
http_connection.onreadystatechange = function() {
if(http_connection.readyState == 4 && http_connection.status == 200) {
alert(http_connection.responseText);
}
}
http_connection.send(document.getElementById('editable').innerText);
}
function retrieve_data() {
// I do not know what to put here
}
connection.php
<?php
$servername = "localhost";
$username = "mysql_user";
$password = "secure_password";
$dbname = "some_database";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
if(!conn) {
echo 'No connection';
}
if(!mysqli_select_db($conn,'some_database')) {
echo "No database";
}
$some_val = $_GET['text']
$sql = "SELECT text FROM some_database";
$result = $conn->query($sql);
echo $result;
$conn->close();
?>
Edit: what my code fails to do is to upload text as well as recieve text.
Some problems in the js:
http_c is not defined
readyState is spelled incorrectly
the send method needs to be outside the onreadystatechange callback
Once those things are corrected, program should give different, which is not to say expected, result.
Other things:
The js is sending a 'POST' request. The php is looking for $_GET["text"] which will give undefined error. I'm speculation this $sql = "SELECT text FROM some_database"; will fail (if it reaches that line) unless there is a table in the database named "some_database".
Suggest, for starters, get the ajax working by short-circuiting the code in connection.php to something like
echo "You are here";
exit;
Then gradually working forward between the js and the php until programs give you what you want.
I’m really struggling with this task for my course and hope someone doesn’t mind helping out or just offering guidance here. Basically I’m trying to create a simple Javascript XML Http Request to display basic information (the country_name & country_capital fields) from the database just in the html page. Below I just describe the apparent stages from the guide, and what I have done.
Firstly the ‘database.html’ page contains javascript XHR code which I think is mostly correct, but may have an error. To be honest I’m not 100% sure what else it does other than somehow refer to the getcountries.php file.
Secondly the getcountries.php file is where I’m really struggling as I’ve never coded in PHP. I think it’s supposed to fetch the data from the local server (I’m running XAMPP) and echo the results on the web page.
The database on phpMyAdmin is simple with just a table of countries including a primary key ID number, the country name, capital and currency, with the details below:
Database name = countries_db
Table name = countries_table
Table fields:
country_ID (primary key)
country_name
country_capital
country_currency
An example entry: 2, USA, Washington DC, US Dollar
To summarise, my question is this: how can I edit what I’ve done to correctly fetch the data from the database and display it on the page?
Really appreciate any help or advice here, thanks a lot.
<!-- Code on Page 1 (database.html) -->
<p id="txtHint"></p>
<p id="hint"></p>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) { // detects whether the browser has XMLHttpRequest functionality
// code for modern browsers
xmlhttp=new XMLHttpRequest(); // creates an XMLHttpRequest object
} else { // code for old browsers
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() { // onreadystatechange defines the function to be called when the readyState property changes
if (this.readyState==4 && this.status==200) {
document.getElementById("hint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getcountries.php?q="+str,true);
xmlhttp.send();
}
</script>
<!-- Code on Page 2 (getcountries.php) -->
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','');
if (!$con) {
die('Could not connect: ' .mysqli_error($con));
}
mysqli_select-db($con,"countries_db");
$sql="SELECT country_name AND country_capital FROM records";
$result = mysqli_query($con,$sql);
echo "Results:"
error_reporting(E_ERROR | E_PARSE);
\
while($row = mysqli_fetch_array($result)) {
echo $row['country_name'] . "<br>";
echo $row['country_capital'] . "<br>";
}
mysqli_close($con);
?>
Assuming that this is the structure of your data base:
Database name = countries_db
Table name = countries_table
Table fields:
country_ID (primary key)
country_name
country_capital
country_currency
The problem is that you have some syntax error in your code change this lines:
mysqli_select-db($con,"countries_db");
$sql="SELECT country_name AND country_capital FROM records";
with:
mysqli_select_db($con,"countries_db");
$sql="SELECT country_name, country_capital FROM countries_table";
Alternative: using PDO:
Try this instead of your getcountries.php implementation
<?php
$driver = 'mysql';
$database = "dbname=countries_db";
$dsn = "$driver:host=localhost;unix_socket=/home/cg/mysql/mysql.sock;$database";
$username = 'root';
$password = 'root';
try {
$conn = new PDO($dsn, $username, $password);
echo "<h2>Database countries_db Connected<h2>";
}catch(PDOException $e){
echo "<h1>" . $e->getMessage() . "</h1>";
}
$sql = 'SELECT country_name, country_capital FROM countries_table';
$stmt = $conn->prepare($sql);
$stmt->execute();
echo "Results:";
echo "<table style='width:100%'>";
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "<tr>";
foreach($row as $value)
{
echo sprintf("<td>%s</td>", $value);
}
echo "</tr>";
}
echo "</table>";
?>
Use mysqli_select_db instead of mysqli_select-db in your getcountries.php:
mysqli_select_db($con,"countries_db");
I have a PHP file getting data from my SQL database and I am trying to set and get two session variables like $_SESSION['fname'] and $_SESSION['userID'] by $theFName and $theId.
$email = $_POST['email'];
$pass = $_POST['pass'];
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DATABASE);
$sql = "SELECT id, email, fname, lname, type FROM users WHERE `email`=? AND `pass`=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ss', $email,$pass);
$stmt->execute();
$stmt->bind_result($theId,$theEmail,$theFName,$theLname,$theType);
if ($stmt->fetch()) {
echo 'true';
$_SESSION['LOGIN_STATUS'] = true;
$_SESSION['fname'] = $theFName;
$_SESSION['userID'] = $theId;
} else {
echo 'false';
}
in JavaScript file I have
<script>
var tok = "var UID = "<?php echo $_SESSION['userID']; ?>";
console.log("The Id is " + UID)
</script>
but I am getting empty string!
can you please let me know what I am doing wrong?
I'm not quite sure I understand what you are trying to do in the JS file, but it is not valid JS in any case - the quotes don't match and it seems like you are trying to do an assignment inside a string.
I think what you are looking for is something more along the lines of this:
<script>
var UID = "<?php echo $_SESSION['userID']; ?>";
console.log("The Id is " + UID)
</script>
However, please note that dynamically generating JS files using PHP is likely not the best way to go about this. Check out this SO answer on the various methods you can use to pass variables from PHP to JS, along with their various pros and cons.
I found and fixed a little bit I am not so good with PHP but any improvements are welcome.
The problem is that sometimes in Chrome and Opera but only sometimes after login sucess the script redirect to a welcome page with javascript redirection after 5 secs. But sometimes it just get stuck and does not redirect but just show a white page without error and other times it redirect and worls fine. What can it be?
Here is the code
<?php session_start();?>
<?php
include 'inc/connection.php';
$db=mysqli_connect($dbserver, $dbuser, $dbpass, $dbname)or die("DB connection error...");
$username_to_sanitize = $_POST['username'];
$password_to_sanitize = $_POST['password'];
$sanitized_username = mysqli_real_escape_string($db, $username_to_sanitize);
$sanitized_password = mysqli_real_escape_string($db, $password_to_sanitize);
$query = "SELECT password, salt, privilege, username FROM members WHERE username = '$sanitize_username'";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) == 0) // User not found. Redirected to login page.
{header('Location:login.php?message=Username not found, please try again');}
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $sanitized_password) );
if($hash != $userData['password']) // Incorrect passw. Redirected to login page.
{header('Location:error.php?message=Wrong password, please try again');}
else if($userData['privilege']=="ADMIN"){session_start();
$_SESSION['username']=$userData['username'];
header('Location:redirection.php?URL=admins/index.php');}
else if($userData['privilege']=="MODERATOR"){session_start();
$_SESSION['username']=$userData['username'];
header('Location:redirection.php?URL=moderators/index.php');}
else if($userData['privilege']=="MEMBER"){session_start();
$_SESSION['username']=$userData['username'];
header('Location:redirection.php?URL=members/index.php');}
else if($userData['privilegio']=="BANNED"){session_start();
$_SESSION['username']=$userData['username'];
header('Location:redirection.php?URL=banned/index.php');}
else{
header('Location:error.php?message=su need privileges to acces this site');
exit();
}
?>
After reading and testing new scripts found on internet I still cannot fix this problem after 2 months. Any idea?
You have a lot of duplication in your code, which is bad because each place that you duplicate means that you need to change it when you update the code, which means that there are more places for bugs to pop up later.
To help, I placed in only one session_start(), and I converted the if/elseif/elseif/elseif... to a switch statement.
Instead of dealing with the location headers themselves, I've replaced those with the http_redirect function, which basically does it for you. To boot, it encodes the URLs for you so you don't have to worry about that.
If you keep seeing a blank page, then you should check the webserver's logs (apache or nginx or php-fpm, or whatever) to see if the errors are there. Otherwise, turn on better error reporting; quite often blank pages are just errors that haven't been reported.
<?php
session_start();
include 'inc/connection.php';
$db = mysqli_connect($dbserver, $dbuser, $dbpass, $dbname) or die('DB connection error...');
$sanitized_username = mysqli_real_escape_string($db, $_POST['username']);
$sanitized_password = mysqli_real_escape_string($db, $_POST['password']);
$query = "SELECT password, salt, privilege, username FROM members WHERE username = '$sanitized_username'";
$result = mysqli_query($db, $query);
if (mysqli_num_rows($result) == 0) {
// User not found. Redirected to login page.
http_redirect('login.php', array('message' => 'Username not found, please try again'), true);
}
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $sanitized_password) );
if($hash != $userData['password']) {
// Incorrect passw. Redirected to login page.
http_redirect('error.php', array('message' => 'Wrong password, please try again'), true);
}
// Just set the username once
$_SESSION['username'] = $userData['username'];
switch ( $userData['privilege'] ) :
case 'ADMIN':
http_redirect('redirection.php', array('URL' => 'admins/index.php'), true);
break;
case 'MODERATOR' :
http_redirect('redirection.php', array('URL' => 'moderators/index.php'), true);
break;
case 'MEMBER' :
http_redirect('redirection.php', array('URL' => 'members/index.php'), true);
break;
case 'BANNED' :
http_redirect('redirection.php', array('URL' => 'banned/index.php'), true);
break;
default:
// The message is weird. Should it be:
// 'You need privileges to access this site' or something like that?
http_redirect('error.php', array('message' => 'su need privileges to acces this site'), true);
break;
endswitch;
http_redirect('error.php', array('message' => 'su need privileges to acces this site'), true);
?>
I asked a similar question earlier, but think I got the wrong point across and learned more about security than fixing the problem I'm having. I am having trouble with my ajax request to post data into a php script and then submit it to a database.
Just to make it clear, the site is local and I will have nobody creating an account besides me and I will be the only one accessing it. I will make it secure once I get this step finished.
Current error I am getting: none, but no data after the success in alert("success" + data)
I have googled/worked for 10+ hours just on this... Any help would be greatly appreciated as I am just learning.
Here is my Javascript:
var firstname = String($("#firstname").val());
var lastname = String($("#lastname").val());
var username = String($("#username").val());
var email = String($("#email").val());
var password = String($("#password").val());
Here is the AJAX:
$.ajax({
type: 'POST',
url: 'create_account.php',
data: {firstname_php: firstname,
lastname_php: lastname,
username_php: username,
email_php: email,
password_php: password},
success: function(data) {
alert("success" + data);
}
});
create_account.php:
$firstname = $_POST['firstname_php'];
$lastname = $_POST['lastname_php'];
$username = $_POST['username_php'];
$email = $_POST['email_php'];
$password = $_POST['password_php'];
echo "$firstname";
// Create connection
$connection = mysqli_connect("localhost","root","root","MyDatabase");
// Check connection
if (mysql_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO users (user_id, user_firstname, user_lastname, user_username, user_email, user_password) VALUES (0, '$firstname', '$lastname', '$username', '$email', '$password)'";
$result = mysqli_query($connection,$sql);
mysqli_close($connection);
You have a single quote in the wrong place in your query:
VALUES (0, '$firstname', '$lastname', '$username', '$email', '$password)'";
^^^
try this:
VALUES (0, '$firstname', '$lastname', '$username', '$email', '$password')";
Everything looks fine in the javascript and ajax (at least as well as I can tell without seeing the html source as well.
However you have at least one php error; mysql_connect_errno doesn't exist and wouldn't be called in relation to the mysqli connector.
so try this instead:
$firstname = $_POST['firstname_php'];
$lastname = $_POST['lastname_php'];
$username = $_POST['username_php'];
$email = $_POST['email_php'];
$password = $_POST['password_php'];
echo "$firstname";
// Create connection
$connection = mysqli_connect("localhost","root","root","MyDatabase");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO users (user_id, user_firstname, user_lastname, user_username, user_email, user_password) VALUES (0, '$firstname', '$lastname', '$username', '$email', '$password')";
$result = mysqli_query($connection,$sql);
mysqli_close($connection);
I haven't used the mysqli connector but other than that it looks fine to me. If it still doesn't work I suggest enabling full php debug info - for example adding this to the top of the php file:
ini_set("display_errors", "1");
error_reporting(E_ALL);
EDIT: as hanlet stated you also have a single quote/apos in the wrong spot. (fixed in my example code)