adding data with PHP to the db is not working - php

I'm using MAMP an my PHP won't add data to the db
I have looked at other similar questions and done everything on them, yet it still is not working.
I am using MAMP and I've done everything right as far as I know but the problem is the same no matter what I do.
<?php
require_once('dbconnect.php');
$email = $_GET['email'];
$name = $_GET['name'];
$message = $_GET['message'];
$my_query = "";
$my_query = "select * from Users where email = '$email' ";
$my_query = "INSERT INTO Users (email, name, message) VALUES ('$email', '$name', '$message')";
$result = mysqli_query($connection, $my_query );
if($result)
{
echo "Successfully Sent!";
}
else
{
echo "<b>ERROR: unable to post </b>";
}
}
mysqli_close();
?>

Here use this code and and tell what is the error
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform a query, check for error
if (!mysqli_query($con,"INSERT INTO Users (email, name, message) VALUES ('$email', '$name', '$message')"))
{
echo("Error description: " . mysqli_error($con));
}
mysqli_close($con);
?>
if you dont get any error or blank value in db use your values like
values('".$email."', '".$name."', '".$message."')"
in db It will be executed like values('test.abc.com', 'abc', 'It is working')

Related

MySQL Entry to Database Not Working

I'm going through a course on MySQL, and I'm learning how to make a user entry bit of code (email and password) where the info in the script will be put into the database on phpMyAdmin. I can't seem to get it to work? My code doesn't have any errors when I put it through an error checker. I'm also completely new to PHP and MySQL. I know it can find the database, because I can update existing data.
<?php
$link = mysqli_connect("host", "username", "password", "username");
if (mysqli_connect_error()) {
die ("There was an error connecting to the database");
}
$query = "INSERT INTO `users` (`email`, `password`) VALUES('email', 'password')";
mysqli_query($link, $query);
$query = "SELECT * FROM users";
if ($result = mysqli_query($link, $query)) {
$row = mysqli_fetch_array($result);
echo "Your email is ".$row[1]." and your password is ".$row[2];
}
?>
Created a refined version. Check it.
<?php
$link = mysqli_connect("host", "username", "password", "username");
if (mysqli_connect_error()) {
die ("There was an error connecting to the database");
}
$query = "INSERT INTO `users` (`email`, `password`) VALUES('email', 'password')";
$result = mysqli_query($link, $query);
if($result != false)
{
echo "The record has been successfully inserted.<br>";
}
else
{
echo "Error Occured in the INSERT query.<br>Error : ".mysqli_error($link);
}
$query = "SELECT * FROM users";
$result = mysqli_query($link, $query);
if($result != false)
{
echo mysqli_num_rows($result)." Records found.<br>";
while($rows = mysqli_fetch_array($result))
{
echo $rows["email"]."<br>";
}
}
else
{
echo "Error Occured in the SELECT query.<br>Error : ".mysqli_error($link);
}
mysqli_close($link);
?>
Update
It turns out I didn't set the auto_increment setting, therefore making the way I set up my database incorrect! He set up another database in the tutorials I was going through, and I found out that as he did it. Thank you everyone for the effort to help me solve my problem!
Why you don't try receiving them with php?
And simply make
$email= $POST['email']
$password= $POST['password']
And change the query to
$query = "INSERT INTO `users` (`email`, `password`) VALUES(" .$email. ", ". $password.")";

Combining all INSERT statements into one

