insert record using mysqli with one page - php

I'm wondering what's the problem with this code?
What I want to happen is to insert record when I click the Submit Button. But it seems I'm having a problem with the isset function.
Database Name: dbase
Table Name: tblmessage
Fields:
message_id - INT - auto increment
message - TEXT
Update:
I can't still add / insert record in my database.
Thank you in advance!
<html>
<head></head>
<body>
<form method = "post" action = "<?php echo $_SERVER['PHP_SELF']; ?>">
Message: <input type = "text" name = "message">
</br></br>
<input type = "submit" name = "submit">
</form>
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['message'])) {
$conn = mysqli_connect("localhost", "root", "","dbase");
$message = $_POST['message'];
$sql = ""INSERT INTO tblmessage (message_id, message) VALUES (NULL, '$message')";
$insert = mysqli_query($conn,$sql);
if ($insert) {
echo "Message successfully added!";
}
else {
echo "Error" . mysqli_error($conn);
}
}
}
mysqli_close($conn);
?>
</body>
</html>

Working Code just copy and paste it
<html>
<head></head>
<body>
<form method = "post" action = "<?php echo $_SERVER['PHP_SELF']; ?>">
Message: <input type = "text" name = "message">
</br></br>
<input type = "submit" name = "submit">
</form>
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['message'])) {
$conn = mysqli_connect("localhost", "root", "", "dbase");
$message = $_POST['message'];
$sql = "INSERT INTO tblmessage (message_id, message) VALUES (NULL, '" . $message . "')";
$insert = mysqli_query($conn, $sql);
mysqli_close($conn);
if ($insert) {
echo "Message successfully added!";
} else {
echo "Error" . mysqli_error($conn);
}
}
}
?>
</body>
</html>

You're trying to implode a String. Read about implode.
Change:
$sql = "INSERT INTO tblmessage (message) VALUES (NULL, ".implode(',',$message).")";
$insert = mysqli_query($conn,$sql);
To:
$sql = "INSERT INTO tblmessage (message_id, message) VALUES (NULL, '$message')";
$insert = mysqli_query($conn,$sql);

You donĀ“t have any SQL-Statement in your Code.
If you want to insert the Message from your form you need to change $sql.
$sql = INSERT into dbase(your_database_field) Values ($message);
$sql-statement=mysqli_query($conn, $sql);
You should sanitize your input before sending your data to the database.

Related

MySQL database could not be updated with PHP program

addmember.php
<?php
require_once("dbtools.inc.php");
$account = $_POST["account"];
$password = $_POST["password"];
$name = $_POST["name"];
$sex = $_POST["sex"];
$year = $_POST["year"];
$month = $_POST["month"];
$day = $_POST["day"];
$telephone = $_POST["telephone"];
$address = $_POST["address"];
$email = $_POST["email"];
$comment = $_POST["comment"];
$link = create_connection();
$sql = "SELECT * FROM users Where account = '$account'";
$result = execute_sql($link, "member", $sql);
if (mysqli_num_rows($result) != 0)
{
mysqli_free_result($result);
echo "<script type='text/javascript'>";
echo "alert('Account already in use! Please choose another username');";
echo "history.back();";
echo "</script>";
}
else
{
mysqli_free_result($result);
$sql = "INSERT INTO users (account, password, name, sex,
year, month, day, telephone, address,
email, comment) VALUES ('$account', '$password',
'$name', '$sex', $year, $month, $day, '$telephone',
'$address', '$email', '$comment')";
$result = execute_sql($link, "member", $sql);
echo "User added successfully!";
}
mysqli_close($link);
?>
join.html
<form action="addmember.php" method="POST" name="myForm">
(Different types of input)
<input type="submit" value="Add">
My aim is to add a member data into the database after the user clicked the Add button on the form in join.html. However the page could run echo "User added successfully!"; this line but the problem is the database could not get updated even though I already called execute_sql command. May I ask what is missing in order to be connected with the database?

How to avoid duplicate emails php / sql?

