I'm noobish to coding. I set up a MYSQL database called contacts, a table called contactstable with fields id, firstname, lastname, emailaddress,postalcode and phonenumber. Each are text or varchars except for the id, which is an auto_increment, pk field. The connection doesnt give any errors, and no error is relayed through the mysqli_connect_error() method. They query doesnt go through and no query is executed. I cant figure out why.
<html>
<head>
<title>Registration</title>
</head>
<body>
<h1>Register with Us!</h1>
<h2>Registration Complete!</h2>
<div class="feedback-container" <?= isset($_REQUEST["first-name"])? "style=\"display:block\"": "style=\"display:none\""; ?>>
<?php
$firstname = $lastname = $emailaddress = $postalcode = $phonenumber = NULL;
if (isset($_REQUEST["first-name"])){
$firstname = $_REQUEST["first-name"];
$lastname = $_REQUEST["last-name"];
$emailaddress = $_REQUEST["email-address"];
$postalcode = $_REQUEST["postal-code"];
$phonenumber = $_REQUEST["phone-number"];
$dbconn = new mysqli();
$dbconn->connect("localhost","root","","contacts");
if(mysqli_connect_error()){
echo "Connection Failed";
}else{
echo "Connection Established";
}
$query = "INSERT INTO 'contactstable' ('firstname', 'lastname', 'emailaddress','postalcode','phonenumber') VALUES ('$firstname', '$lastname', '$emailaddress', '$postalcode', '$phonenumber')";
if ($dbconn->query($query) == TRUE){
echo ("Thank you for registering with us. We will shortly send a confirmation email to $emailaddress.");
}else{
echo ("<p>Your contact information was not added to our database. Please try again later or contact our webadmin at webadmin#gmail.com</p>");
}
}
?>
</div>
</body>
When it runs, it outputs the following:
"Connection Established"
"Your contact information was not added to our database. Please try again later or contact our webadmin at webadmin#gmail.com"
There are no error messages.
There is no data updated.
I'd make this
$query = "INSERT INTO 'contactstable' ('firstname', 'lastname', 'emailaddress','postalcode','phonenumber') VALUES ('$firstname', '$lastname', '$emailaddress', '$postalcode', '$phonenumber')";
look like this
$query = "INSERT INTO contactstable (firstname, lastname, emailaddress,postalcode,phonenumber) VALUES ('$firstname', '$lastname', '$emailaddress', '$postalcode', '$phonenumber')";
query should look like this.
INSERT INTO `contactstable`
(`firstname`, `lastname`, `emailaddress`,`postalcode`,`phonenumber`)
VALUES
('$firstname', '$lastname', '$emailaddress', '$postalcode', '$phonenumber')
Use backticks if you want to quote your field names.
$query = "INSERT INTO `contactstable` (`firstname`, `lastname`, `emailaddress`,`postalcode`,`phonenumber`) VALUES ('$firstname', '$lastname', '$emailaddress', '$postalcode', '$phonenumber')";
Also you can use " if you set SET sql_mode='ANSI_QUOTES'
http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html
Related
I was trying to insert data into multiple data tables. It's only working for single data tables, I'm just wondering how I would be able to insert data into two data tables. I've been struggling with this issue for the past few hours and can't seem to get to the bottom of it. If anyone has any advice please let me know. :)
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost","ivodatat","","");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Inputs for security
$fname = mysqli_real_escape_string($link, $_REQUEST['fname']);
$sname = mysqli_real_escape_string($link, $_REQUEST['sname']);
$address = mysqli_real_escape_string($link, $_REQUEST['address']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
$phone = mysqli_real_escape_string($link, $_REQUEST['phone']);
$mac = mysqli_real_escape_string($link, $_REQUEST['mac']);
$installer = mysqli_real_escape_string($link, $_REQUEST['installer']);
$status = mysqli_real_escape_string($link, $_REQUEST['status']);
// Insert Query
$sql1 = "INSERT INTO leadlist (fname, sname, address, email, phone, mac, installer, status) VALUES ('$fname', '$sname', '$address', '$email', '$phone', '$mac', '$installer', '$status')";
$sql2 = "INSERT INTO $installer (fname, sname, address, email, phone, mac, installer, status) VALUES ('$fname', '$sname', '$address', '$email', '$phone', '$mac', '$installer', '$status')";
if (mysqli_multi_query($link, $sql1, $sql2)){
mysqli_close($conn);
header("Location: installercontrol.php");
exit;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close The Connection
mysqli_close($link);
?>
To use mysqli_multi_query you need to append the queries to each other as it only takes one query argument. From the manual:
Executes one or multiple queries which are concatenated by a semicolon.
Try this instead:
mysqli_multi_query($link, $sql1 . ';' . $sql2)
You should probably also update your error message:
echo "ERROR: Could not able to execute $sql1;$sql2. " . mysqli_error($link);
$name = mysqli_real_escape_string($connection, $_POST["name"]);
$surname = mysqli_real_escape_string($connection, $_POST["surname"]);
$username = mysqli_real_escape_string($connection, $_POST["username"]);
$email = mysqli_real_escape_string($connection, $_POST["email"]);
$pw1 = mysqli_real_escape_string($connection, $_POST["pw1"]);
$query = "INSERT INTO 'users' ('id','name', 'surname', 'username', 'email', 'password') VALUES (NULL,'$name', '$surname', '$username', '$email', '$pw1')";
$result = mysqli_query($connection, $query);
if(!$result){
echo ("fail");
}
I test if the query has worked using if(!$result){ echo ("fail");} and it echoes fail every time and no data is inserted into the database every time! I have checked the syntax and i believe it is correct... could this be because of the database "collation"?
You should not use the single quote at the table or field name. You have to use a Backtick (like ``) which is located in under Esc key or left side of 1 Key or upper side of Tab key. It should looks like:
$query = "INSERT INTO `users` (`id`, `name`, `surname`, `username`, `email`,
`password`) VALUES ('null', '$name', '$surname', '$username', '$email', '$pw1')";
or
$query = "INSERT INTO users (id, name, surname, username, email,
password) VALUES ('null', '$name', '$surname', '$username', '$email', '$pw1')";
Note: If your id field is already set auto increment then you can remove id and value null. Because id value will automatically increment.
Hope it will helpful.
I'm on ubuntu running on apache2.
<?php
$con = mysqli_connect("localhost", "root", "password", "loops");
if (!mysqli_connect_errno()) {
echo "Error to connect: ".mysqli_connect_error();
}
$firstName = $_POST['firstname'];
$lastName = $_POST['lastname'];
$age = $_POST['age'];
echo "First: ".$firstName."<br />Age: ".$age;
$sql = "INSERT INTO persons (FirstName, LastName, Age)
values (".$firstName.",".$lastName.",".$age.")";
if (!mysqli_query($con)) {
die("Error :".mysqli_error($con);
}
echo "1 added";
mysqli_close($con);
?>
I don't know what to do now, but the error seems to be on the '$sql', 'cause when I put that
under a comment, the rest works...
You forgot the infamous mistake of wrapping the varchar variables with single quote '
"INSERT INTO persons (FirstName, LastName, Age)
values ('".$firstName."','".$lastName."','".$age."')";
Additionally, It's highly risky for you, not be using protections against SQL Injections
Try this, mysqli_query($con, $sql) You need to execute the query so that it will store into the database
$sql = "INSERT INTO persons (FirstName, LastName, Age)
values ('".$firstName."','".$lastName."','".$age."')";
if (!mysqli_query($con, $sql)) {
...................^
die("Error :".mysqli_error($con);
}
Try this:
$sql = "INSERT INTO persons (`FirstName`, `LastName`, `Age`) values (".$firstName.",".$lastName.",".$age.")";
If this doesn't work, what error do you get.
I have following message box error, says Failed. these are my codes:
<?php
require('admin/connectdb.php');
if (isset($_POST['Sub']))
{
//get data from reservation form
$cutomername=$_POST['aname'];
$gender=$_POST['sex'];
$phoneno=$_POST['tel'];
$email=$_POST['email'];
$age=$_POST['age'];
$computerpart=$_POST['partcomp'];
$option1=$_POST['option1'];
$notes=$_POST['Notes'];
$query="INSERT INTO `assignmentwebprog`.`reservation` (`cumstomername`, `gender`, `phoneno`, `email`, `age`, `typeofcomputerpart`, `option`, `notes`)
VALUES ('$cutomername', '$gender', '$phoneno', '$email', '$age', '$computerpart', '$option1', '$notes')";
$qresult = mysql_query($query);
if ($qresult){
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
}
else
{
echo "<script type='text/javascript'>alert('failed!')</script>";
}
}
?>
up there is inserting value to phpmyadmin & every time i load/input then click enter then the page shows message box "failed"
these are my database:
<?php
$host="localhost"; // Host name
$username="root"; // username
$username="root"; // username
$db_name="assignmentwebprog"; //database name
$tbl_name="reservation";
// Replace database connect functions depending on database you are using.
mysql_connect("$host", "$username", "$password");
mysql_select_db("$db_name");
?>
currently my database is phpmyadmin, is there something missing with my code?
Check to see if the field in the database cumstomername is spelt correctly.
It should probably be customername
Passing the paramter
$cutomername=$_POST['aname'];
SQL
$query="INSERT INTO `assignmentwebprog`.`reservation` (`cumstomername`, `gender`, `phoneno`, `email`, `age`, `typeofcomputerpart`, `option`, `notes`)
VALUES ('$cutomername', '$gender', '$phoneno', '$email', '$age', '$computerpart', '$option1', '$notes')";
Change this line and try:
$qresult = mysql_query($query) or die(mysql_error());
check this :
$query="INSERT INTO reservation (cumstomername, gender, phoneno, email, age, typeofcomputerpart, option, notes)
VALUES ('$cutomername', '$gender', '$phoneno', '$email', '$age', '$computerpart', '$option1', '$notes')";
$qresult = mysql_query($query) or die(mysql_error());
You might have missing something in the $query which is mandatory for the table insertion.
First echo the query on the page. // echo $query ;
Then RUN the query in phpmyadmin and you will get the reason why it is not inserting in the table. See the error there.
I've created a registration form and I'm adding the data with php but for some reason it will not let me add the data into the database. Can you see anything wrong with this code?
<?php
mysql_connect("localhost", "root", "password") or die("No Connection");;
mysql_select_db("music") or die("No Database");;
$username= mysql_real_escape_string($_REQUEST["username"]);
$password= mysql_real_escape_string($_REQUEST["password"]);
$email= mysql_real_escape_string($_REQUEST["email"]);
$hash = md5( rand(0,1000) );
mysql_query("INSERT INTO members (id, username, password, email, hash, active) VALUES('', '$username', '$password', '$email', '$hash', '')") or die("Can't Add");
if(mysql_affected_rows()>0){
echo "1";
}else{
echo "2";
}
?>
I Keep getting a Can't Add error indicating that there is a simple problem with the mysql_query row
Thank you
Can't add is not an error, just a catch all statement you added at the end.
To see your actual problem, change your code at the end of the mysql_query line to include the actual error retrieved from mysql_error().
mysql_query("INSERT INTO members (username, password, email, hash, active) VALUES('$username', '$password', '$email', '$hash', '')")
or die("Can't Add - " . mysql_error());
That will give you more details regarding the error, if you post that, I can update my answer with the reason why.
Note that I've also removed the insertion of id, it's not needed if your column is AUTO_INCREMENT, which it should be.
if id is your primary key then replane '' with null
Make id as auto-incremented primary key and remove it from insert query.
there may be unique constraints for any of the column
Either have
mysql_query("INSERT INTO members (id, username, password, email, hash, active)
VALUES(null, '$username', '$password', '$email', '$hash', '')") or die("Can't Add");
^^^^
OR
mysql_query("INSERT INTO members (username, password, email, hash, active)
VALUES( '$username', '$password', '$email', '$hash', '')") or die("Can't Add");