I'm creating a page for a class and I have lots of different while loops with lots of different INSERT statements. I didn't think there would be a problem with that until I discovered that they weren't being inputed right. They were all inputed but what happened was that they were all inputed in separate rows as opposed to being one entry across their individual columns. I need it so that all of the INSERT statements are combined into one while still checking to make sure that the full name isn't yet in the database. Please help me rewrite my code so that it can do just that.
Here is the code that needs to be rewritten so that it just has one INSERT statement:
<?php
$con = mysql_connect("localhost","a7068104_user2","wiseguy1345");
if(!$con) {
die("could not connect to localhost:" .mysql_error());
}
header("refresh:1.5; url=NamesAction.php");
mysql_select_db("a7068104_world") or die("Cannot connect to database");
$name = mysql_real_escape_string($_POST['firstname']);
$query = "SELECT * FROM names_1 WHERE firstname='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your first name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (firstname) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your first name was successfully added to the database!";
}
else{
echo "Your first name couldn't be added to the database!";
}
}
$name = mysql_real_escape_string($_POST['lastname']);
$query = "SELECT * FROM names_1 WHERE lastname='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your last name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (lastname) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your first name was successfully added to the database!";
}
else{
echo "Your first name couldn't be added to the database!";
}
}
$name = mysql_real_escape_string($_POST['firstname'] . " " . $_POST['lastname']);
$query = "SELECT * FROM names_1 WHERE fullname='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your full name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (fullname) VALUES('$name')";
$result = mysql_query($query);
}
$age = mysql_real_escape_string($_POST['age']);
$query = "INSERT INTO names_1 (age) VALUES('$age')";
$result = mysql_query($query);
if($result) {
echo "Your name was successfully added to the database!";
}
else {
echo "Your name couldn't be added to the database!";
}
mysql_close($con);
?>
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>Names</h1>
<p>You will be redirected back to the <b>Names</b> page in a moment.</p>
<?php include("Footer.php");?>
</div>
</body>
</html>
When inserting a row with multiple columns you can just combine the two groups of keys and values like so:
INSERT INTO names_1 (firstname, lastname) VALUES ('John', 'Smith')
The other alternative is in your database mark both the Firstname and Lastname as Unique columns. Then you can do the following.
INSERT INTO names_1 (firstname, lastname) VALUES ('John', 'Smith') ON DUPLICATE KEY UPDATE names_1 SET x="blah" WHERE blah
http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html
This should accomplish what you are setting out to do.
<?php
$con = mysql_connect("localhost","a7068104_user2","wiseguy1345");
if(!$con) {
die("could not connect to localhost:" .mysql_error());
}
header("refresh:1.5; url=NamesAction.php");
mysql_select_db("a7068104_world") or die("Cannot connect to database");
$fullname = mysql_real_escape_string($_POST['firstname'] . " " . $_POST['lastname']);
$query = "SELECT * FROM names_1 WHERE fullname='" . $fullname . "'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your full name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (firstname, lastname, fullname, age) VALUES('" . $_POST['firstname'] . "','" . $_POST['lastname'] . "','" . $fullname . "'," . $_POST['age'] . ")";
$result = mysql_query($query);
}
mysql_close($con);
?>
<html>
<head>
<link rel="stylesheet" href="Site.css"/>
<?php include("Header.php"); ?>
</head>
<body>
<div id="main">
<h1>Names</h1>
<p>You will be redirected back to the <b>Names</b> page in a moment.</p>
<?php include("Footer.php");?>
</div>
</body>
</html>

Before I send my form, check if the maakartikel extends in my database

My PHP Code:
I want that before I send my form it will check if the maakartikel extends in my database. If it already extends it has to give a error with: This maakartikel extends. If it doesn't it have to add it to the database.
<?php
$con = mysqli_connect("localhost", "csa", "csa", "csa");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL:" . mysqli_connect_error();
}
$sql= "INSERT INTO mart (Maakartikel, Omschrijving)
VALUES
('$_POST[maakartikel]', '$_POST[omschrijving]') ";
if (!mysqli_query($con, $sql))
{
die('Error:' . mysqli_errno($con));
}
echo "1 record added";
mysqli_close($con);
?>
Try this....
<?php
$con = mysqli_connect("localhost", "csa", "csa", "csa");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL:" . mysqli_connect_error();
}
// first check in databse befor to insert Maakartikel
$check_record = "SELECT * from mart where Maakartikel = '$_POST[maakartikel]'";
$query_execute = mysqli_query($check_record);
$num_rows = mysqli_num_rows($query_execute);
if ($num_rows > 0) {
echo "Error: This maakartikel extends";
exit();
} else {
//if not found in database then insert record.
$sql = "INSERT INTO mart (Maakartikel, Omschrijving)
VALUES
('$_POST[maakartikel]', '$_POST[omschrijving]') ";
if (!mysqli_query($con, $sql)) {
die('Error:' . mysqli_errno($con));
}
echo "1 record added";
}
mysqli_close($con);
?>
try following solution
first write "select" query to check weather record exits or not
if record exits then donot insert else insert data in table
for example
$select= mysql_query("select * from table where name='xyz'");
$count = mysql_num_rows($select)
if($count>1)
{
echo "already exits";
}
else
{
// insert record
}
Note : here i have used mysql functions not mysqli set so you can change whatever the functions regarding as dont know much of mysqli
Look into NOT EXISTS. You can use this with your insert statement so it doesn't insert a duplicate.
$check = "select maakartikel from your_table_name";
$res = mysqli_query($check);
if($res->rowCount() > 0){
$sql= "INSERT INTO mart (Maakartikel, Omschrijving)
VALUES
('$_POST[maakartikel]', '$_POST[omschrijving]') ";
if (!mysqli_query($con, $sql))
{
die('Error:' . mysqli_errno($con));
}
echo "1 record added";
}else {
echo "record already exist";
}