I used this code and I don't know what is the problem and I used different codes as well
what I want to do to check and not allow the user to add his email twice
<?php
include("includedb.php");
//declare variables
$name = $_POST['name'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$gift = $_POST['gift'];
$formName = $_POST['formName'];
$formEmail = $_POST['formEmail'];
$formEmirate = $_POST['formEmirate'];
$birthday = $_POST['birthday'];
$date = $_POST['date'];
$result = mysqli_query("SELECT * FROM users WHERE email = '$email'") or exit(mysqli_error()); //check for duplicates
$num_rows = mysqli_num_rows($result); //number of rows where duplicates exist
if ($num_rows == 0) { //if there are no duplicates...insert
$sql = "INSERT INTO users (name, email, tel, gift, formName, formEmail, formEmirate, birthday, date)
VALUES ('$name', '$email', '$tel','$gift', '$formName', '$formEmail', '$formEmirate','$birthday',CURRENT_TIMESTAMP )";
if (!mysqli_query($sql)) {
die('Error: ' . mysqli_error());
}
}
mysqli_close();
header("location: thank-you.html?remarks=success");
?>
the problem is you are not passing any connection to the mysql_query
thus the queries are not getting queried
$conn = your connection;
$result = mysqli_query($conn,"SELECT * FROM users WHERE email = '$email'") or exit(mysqli_error()); //check for duplicates
$num_rows = mysqli_num_rows($result); //number of rows where duplicates exist
if($num_rows == 0) { //if there are no duplicates...insert
$sql = "INSERT INTO users (name, email, tel, gift, formName, formEmail, formEmirate, birthday, date)
VALUES ('$name', '$email', '$tel','$gift', '$formName', '$formEmail', '$formEmirate','$birthday',CURRENT_TIMESTAMP )";
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error());
}
}
thanks for support I found what has worked with me please find the code below and please advise me how to make it secure and protect it from sql injection
if(isset($_POST['submit'])){
$name= $_POST['name'];
$email= $_POST['email'];
$result = mysqli_query($conn,"SELECT * FROM test WHERE email = '$email'") or exit(mysqli_error()); //check for duplicates
$num_rows = mysqli_num_rows($result); //number of rows where duplicates exist
if(($num_rows) > 0){
echo "A record already exists.";
exit;
}
else{
$sql = "INSERT INTO test (name, email)
VALUES ('$name', '$email')";
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error());
}
}
if($result) {
header("Location: game.html");
}else{ echo "Not Successful"; }
mysqli_close();
}
?>
<!DOCTYPE html>
<head>
</head>
<body>
<h2>Enter your Name and Email</h2>
<form method="post">
<p><strong>First Name:</strong><br /> <input type="text" name="name" /></p>
<p><strong>email:</strong><br /> <input type="email" name="email"/></p>
<input type="submit" name="submit" value="Add Customer" />
</form>
</body>
</html>

Inserting E-mail Into DB

