I'm setting up the wholly organized sign up form, I'm trying to sent into information into my MySQL database server. My code not work and can't figuring out pops up message You have been signed up!
I've tried several options but none of them work on a server,
<?php
if (array_key_exists('email', $_POST) or array_key_exists('password', $_POST)) {
// So I'm guessing here need to some additions of based my own inclinatios.
my code
<?php
if (array_key_exists('email', $_POST) or array_key_exists('password', $_POST)) {
$link = mysqli_connect("localhost", "id8955440_bigebro", "sunshine1987**", "id8955440_bigebro");
if (mysqli_connect_error()) {
die("There was an error connecting to the database");
}
if ($_POST['email'] == '') {
echo "<p>Email address is required.</p>";
} else if ($_POST['password'] == '') {
echo "<p>Password is required.</p>";
} else {
$query = "SELECT `id` FROM `bigebro` WHERE email = '" . mysqli_real_escape_string($link, $_POST['email']) . "'";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
echo "<p>That email address has already been taken.</p>";
} else {
$query = "INSERT INTO `bigebro` (`email`, `password`) VALUES ('" . mysqli_real_escape_string($link, $_POST['email']) . "', '" . mysqli_real_escape_string($link, $_POST['password']) . "')";
if (mysqli_query($link, $query)) {
echo "<p>You have been signed up!";
} else {
echo "<p>There was a problem signing you up - please try again later.</p>";
}
}
}
}
?>
HTML
<form method="post">
<input name="email" type="text" placeholder="Email address">
<input name="password" type="password" placeholder="Password">
<input type="submit" value="Sign up">
</form>
$link = mysqli_connect("localhost", "id8955440_bigebro", "sunshine1987**", "id8955440_bigebro");
When I signed up form only pops up "There was a problem signing you up - please try again later" I want to expect to "you have been signed up" from the result
. please see sign up form
Use mysqli_error to track error in query.
$query = "INSERT INTO `bigebro` (`email`, `password`) VALUES ('" . mysqli_real_escape_string($link, $_POST['email']) . "', '" . mysqli_real_escape_string($link, $_POST['password']) . "')";
if (mysqli_query($link, $query)) {
echo "<p>You have been signed up!";
} else {
echo "Error: " . mysqli_error($conn);
}
Also check your db stucture like id should be auto incremented, email and password should be varchar.
you should validate email and password with javascript.
put an echo statement below the line
$query = "INSERT INTO `bigebro` (`email`, `password`) VALUES ('" . mysqli_real_escape_string($link, $_POST['email']) . "', '" . mysqli_real_escape_string($link, $_POST['password']) . "')";
echo $query;
if (mysqli_query($link, $query)) {
echo "<p>You have been signed up!";
} else {
echo "<p>There was a problem signing you up - please try again later.</p>";
}
Run the printed query with the same database credentials. If it runs then the problem is with ur PHP code. u should have INSERT privileges for your database user.
Related
I have something like this on my website. and I want to calculate the whole points of Sofia and show her the total balance. which is 163. but I am not getting how to add and then show her balance on my website. sorry, if it is too easy question. I am new to php.
here is the code
<form method="POST">
user name : <input type="text" name="username"><br>
Points to Add: <input type="number" name="blance" max="100"
min="1">
<br>
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit'])) {
$servername = "localhost";
$user = "root";
$password = "";
$database = "enter code here";
$con = mysqli_connect("$servername", "$user" , "$password" ,
"$database");
if ($con->connect_error) {
die ("connection failed" . $con->connect_error);
} else {
$username = mysqli_real_escape_string($con, $_POST['username']);
$blance = mysqli_real_escape_string($con, $_POST['blance']);
$sql = "INSERT INTO user (username, blance) VALUES ('$username',
'$blance')";
if ($con->query($sql) === TRUE) {
echo "success";
} else {
echo "error" . $sql . "<br>" . $con->error;
}
$sql6 = "SELECT * FROM user";
$result = mysqli_query($con, $sql6);
$resultcheck = mysqli_num_rows($result);
if ($resultcheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['username'] . "<br>";
}
}
echo "<br>" . "<br>" . "<br>";
}}
?>
</body>
This query will return sum of points for each username, assuming your table is named test
SELECT SUM(points) AS total_points
FROM test
GROUP BY username
I have this problem with mysql on phpmyadmin databases that I want to update my database, for instance change the username, but with the current code I have, if I leave something empty, it updates the database with empty value, I wanted to change this that IF the post is empty it doesnt update the database to empty space
here is my code:
<!doctype html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "eerstedatabase";
//create connection
$connection = new mysqli($servername, $username, $password, $dbname);
if ($_POST) {
//check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
//if these posts are empty it updates them to empty in the database aswell
$sql = "UPDATE gebruikers SET Gebruikersnaam='" . $_POST['Gebruikersnaam'] . "',
Wachtwoord='" . $_POST['Wachtwoord'] . "',
Email='" . $_POST['Email'] . "'
WHERE ID='" . $_POST['ID'] . "' ";
if ($connection->query($sql) === TRUE) {
echo "Record updated successfully";
include 'Opdracht1.php';
} else {
echo "Error updating record: " . $conn->error;
}
}
else
{
?>
<html>
<head>
<meta charset="utf-8">
<title>Naamloos document</title>
</head>
<body>
<center>
<table>
<form name="update" action="OpdrachtDW6.php" method="POST">
<tr>
<td>ID</td>
<td><input type="text" name="ID" rquired /></td>
</tr>
<tr>
<td>Gebruikersnaam</td>
<td><input type="text" name="Gebruikersnaam" required /></td>
</tr>
<tr>
<td>Wachtwoord</td>
<td><input type="text" name="Wachtwoord" required /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="Email" required /></td>
</tr>
<tr>
<td><input type="submit" value="Updaten" /></td>
</tr>
</td>
</form>
</center>
</body>
</html>
<?php
}
?>
you can check if the POST values are empty or not:
if(empty($_POST['Email'])
// Do something
There are other options like check the length of string, if the name is too short, maybe it is not acceptable. Hope this help.
You need to check the value of the $_POST fields on the server side.
$errs = false;
if ($_POST['ID'] == "") {
$errs = true;
echo "ID Field Missing";
}
if ($_POST['Gebruikersnaam'] == "") {
$errs = true;
echo "Gebruikersnaam Field Missing";
}
/* And so on... */
if (!$errs) {
//check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$sql = "UPDATE gebruikers SET Gebruikersnaam='" . $_POST['Gebruikersnaam'] . "',
Wachtwoord='" . $_POST['Wachtwoord'] . "',
Email='" . $_POST['Email'] . "'
WHERE ID='" . $_POST['ID'] . "' ";
if ($connection->query($sql) === TRUE) {
echo "Record updated successfully";
include 'Opdracht1.php';
} else {
echo "Error updating record: " . $conn->error;
}
}
You can use this logic
if(isset($_POST['Email'])){
//post email is not empty! and you can insert in database!
if ($connection->query($sql) === TRUE) {
echo "Record updated successfully";
include 'Opdracht1.php';
} else {
echo "Error updating record: " . $conn->error;
}
}
What I've done before is build my query into variables, then if a variable is empty it will skip that bit of the query.
For example
if($_POST['fielda']) {
$fieldasql = "fielda = '".$_POST['fielda']."',";
} else {
$fieldasql = "";
}
if($_POST['fieldb']) {
$fieldbsql = "fieldb = '".$_POST['fieldb']."',";
} else {
$fieldbsql = "";
}
then your query would be:
$sql = "UPDATE gebruikers SET " . $fieldasql . " " . $fieldbsql;
Here is the (basic) logic to check against (not) empty fields.
Sidenote: See comments in code to process as desired.
if( !empty($_POST['ID'])
&& !empty($_POST['Gebruikersnaam'])
&& !empty($_POST['Wachtwoord'])
&& !empty($_POST['Email'])
)
{
// Execute the query
}
else {
// kill the process or do something else
}
If you only want to perform the UPDATE if only the email is empty, then simply do:
if(!empty($_POST['Email'])) {
$sql = "UPDATE gebruikers ...
// Rest of your code
}
Consult the following on PHP's logical operators:
http://php.net/manual/en/language.operators.logical.php
and empty():
http://php.net/manual/en/function.empty.php
Footnotes:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements.
Also on doing an UPDATE and to check if it truly was successful, use mysqli_affected_rows():
http://php.net/manual/en/mysqli.affected-rows.php
as if ($connection->query($sql) === TRUE) could give you a false positive.
You can also alter your column(s) to not accept NULL values.
Consult http://dev.mysql.com/doc/refman/5.7/en/working-with-null.html
and making it/them as NOT NULL.
On an added note, this if ($_POST) { could be changed to if(isset($_POST['submit'])){ and adding the submit name attribute to your submit button.
<input type="submit" name="submit" value="Updaten" />
I have a little Problem with my Update query to chnage the Profile Infos
Problem now:
My Update Query is not working completly, the E-Mail query work but the status query is not working.
PHP CODE
if(!empty($_POST)) {
$query = "UPDATE users SET";
if(!empty($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) && $_POST['email'] != $_SESSION['u']['email']) {
$s_mail = $_POST['email'];
$row = mysql_num_rows(mysql_query("SELECT email FROM users WHERE email='$s_mail'"));
if($row != 0) {
header("Location: ".$l['settings']."?msg=2");
die("REDIRECT");
}
$query .= " `email`='".$_POST['email']."'";
$_SESSION['u']['email'] = $_POST['email'];
} else if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
header("Location: ".$l['settings']."?msg=3");
die("REDIRECT");
}
//PROBLEM starts here
if(!empty($_POST['status'])) {
$query .= ",`status`='".$_POST['status']."'";
$_SESSION['u']['status'] = $_POST['status'];
}
//AND ends here
$query .= " WHERE id='".$_SESSION['u']['id']."'";
mysql_query($query);
header("Location: ".$l['settings']."?msg=1");
die("REDIRECT");
}
HTML FORM
<input maxlength="200" type="text" class="form-control" placeholder="Status" name="status" value="<?php //ECHO STATUS ?>" />
Maybe someone can help me.
On your $query you have
$query .= ",`status`='".$_POST['status']."'";
remove comma make it like this
$query .= " `status`='".$_POST['status']."'";
You need to set a flag for email condition as
$flag = FALSE;// set a flag
if (!empty($_POST)) {
if (!empty($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) && $_POST['email'] != $_SESSION['u']['email']) {
$s_mail = $_POST['email'];
$row = mysql_num_rows(mysql_query("SELECT email FROM users WHERE email='$s_mail'"));
if ($row != 0) {
header("Location: " . $l['settings'] . "?msg=2");
die("REDIRECT");
}
$flag = TRUE;// set to true if success
$_SESSION['u']['email'] = $_POST['email'];
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
header("Location: " . $l['settings'] . "?msg=3");
die("REDIRECT");
}
//PROBLEM starts here
if (!empty($_POST['status'])) {
$query = "UPDATE users SET";
$query .= " `status`='" . $_POST['status'] . "'";
if ($flag) {// if true then apply email condition
$query .= ",`email`='" . $_POST['email'] . "'";
}
$query .= " WHERE id='" . $_SESSION['u']['id'] . "'";
$_SESSION['u']['status'] = $_POST['status'];
}
//AND ends here
mysql_query($query);
header("Location: " . $l['settings'] . "?msg=1");
die("REDIRECT");
}
Note:- mysql is deprecated instead use mysqli OR pdo
I am very new to PHP (currently doing a university project). My website is an admin site, with about 3 admin users who can log in and change the site etc. Currently, I have a delete function on my comments (comments which users can post to the site) but anybody who comes onto the site can see the delete function and can delete anybodies comments?
I want it so that only my admin's when logged in, can see the delete function, and subsequently be the only ones who can delete the comments. I have a users database with name, password, username and email columns. I was wondering if somebody could please take a look at my code and tell me how I can change this so that only when admins log in they can see the button and delete the comments.
$str_message = "";
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
}else{
//if ($_SESSION['admin'] == 'yes') {
if(isset($_GET['delete'])){
$deleteq="DELETE FROM comments WHERE ID={$_GET['delete']} LIMIT 1";
$deleter=mysqli_query($db_server, $deleteq);
IF($deleter){
echo"<p>That message was deleted!</p>";}}
//}
//Test whether form has been submitted
if(trim($_POST['submit']) == "Submit"){
//Handle submission
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
$str_message = "The reCAPTCHA wasn't entered correctly. Go back and try it
again.
(reCAPTCHA said: " . $resp->error . ")";
} else {
// Your code here to handle a successful verification
$comment = $_POST['comment'];
if($comment != ""){
$query = "INSERT INTO comments (comment) VALUES ('$comment')";
mysqli_query($db_server, $query) or die("Comment insert failed: " .
mysqli_error($db_server) );
$str_message = "Thanks for your comment!";
}else{
$str_message = "Invalid form submission";
}
}
}
//Create page with or without submission
$query = "SELECT * FROM comments";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server) );
{
while($row = mysqli_fetch_array($result)){
$ID= $row['ID'];
$str_result .= "<p><em>Comment $j (" . $row['commDate'] .
")</em><br /> " .$row['comment'] . "</p>
<a href ='commentnow.php?delete=$ID
'>Delete</a><hr />";
}
mysqli_free_result($result);
} }
?>
If we assume that your commented out statement to check if the user is an admin (if ($_SESSION['admin'] == 'yes')) works, then the following code should give you a good idea of how to do it. There are two places where you need to add the if statement. I haven't been able to test this but look in this code for where you see // ADMIN IF STATEMENT and I hope you understand what changes to your code need to be made for it to work properly.
<?
$str_message = "";
if (!$db_server) {
die("Unable to connect to MySQL: " . mysqli_connect_error());
} else {
if ($_SESSION['admin'] == 'yes') { // ADMIN IF STATEMENT
if (isset($_GET['delete'])) {
$deleteq = "DELETE FROM comments WHERE ID={$_GET['delete']} LIMIT 1";
$deleter = mysqli_query($db_server, $deleteq);
if ($deleter) {
echo "<p>That message was deleted!</p>";
}
}
}
//Test whether form has been submitted
if (trim($_POST['submit']) == "Submit") {
//Handle submission
$resp = recaptcha_check_answer(
$privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]
);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
$str_message = "The reCAPTCHA wasn't entered correctly. Go back and try it again. (reCAPTCHA said: " . $resp->error . ")";
} else {
// Your code here to handle a successful verification
$comment = $_POST['comment'];
if ($comment != "") {
$query = "INSERT INTO comments (comment) VALUES ('$comment')";
mysqli_query($db_server, $query) or die("Comment insert failed: " . mysqli_error($db_server) );
$str_message = "Thanks for your comment!";
} else {
$str_message = "Invalid form submission";
}
}
}
//Create page with or without submission
$query = "SELECT * FROM comments";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server) ); {
while ($row = mysqli_fetch_array($result)) {
$ID = $row['ID'];
if ($_SESSION['admin'] == 'yes') { // ADMIN IF STATEMENT
$str_result .= "<p><em>Comment $j (" . $row['commDate'] . ")</em><br /> " .$row['comment'] . "</p><a href ='commentnow.php?delete=$ID'>Delete</a><hr />";
} else {
$str_result .= "<p><em>Comment $j (" . $row['commDate'] . ")</em><br /> " .$row['comment'] . "</p>";
}
}
mysqli_free_result($result);
}
}
?>
if ($_SESSION['admin'] == 'yes') {
<insert code to generate a delete button here>
}
First you need to change in your log in page. When an user login then check if he is an admin user. if yes the set a session variable ($_SESSION['admin']) to yes or set it to no. try like this:
//login.php
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
}else{
session_start();
$sql="Select * FROM users WHERE user_name = 'your_username' and LIMIT 1";
$result=mysqli_query($db_server, $sql);
$objUser = $result->fetch_object();
if($objUser->user_type =="admin")
$_SESSION['admin'] = 'yes';
else
$_SESSION['admin'] = 'no';
//rest of your code for login the user
}
Then in your delete page check if current user is admin or not. If yes then execute query else echo a message. like this:
session_start();
$str_message = "";
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
}else{
if(isset($_GET['delete'])){
if ($_SESSION['admin'] == 'yes') {
$deleteq="DELETE FROM comments WHERE ID={$_GET['delete']} LIMIT 1";
$deleter=mysqli_query($db_server, $deleteq);
if($deleter){
echo"<p>That message was deleted!</p>";}
}
else
{
echo "you are not admin";
}
}
//Test whether form has been submitted
if(trim($_POST['submit']) == "Submit"){
//Handle submission
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
$str_message = "The reCAPTCHA wasn't entered correctly. Go back and try it
again.
(reCAPTCHA said: " . $resp->error . ")";
} else {
// Your code here to handle a successful verification
$comment = $_POST['comment'];
if($comment != ""){
$query = "INSERT INTO comments (comment) VALUES ('$comment')";
mysqli_query($db_server, $query) or die("Comment insert failed: " .
mysqli_error($db_server) );
$str_message = "Thanks for your comment!";
}else{
$str_message = "Invalid form submission";
}
}
}
//Create page with or without submission
$query = "SELECT * FROM comments";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server) );
{
while($row = mysqli_fetch_array($result)){
$ID= $row['ID'];
$str_result .= "<p><em>Comment $j (" . $row['commDate'] .
")</em><br /> " .$row['comment'] . "</p>
<a href ='commentnow.php?delete=$ID
'>Delete</a><hr />";
}
mysqli_free_result($result);
} }
?>
I think it makes sense !
Basically I have edited the "new_topic" page in my generic forum so that the user can select the category of the post from a drop down list, rather than goto the category first and going to new topic, what I am trying to do now is when the thread is created, rather than jumping to the standard "your new thread was created here" it redirect to the category the topic was made under.
I tried using
header( "Location: category.php?id='. $topic_cat . '" );
But header was already being used elsewhere.
So I found a meta refresh that works to an extent..
echo "<META HTTP-EQUIV='Refresh' Content='0; URL=/category.php?id='. $topic_cat .'>";
But it redirects to "category.phpid=" and outputs the following message..
The category could not be displayed, please try again later.You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 8
Is there anyway I can make the page jump to the category that is only being defined in the submit function itself? Thanks for any help.
EDIT: would using "if" functions work to define the redirect? ie. if topic_cat 2 is selected in the form redirect to category.phpid=2??
Sorry I am very new to PHP and still trying to get my head around it all :(
Here is the topic creation page in it's entirety
<?php
//create_topic.php
include 'connect.php';
if($_SESSION['signed_in'] == false)
{
//the user is not signed in
echo 'Sorry, you have to be signed in to create a topic.';
}
else
{
//the user is signed in
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
//the form hasn't been posted yet, display it
//retrieve the categories from the database for use in the dropdown
$sql = "SELECT
cat_id,
cat_name,
cat_description
FROM
categories";
$result = mysql_query($sql);
if(!$result)
{
//the query failed, uh-oh :-(
echo 'Error while selecting from database. Please try again later.';
}
else
{
if(mysql_num_rows($result) == 0)
{
//there are no categories, so a topic can't be posted
if($_SESSION['user_level'] == 1)
{
echo 'You have not created categories yet.';
}
else
{
echo 'Before you can post a topic, you must wait for an admin to create some categories.';
}
}
else
{
echo '<form method="post" action="">';
echo '<select name="topic_cat">';
while($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
}
echo '</select><br />';
echo '<textarea name="post_content" /></textarea><br /><br />
<input type="submit" value="Create topic" />
</form>';
}
}
}
else
{
//start the transaction
$query = "BEGIN WORK;";
$result = mysql_query($query);
if(!$result)
{
//Damn! the query failed, quit
echo 'An error occured while creating your topic. Please try again later.';
}
else
{
//the form has been posted, so save it
//insert the topic into the topics table first, then we'll save the post into the posts table
$sql = "INSERT INTO
topics(topic_subject,
topic_date,
topic_cat,
topic_by)
VALUES('" . mysql_real_escape_string($_POST['post_content']) . "',
NOW(),
" . mysql_real_escape_string($_POST['topic_cat']) . ",
" . $_SESSION['user_id'] . "
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your data. Please try again later.<br /><br />' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
//the first query worked, now start the second, posts query
//retrieve the id of the freshly created topic for usage in the posts query
$topicid = mysql_insert_id();
$sql = "INSERT INTO
posts(post_content,
post_date,
post_topic,
post_by)
VALUES
('" . mysql_real_escape_string($_POST['post_content']) . "',
NOW(),
" . $topicid . ",
" . $_SESSION['user_id'] . "
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your post. Please try again later.<br /><br />' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
$sql = "COMMIT;";
$result = mysql_query($sql);
echo "<META HTTP-EQUIV='Refresh' Content='0; URL=/category.php?id=". $topic_cat ."'>";
}
}
}
}
}
; ?>
echo "<META HTTP-EQUIV='Refresh' Content='0; URL=/category.php?id=" . $topic_cat . "'>";
That should work. You needed to put double quotation-marks outside the . $topic_cat . variable like so; " . $topic_cat . "