Display error if the email address entered in form already exists

How do I use "emailaddress" as the only duplicate entry that provides a error?
A lot of the answers I've found use mysql_query but I want to use mysqli.
<?php
$con=mysqli_connect("localhost","","","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO entry (firstname, lastname, emailaddress, favoritesong) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[emailaddress]','$_POST[favoritesong]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
WARNING! the posted code and this answer (as i am only addressing the question now) contain big SQL injection leaks. Please read up on SQL injection and use escaping or prepared statements.
<?php
$con = mysqli_connect("localhost", "", "", "");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$existsQuery = "select count(*) as count from entry where emailaddress like '".$_POST[emailaddress]."'";
$existsResult = mysqli_query($con, $existsQuery);
if($existsResult->fetch_object()->count > 0)
{
echo "email already exist";
}
else
{
$sql = "INSERT INTO entry (firstname, lastname, emailaddress, favoritesong) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[emailaddress]','$_POST[favoritesong]')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
mysqli_close($con);
?>
simply make emailaddress unique in your table.

Do Not Duplicate VALUE if already exist on MySQL

I've been trying to accomplish this, but as other issues I just can't figured it out. I've been reading around for posibles solutions but non of them goes along with my code, or if they do I can't figure out how or where to use them.
I have a DB where a user sends records. The database consist in few tables containing the Following "Name, Lastname, Phone". If any of this values is duplicate, I would like my code to identify and Ignore the submission of the Form if ALL this VALUES already exist on the DB.
Here is my code:
<?php
$con = mysql_connect("HOST","USER","PASS");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("testdb", $con);
$sql="INSERT INTO people (Name, LastName, Phone)
VALUES
('$_POST[Name]','$_POST[LastName]','$_POST[Phone]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Record Added";
mysql_close($con);
?>
The mysql_* function are all deprecated now, and should NEVER be used. change your code to do something like the following:
//Set up a PDO connection to MySQL
$host = 'host_name';
$dbname = 'database_name';
$user = 'user_name';
$pass = 'user_pass';
try
{
$DB = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
//Determine whether the appropriate values have been passed.
if(isset($_POST['Name']))
{
$name = $_POST['Name'];
}
else
{
echo "You must provide a name!";
exit; //This may not be what you want to do here, it's an example action
}
if(isset($_POST['LastName']))
{
$name = $_POST['LastName'];
}
else
{
echo "You must provide a last name!";
exit; //This may not be what you want to do here, it's an example action
}
if(isset($_POST['Phone']))
{
$name = $_POST['Phone'];
}
else
{
echo "You must provide a phone number!";
exit; //This may not be what you want to do here, it's an example action
}
//Set up the query using anonymous values
$sql="INSERT INTO people (Name, LastName, Phone) VALUES ('?','?','?')";
$sth = $DB->prepare($sql);
try
{
//Attempt to execute the insert statement
$sth->execute(array($_POST[Name], $_POST[LastName], $_POST[Phone]));
echo "Record Added";
}
catch(PDOException $e)
{
//If the insert failed, then you can handle the error, and determine
//what further steps need to be taken.
echo "Record Not Added";
}
Here's another question with a similar setting, that may also be useful to you:
https://stackoverflow.com/a/10414922/1507210
search in the table before insert
<?php
$con = mysql_connect("HOST","USER","PASS");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("testdb", $con);
$name = mysql_real_escape_string($_POST[Name]);
$LastName= mysql_real_escape_string($_POST[LastName]);
$Phone= mysql_real_escape_string($_POST[Phone]);
$search_res=mysql_query("SELECT * from people where Name='$Name' OR LastName='$LastName' OR Phone='$Phone'");
if(mysql_num_rows($search_res) < 1){
$sql="INSERT INTO people (Name, LastName, Phone)
VALUES
('$Name','$LastName','$Phone')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Record Added";
}else{
echo "User Already exits";
}
mysql_close($con);
?>
Try this easy solution
$result = mysql_query("SELECT * FROM TABLE WHERE Column = 'value' ");
if( mysql_num_rows($result) < 1) {
mysql_query("INSERT INTO table (column) VALUES ('value') ");
}

Categories