Trying to build an email list in a database. I made this code, but it's not working and i'm not getting any errors. Am I on the right track?
HTML:
<div id="signup">
<h1>Sign-Up For Our Newsletter!</h1>
<form method="post" action="scripts/php/addSubscription.php">
<label for="email">E-mail: </label><input type="email" name="email" size="75"> <input type="submit">
</form>
</div>
PHP:
require('settings/globalVariables.php');
require('settings/mysqli_connect.php');
mysqli_select_db($conn,"newsletterlist");
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sql = "INSERT INTO newsletterusers (email) VALUES ($email)";
if (mysqli_query($conn, $sql)) {
echo 'You have successfully subscribed!';
}
else {
echo 'Sorry, An error occured. Please try again.';
}
mysqli_close($conn);
$conn is a variable in mysqli_connect.php
Adding contents of mysqli_connect.php just for reference:
<?php
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS);
?>
I use this on several databases and it connects each time.
EDIT:
Updated code per answers/comments and still nothing is happening.
require('settings/globalVariables.php');
require('settings/mysqli_connect.php');
mysqli_select_db($conn,"newsletterlist");
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sql = "INSERT INTO newsletterusers (email) VALUES ('$email')";
if (mysqli_query($conn, $sql)) {
echo 'You have successfully subscribed!';
}
else {
echo "Error: ".mysqli_error($conn);
}
mysqli_close($conn);
SOLVED:
require('/home/jollyrogerpcs/public_html/settings/globalVariables.php');
require('/home/jollyrogerpcs/public_html/settings/mysqli_connect.php');
mysqli_select_db($conn,"newsletterlist");
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sql = "INSERT INTO newsletterusers (email) VALUES ('$email')";
if (mysqli_query($conn, $sql)) {
echo 'You have successfully subscribed!';
}
else {
echo "Error: ".mysqli_error($conn);
}
mysqli_close($conn);
You are currently getting an error but your code doesn't show you. Print the error for a start:
if (mysqli_query($conn, $sql)) {
echo 'You have successfully subscribed!';
}
else {
echo "Error: ".mysqli_error($conn);
}
The real error you are getting is a syntax error. This is how your generated SQL looks like:
INSERT INTO newsletterusers (email) VALUES (hello#email.com)
Note that there are no quotes around it, you can fix it by surrounding $email with quotes:
$sql = "INSERT INTO newsletterusers (email) VALUES ('$email')";

Unhelpful SQL/PHP error

EDIT: I think I figured out what is happening! The Variable $string is set to be a post value, so when I run the comment code it is overriding the Post value with its own and setting $string to be nothing, breaking the page. Any ideas how to fix?
I'm running a piece of code for a simple website that should submit a comment entered into a form into the database, but when I click the submit button for the comment it just gives me this error message:
Database access failed1: 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 1
The code for the page in question is:
<?php
require_once('checklog.php');
require_once("functions.php");
require_once('../Website/recaptcha/recaptchalib.php');
//Include external php files. Functions contains functions, Checklog redirects the user to the login page if they are not logged in. Checklog also contains session_start(). If you remove it make sure to add session_start() to this page.
$db_hostname = 'localhost';
$db_database = 'removed';
$db_username = 'removed';
$db_password = 'removed';
$db_status = 'not initialised';
$str_result = '';
$str_options = '';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
$db_status = "connected";
$string = $_POST ['filmID'];
mysqli_select_db($db_server, $db_database);
$query = "SELECT FilmName, GenreName, DirName, Synopsis FROM Films JOIN Genres JOIN Directors WHERE Directors.DirID = Films.DirID AND Films.GenreID = Genres.GenreID AND Films.FilmID = $string";
$resultcount = 1;
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed1: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$FilmName = $row['FilmName'];
$GenreName = $row['GenreName'];
$DirName = $row['DirName'];
$Synopsis = $row['Synopsis'];
}
mysqli_free_result($result);
$query = "SELECT username, Rating, Comment FROM Comments JOIN Users WHERE Comments.UserID = Users.UserID AND Comments.FilmID = $string";
$commentnum = 1;
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed2: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_comments .= "<p>" . $commentnum . " - Review by " . $row['username'] . ": " . $row['Comment'] . " [" . $row['Rating'] . "/5]</p>";
$commentnum = $commentnum + 1;
}
mysqli_free_result($result);
if(trim($_POST['submit']) == "Submit"){
$privatekey= "6Lem4-gSAAAAADsaa9KXlzSAhLs8Ztp83Lt-x1kn";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
$message = " ";
if (!$resp->is_valid) {
//incorrect entry
$message = "The reCAPTCHA wasn't entered correctly. Go back and try again.
(reCAPTCHA said: " . $resp->error . ")";
//recaptcha validation
} else {
//Submit the reviews
$comment = clean_string($db_server, $_POST['comment']);
$rating = clean_string($db_server, $_POST['rating']);
$user = $SESSION['UserID'];
if ($comment != '') {
$queryreview = "INSERT INTO Comments (Comment, Rating, UserID, FilmID) VALUES ('$comment', '$rating', '$user', '$string')";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $queryreview) or
die("Insert failed: " . mysqli_error($db_server));
}
}
}
?>
<html>
<head>
<title>View individual film details.</title>
</head>
<body>
<h1>Welcome to the site, <?php echo $_SESSION['username']; ?> ! You are user ID <?php echo $_SESSION['userid'] ?>.</h1>
<p>This film is called <?php echo $FilmName ?> and is a <?php echo $GenreName; ?> film directed by <?php echo $DirName; ?></p>
<p>Synopsis: <?php echo $Synopsis; ?> </p></body>
<p>Reviews:
<?php echo $str_comments ?></p>
<form id="frmComments" action="viewfilm.php" method="post">
<p>Have you seen this movie? Leave a review and tell other users what you thought.</p>
review: <textarea rows="2" cols="30" name="comment"></textarea> </p>
<p>Rating: <select name="rating">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<?php
$publickey = "6Lem4-gSAAAAAMHLAVbieIknMtUZo71ZKzzCkoFN";
echo recaptcha_get_html($publickey);
?>
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
</body>
</html>
The piece of code that should be running the comment insertion is
if(trim($_POST['submit']) == "Submit"){
$privatekey= "6Lem4-gSAAAAADsaa9KXlzSAhLs8Ztp83Lt-x1kn";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
$message = " ";
if (!$resp->is_valid) {
//incorrect entry
$message = "The reCAPTCHA wasn't entered correctly. Go back and try again.
(reCAPTCHA said: " . $resp->error . ")";
//recaptcha validation
} else {
//Submit the reviews
$comment = clean_string($db_server, $_POST['comment']);
$rating = clean_string($db_server, $_POST['rating']);
$user = $SESSION['UserID'];
if ($comment != '') {
$queryreview = "INSERT INTO Comments (Comment, Rating, UserID, FilmID) VALUES ('$comment', '$rating', '$user', '$string')";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $queryreview) or
die("Insert failed: " . mysqli_error($db_server));
}
}
}
But as you can see by the "1" included in the error message, the error is pointing to the earlier query that is used to generate the page content. Thing is this query does work, it is only after clicking submit on a comment that I get this error.
Yes, the probem is indeed the $string variabe that is being sent empty.
There are different ways to solve this issue here are some ideas:
Use a hidden field in the form where the value of the posted filmID is stored and sent again after submitting.
Store the filmID value in the Session global.
Hope this helps
if you need to give string in your values then set variable inside quotation like this:
Change
$queryreview = "INSERT INTO Comments (Comment, Rating, UserID, FilmID) VALUES ('$comment, $rating, $user, $string')"
to
$queryreview = "INSERT INTO Comments (Comment, Rating, UserID, FilmID) VALUES ('$comment', '$rating', '$user', '$string')"

