Hello I am trying to use phpmyadmin and connect to my database. I did once before but I have never applied styles to the text boxes so I don't know if its right. For some reason I get an error message I told it to say if it fails to connect. I can't figure out why its not connecting. I'm using MAMP server Port: PHP 5.6.21
Here is my PHP code:
<?php
if($_POST['formSubmit'] == "Submit") {
$errorMessage = "";
if(empty($_POST['formName'])) {
$errorMessage .= "<li>You need to enter your name</li>";
}
if(empty($_POST['formEmail'])) {
$errorMessage .= "<li>You need to enter your email</li>";
}
if(empty($_POST['formSubject'])) {
$errorMessage .= "<li>Please enter a subject.</li>";
}
if(empty($_POST['formComment'])) {
$errorMessage .= "<li>Please enter your question.</li>";
}
$varname = $_POST['formName'];
$varemail = $_POST['formEmail'];
$varsubject = $_POST['formSubject'];
$varcomment = $_POST['formComment'];
if(empty($errorMessage)) {
$db = mysql_connect("localhost","root","root");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("three_cats_database" ,$db);
$sql = "INSERT INTO contact_form (name, email, subject, comment) VALUES (".
PrepSQL($varname) . ", " .
PrepSQL($varemail) . ", " .
PrepSQL($varsubject) . "," .
PrepSQL($varcomment) . ") ";
mysql_query($sql);
header("Location: thankyou.php");
exit();
}
}
// function: PrepSQL()
// use stripslashes and mysql_real_escape_string PHP functions
// to sanitize a string for use in an SQL query
//
// also puts single quotes around the string
//
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
// Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
Here is my HTML:
<p>Please fill out this form completely to contact us with any concerns or suggestions.</p><br>
<div class="imgbg"><div class="img">
<!-- FORM IS HERE -->
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<div class="contact-form margin-top">
<label for='formName'><span>Name:</span>
<input type="text" class="input_text" name="formName" id="name" maxlength="50" value="<?=$varname;?>"/>
</label>
<label for='formEmail'><span>Email:</span>
<input type="text" class="input_text" name="formEmail" id="email" maxlength="50" value="<?=$varemail;?>"/>
</label>
<label for='formSubject'><span>Subject:</span>
<input type="text" class="input_text" name="formSubject" id="subject" maxlength="50" value="<?=$varsubject;?>"/>
</label>
<label><span>Comment</span>
<textarea class="message" name="formComment" id="feedback"><?php echo htmlspecialchars($varcomment);?></textarea>
</label>
<input type="submit" class="button" name="formSubmit" value="Submit" />
</label>
</div>
</form>
And last a picture of my database setup for proof of names
Here is the code that you are having a problem with. Hope this helps. I made comments explaining what was happening throughout the code so if you want to go ahead and read them, that would make you understand a tad bit better. Hope this helps.
if($_POST['formSubmit'] == "Submit") {
$errorMessage = "";
if(empty($_POST['formName'])) {
$errorMessage .= "<li>You need to enter your name</li>";
}
if(empty($_POST['formEmail'])) {
$errorMessage .= "<li>You need to enter your email</li>";
}
if(empty($_POST['formSubject'])) {
$errorMessage .= "<li>Please enter a subject.</li>";
}
if(empty($_POST['formComment'])) {
$errorMessage .= "<li>Please enter your question.</li>";
}
$varname = $_POST['formName'];
$varemail = $_POST['formEmail'];
$varsubject = $_POST['formSubject'];
$varcomment = $_POST['formComment'];
if(empty($errorMessage)) {
try
{
// I used PDO because I prefer it over mysqli
$db = new PDO('mysql:host=localhost:3306;dbname=three_cats_database, root, root');
}
catch(PDOException $e)
{
die('Unable to connect to database');
}
// Here is the sql statement that you provided.
$sql = "INSERT INTO contact_form (name, email, subject, comment)
VALUES (?,?,?,?)";
// Prepare helps with sql injections ect. It is still not completely hacker proof.
$stmt = $db->prepare($sql);
// Each question mark (?) means they increment from 1-4 in this case.
$stmt->bindValue(1, $varname, PDO::PARAM_STR);
$stmt->bindValue(2, $varemail, PDO::PARAM_STR);
$stmt->bindValue(3, $varsubject, PDO::PARAM_STR);
$stmt->bindValue(4, $varcomment, PDO::PARAM_STR);
//If statement to check if the sql command went through.This is also good for error checking.
if($stmt->execute())
{
header("Location: thankyou.php");
}
else
{
// There was an error in the statement
}
}
}
Edit this line to get more informations on your error :
if(!$db) die("Error connecting to MySQL database.");
can become :
if(!$db) die("Error connecting to MySQL database : ".mysql_error($db));
You will see more information when crashing :)
Note : create a user for your table, it's better to never write root password in your php files
Related
I am making a site to display the family relations of an individual...I made use of PHP to store data from a form. I use access code to categorize different relations if an individual. i.e..101-the relations of person X.
I need a bit of help as to why to an entry is being entered twice into the database.(new to PHP and first time asking for help here)
Thank you in Advance!
forms code(IN ct.php):
<form id="frm1" action="ap.php" method="POST">
access code: <input type="text" name="code_entered" value=""><br><br>
position in family: <select name="fpos_entered">
<option>Grandfather</option>
<option>Grandmother</option>
<option>Father</option>
<option>Mother</option>
<option>Brother</option>
<option>Sister</option>
<option>Uncle</option>
<option>Aunt</option>
<option>Nephew</option>
<option>Niece</option>
<option selected>Yourself</option>
</select><br><br>
name: <input type="text" name="name_entered" value=""><br><br>
DOB:<input type="date" name="dob_entered" value=""><br><br>
<input type="submit" value="Submit">
</form>
i use the following PHP code to store the data from the form:
<?php
include 'ct.php';
$temp="temp";
$conn= mysqli_connect ('localhost','root','','familytree');
if (!$conn)
{
die ('Could not connect:' . mysql_error());
}
if (isset($_POST['code_entered']))
{
$acc= $_POST['code_entered'];
}if (isset($_POST['fpos_entered']))
{
$fpos= $_POST['fpos_entered'];
}if (isset($_POST['name_entered']))
{
$n= $_POST['name_entered'];
}if (isset($_POST['dob_entered']))
{
$db= $_POST['dob_entered'];
}
$sql ="insert into temp values ('$acc', '$n','$fpos','$db')";
$result = mysqli_query($conn,$sql);
if ($conn->query($sql) === TRUE) {
echo "<p>New record created successfully</p>.";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
which results in me having :
pic of the database after 2 enteries
<?php
declare(strict_types=1);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "familytree";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
try {
$stmt = $conn->prepare("
INSERT INTO `temp` (code, fpos, name, dob)
VALUES (:code, :fpos, :name, :dob)");
$stmt->bindParam(':code', $_POST['code_entered'] ?? null);
$stmt->bindParam(':fpos', $_POST['fpos_entered'] ?? null);
$stmt->bindParam(':name', $_POST['name_entered'] ?? null);
$stmt->bindParam(':dob', $_POST['dob_entered'] ?? null);
$stmt->execute();
echo "<p>New record created successfully</p>.";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
I recommend you to use PDO instead of mysqli. Also, bind the attributes coming from outside :)
Official docu: https://www.w3schools.com/php/php_mysql_prepared_statements.asp
you can change the code of this
$result = mysqli_query($conn,$sql);
if ($conn->query($sql) === TRUE) {
echo "<p>New record created successfully</p>.";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
into this
$result = mysqli_query($conn,$sql);
if ($result === TRUE) {
echo "<p>New record created successfully</p>.";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
and also you must to be careful about sql injection so i think you must use this
Getting an error of
"Error: 1
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 '1' at line 1"
Please help guys, Many thanks in advance.
Code:
<?php
include('head.php');
if(isset($_POST['submit']))
{
$userid = trim($_POST['userid']);
$email = trim($_POST['email']);
$mobile = trim($_POST['mobile']);
$sql = mysqli_query($conn,"INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')");
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>******</title>
<link href="forum-styles.css" rel="stylesheet" type="text/css">
</head>
<style type="text/css">
.txtField {
padding: 5px;
border:#fedc4d 1px solid;
border-radius:4px;
}
</style>
<body background="img/gold-and-money.jpg">
<form action="" method="post" class="basic-grey">
<h1>****** Forgot Password
<span>Please let us know your UserId, We will reset password and inform you.</span> </h1>
<label>
<span>User Id :</span>
<input type="text" name="userid" required />
</label>
<label>
<span>Mobile N. :</span>
<input type="text" name="mobile" required/>
</label>
<label>
<span>Email Id :</span>
<input type="text" name="email" required/>
</label>
<label>
<div align="right"><span> </span>
<input type="submit" class="button" value="Submit" name="submit"/>
</div>
</label>
</form>
</body>
</html>
$sql = mysqli_query($conn,"INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')");
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
You've got two calls here to mysqli_query. The first time, you're making the query and assigning the return value to $sql; the second time, you're running $sql as a query.
To fix the immediate problem, do something along the lines of:
$sql = "INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')";
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
You're assigning your query to a string, and then using that in your query. This makes debugging things easier, as you can now output your generated query to check what you're producing.
However
You're also passing user-generated data directly into an SQL query, without escaping it. This is very bad - at best, you're going to have a problem if some of the data contains apostrophes. At worst, your database will get hacked. One solution here is to use escaping, as Fred suggested, using mysqli_real_escape_string:
$userid = mysqli_real_escape_string($conn, $_POST['userid']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$mobile = mysqli_real_escape_string($conn, $_POST['mobile']);
I'd suggest also looking at using bound parameters and a prepared statement instead, for added extra security.
Use prepared statements, or PDO with prepared statements, they're much safer.
#andrewsi answered correct: "You're running your query twice. The first time, you're assigning the result to $sql; the second time, you're trying to run that result as a query."
#andrewsi, you r running your query twice and your your query contains variables which you have make them as literals. so code would be like this:
$sql ="INSERT INTO forgot(userid,email,mobile)VALUES ($userid,$email,$mobile)";
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
I hope this will help you.
Here is a basic example. Check where you have a turn. Always keep follow the standard way of coding.
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
/* drop table */
$mysqli->query("DROP TABLE myCity");
/* close connection */
$mysqli->close();
?>
Ankit, their are few things to take care of while coding the queries, instead of explaining them, I will try to rewrite the query:
$query = sprintf("INSERT INTO forgot('userid','email','mobile')
VALUES ('%s', '%s', '%s')"
, mysqli_real_escape_string( $con, $_POST['userid'] )
, mysqli_real_escape_string( $con, $_POST['email'] )
, mysqli_real_escape_string( $con, $_POST['mobile'] ));
if (mysqli_query($dbConnection, $query)) {
echo "Successfully inserted" . mysqli_affected_rows($conn) . " row";
} else {
echo "Error occurred: " . mysqli_error($dbConnection);
}
if in case, userid is the integer, convert the userid to int as follows before creating the $query:
$userid = (int)$_POST['userid'];
$sql = "INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')";
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
It will work.
I have a table ver_code in my database and inside the table there is only one row called code and i have inserted few verification code like ABCDEF , GHIJKL for instance now my following code has failed to verify code from my table using a simple form below
<?php
if (isset($_POST['ver_code']))
{
$ver_code = $_POST['ver_code'];
if(!empty($ver_code)){
try{
$conn = new PDO("mysql:host=localhost;dbname=pro1", "pro1", "4931//4931");
}
catch(PDOException $pe)
{
die('Connection error, because: ' .$pe->getMessage());
}
$sql = "SELECT `code` FROM `ver_code`";
$stmt = $conn->query($sql);
if(!$stmt)
{
die("Execute query error, because: ". $conn->errorInfo());
}
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt->fetch();
if($row['code'] == $ver_code['code']){
echo "Account Verified ! ";
}else{
echo "Invalid Verification Code !";
}
}else{
echo "Plz enter a verification code ... ";
}
}
?>
<form action="index2.php" method="POST" >
<input type="text" name="ver_code" />
<input type="submit" value="Verify" />
</form>
i doubt this line
$row['code'] == $ver_code['code']
it should be
$row['code'] == $ver_code; as $ver_code is simple post variable not an array.
EDIT: if you need to verify from all rows
$stmt = $conn->prepare("SELECT `code` FROM `ver_code` where code= ?");
$stmt->bindParam(1,$ver_code);
$stmt->execute();
if($stmt->rowCount()>0){
echo "Account Verified ";
}else{ echo "Invalid Verification Code";}
I have to code below - updated
php code
if(empty($_POST['formEmail']))
{
$errorMessage .= "<li>You forgot to enter your email</li>";
}
$varEmail = $_POST['formEmail'];
if(empty($errorMessage))
{
$db = mysql_connect("servername","username","password");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("tableName" ,$db);
$sql = "INSERT INTO emails(email) VALUES ('$varEmail')";
mysql_query($sql);
echo "Details added";
$_SESSION['status'] = 'success';
}
exit();
}
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
form code
<?php
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<p>
<label for='formEmail'>Sign up to be notified when we go live!</label><br/>
<input type="text" name="formEmail" maxlength="50" value="<?=$varEmail;?>" />
</p>
<input type="submit" name="formSubmit" value="Submit" />
</form>
I'm not getting any errors and as far as I can tell the syntax looks fine but its not putting the email information into the database. Anyone have an idea of whats going on? As a side note I am a newb to all php.
You've forgotten to run the query! Put
mysql_query($sql);
straight after
$sql = "INSERT INTO emails(email) VALUES ('$varEmail')";
Make sure you run the $_POST variable through mysql_real_escape_string as well:
$varEmail = mysql_real_escape_string($_POST['formEmail']);
This will help protect you from SQL Injection attacks.
EDIT
One more tiny thing, I guess you want to set the session variable success when the form has submitted successfully. to do that you'll need to move
echo "Details added";
$_SESSION['status'] = 'success';
within the same if structure as the SQL query is run, otherwise it will never be set
Try:
$db = mysql_connect("servername","username","password");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("tableName" ,$db);
$sql = sprintf("INSERT INTO emails(email) VALUES ('%s')",mysql_real_escape_string($varEmail));
$results = mysql_query($sql);
I have heard of this issue but can't seem to figure it out. I have the database and table names correct. I am not finding any errors and i even inserted a table myself on phpmyadmin that worked but when I tried to do it on my site it doesnt work. I even tested the connection..Not sure what to do now
Maybe someone can take a look at my code and see if they notice anything
<?php
if(mysql_connect('<db>', '<un>', '<pw>') && mysql_select_db('smiles'))
{
$time = time();
$errors = array();
if(isset($_POST['guestbook_name'], $_POST['guestbook_message'])){
$guestbook_name = mysql_real_escape_string(htmlentities($_POST['guestbook_name']));
$guestbook_message = mysql_real_escape_string(htmlentities($_POST['guestbook_message']));
if (empty($guestbook_name) || empty($guestbook_message)) {
$errors[] = 'All Fields are required.';
}
if (strlen($guestbook_name)>25 || strlen($guestbook_message)>255) {
$errors[] = 'One or more fields exceed the character limit.';
}
if (empty($errors)) {
$insert = "INSERT INTO 'guestbook'VALUES('','$time','$guestbook_name','$guestbook_message')";
if($insert = mysql_query($insert)){
header('Location: '.$_SERVER['PHP_SELF']);
} else{
$errors[] = 'Something went wrong . Please try again.';
}
} else {
foreach($errors as $error) {
echo '<p>'.$error.'</p>';
}
}
}
//display entries
}
else {
'Fixing idiot';
}
?>
<hr />
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>" method="POST">
<p>Post Somethign</p>
<br />
Name:<br /><input type="text" name="guestbook_name" maxlength="25" />
<br />
Message:
<br />
<textarea name="guestbook_message" rows="6" coles="30"maxlength="255"></textarea>
<input type="submit" value="Post" />
</form>
Remove quotes from table name 'guestbook' and leave a space between it and values
Table name doesn't need quotes and supossing you're using id autoincrement, don't insert an empty string. So it should be:
$insert = "INSERT INTO guestbook VALUES('$time','$guestbook_name','$guestbook_message')";
Also, take a look at your $time value. What MySQL data type is?
After the insert, try to display the mysql error:
$conn = mysql_connect('<db>', '<un>', '<pw>');
mysql_query($insert)
if (mysql_errno($conn)){
$errors[] = mysql_error($conn);
}else{
header('Location: '.$_SERVER['PHP_SELF']);
}
EDIT: The hole snippet should be similar to:
<?php
$conn = mysql_connect('<db>', '<un>', '<pw>')
if( $conn && mysql_select_db('smiles')) //Note $conn
{
$time = time();
$errors = array();
if(isset($_POST['guestbook_name'], $_POST['guestbook_message'])){
$guestbook_name = mysql_real_escape_string(htmlentities($_POST['guestbook_name']));
$guestbook_message = mysql_real_escape_string(htmlentities($_POST['guestbook_message']));
if (empty($guestbook_name) || empty($guestbook_message)) {
$errors[] = 'All Fields are required.';
}
if (strlen($guestbook_name)>25 || strlen($guestbook_message)>255) {
$errors[] = 'One or more fields exceed the character limit.';
}
if (empty($errors)) {
mysql_query($insert)
$insert = "INSERT INTO guestbook VALUES('$time','$guestbook_name','$guestbook_message')";
if (mysql_errno($conn)){
$errors[] = mysql_error($conn);
}else{
header('Location: '.$_SERVER['PHP_SELF']);
}
} else {
foreach($errors as $error) {
echo '<p>'.$error.'</p>';
}
}
}
//display entries
}
you can try below query for insertion:
$insert = "INSERT INTO guestbook VALUES('','{$time}','{$guestbook_name}','{$guestbook_message}')";