Unknow php error in sql INSERT INTO

I have problem in my registration.
Look on my code:
//player.php
<?php
session_start();
class Player
{
var $name;
function _construct($name)
{
$this->$name = $name;
}
function CreatePlayer($name, $pass, $mail, $date, $type)
{
if($_POST['submit'])
{
$link = mysql_connect("localhost","wewewe", "wewewe");
if(!$con)
{
die( $return = mysql_error());
}
mysql_select_db("wewewe", $con);
mysql_query("INSERT INTO USERS (name, pass, mail, date, type) VALUES ('$name', '$pass', '$mail', '$date','$type')");
mysql_close(link);
}
return $return;
}
function LoginPlayer($name, $pass)
{
$link = mysql_connect("localhost","username", "pass");
mysql_select_db("con", $con);
$result = mysql_query("SELECT FROM USERS WHERE pass='$pass' AND name='$name'");
$count = mysql_num_rows($result);
if($count==1)
{
$_SESSION['name'] = $name;
$_SESSION['logged'] = true;
}
mysql_close($link);
}
}
?>
//reg.php
<html>
<form action="log.php" method="post">
Meno: <input type="text" name="meno">
<br>
Heslo: <input type="text" name="heslo">
<br>
Mail: <input type="text" name="mail">
<br>
Date: <input type="text" name="date">
<br>
Type: <input type="text" name="type">
<br>
<input type="submit">
<br>
</form>
<?php
include 'player.php';
$name = $_POST['meno'];
$pass = $_POST['heslo'];
$mail = $_POST['mail'];
$date = $_POST['date'];
$type = $_POST['type'];
$obj = new Player($name);
$res = $obj->CreatePlayer($name, $pass, $mail, $date, $type);
if($res==true)
{
echo "jo!";
}
else
{
echo $res;
}
?>
My problem is that if I write text to all fields and press ok, my page will restart but without any error message. And when I will look to a database, theres nothing. Why? Can anybody plese help me?
EDIT:
<?php
session_start();
class Player
{
var $name;
function _construct($name)
{
$this->$name = $name;
}
function CreatePlayer($name, $pass, $mail, $date, $type)
{
if($_POST['submit'])
{
$con = mysql_connect("localhost","wewewe", "wewewe");
if(!$con)
{
die( $return = mysql_error());
}
mysql_select_db("wewewe", $con);
$query = "INSERT INTO USERS (name, pass, mail, date, type) VALUES ('$name', '$pass', '$mail', '$date','$type')";
$retrn = var_dump($query); // SHOWS YOU QUERY STRING
mysql_query($query) or die(mysql_error()); // EXECUTES QUERY OR THROWS EXCEPTON (SHOWS ERROR TOO)
mysql_close($con);
}
return $return;
}
function LoginPlayer($name, $pass)
{
$link = mysql_connect("localhost","username", "pass");
mysql_select_db("con", $con);
$result = mysql_query("SELECT FROM USERS WHERE pass='$pass' AND name='$name'");
$count = mysql_num_rows($result);
if($count==1)
{
$_SESSION['name'] = $name;
$_SESSION['logged'] = true;
}
mysql_close($link);
}
}
?>
I think its not going inside if($_POST['submit'])
change
<input type="submit">
to
<input name="submit" type="submit" />
<input type="submit"> modify to <input type="submit" name="submit">
To debug SQL INSERTING :
mysql_select_db("wewewe", $con);
mysql_query("INSERT INTO USERS (name, pass, mail, date, type) VALUES ('$name', '$pass', '$mail', '$date','$type')");
mysql_close(link);
modify to
mysql_select_db("wewewe", $con);
$query = "INSERT INTO USERS (name, pass, mail, date, type) VALUES ('$name', '$pass', '$mail', '$date','$type')";
var_dump($query); // SHOWS YOU QUERY STRING
mysql_query($query) or die(mysql_error()); // EXECUTES QUERY OR THROWS EXCEPTON (SHOWS ERROR TOO)
mysql_close(link);
Your query in the function LoginPlayer is incorrect. You may simply fix it like this
$result = mysql_query("SELECT name FROM USERS WHERE pass='$pass' AND name='$name'");

Categories