Why does insert work only when calling the database twice? - php

I was facing some problems with my database code. I used an insert query to insert my data from the form into my database called "wstorage". Only this method didn't work when I used the usual query " INSERT INTO users (nom, Prenom,..) VALUES ('$nom', '$Prenom'..).
In fact, the query did work but nothing showed on my database. Then I used another query where I call for the second time the name of my database 'wstorage'(the first time being in the session start and connection) and suddenly it works.
My question is : Why does it work when I normally don't have to call my database in the insert query?
This is my server.php code :
<?php
session_start();
$db = mysqli_connect('localhost','root','','wstorage');
if (mysqli_connect_errno()) {
echo 'Failled to connect to MYSQL: '.$mysqli_connect_errno();
}
// REGISTER USER
if (isset($_POST['registeruser'])) {
// receive all input values from the form
$nom = mysqli_real_escape_string($db, $_POST['nom']);
$Prenom = mysqli_real_escape_string($db, $_POST['Prenom']);
$Situation = mysqli_real_escape_string($db, $_POST['Situation']);
$sex = mysqli_real_escape_string($db, $_POST['sex']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$Nombre_Livre = mysqli_real_escape_string($db, $_POST['Nombre_Livre']);
$Nombre_Media = mysqli_real_escape_string($db, $_POST['Nombre_Media']);
$Nombre_Recidives = mysqli_real_escape_string($db, $_POST['Nombre_Recidives']);
$Etat_Abon = mysqli_real_escape_string($db, $_POST['Etat_Abon']);
$Penalite = mysqli_real_escape_string($db, $_POST['Penalite']);
$Etat_Penalite = mysqli_real_escape_string($db, $_POST['Etat_Penalite']);
$Numero = mysqli_real_escape_string($db, $_POST['Numero']);
$query = "INSERT INTO `wstorage`.`users` (`nom`, `Prenom`, `Situation`, `sex`, `email`, `Numero`, `Nombre_Livre`, `Nombre_Media`, `Nombre_Recidives`, `Etat_Abon`, `Penalite`, `Etat_Penalite`, `date`) VALUES ('$nom', '$Prenom', '$Situation', '$sex', '$email', '$Numero', '$Nombre_Livre', '$Nombre_Media', '$Nombre_Media', '$Etat_Abon', '$Penalite', '$Etat_Penalite', CURRENT_TIMESTAMP)";
mysqli_query($db, $query);
if($query) {
echo "success";
} else {
echo " Fail";
}
}
?>

Related

Just can't find what I did wrong php code

I am a novice trying to do the site for a non profit I volunteer with. Most of the code was gleened from You tube. Below is the code. The db name is cani the table is contact. When ever I submit is doesn't give me a success message, no data shows up in the database, and it doesn't return back to newentry.php. My brain hurts!
<?php
if (isset($_POST['submit'])){
include_once('dbh.inc.php');
$type = mysqli_real_escape_string($conn, $_POST['type']);
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$company = mysqli_real_escape_string($conn, $_POST['company']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$phone = mysqli_real_escape_string($conn, $_POST['phone']);
$add1 = mysqli_real_escape_string($conn, $_POST['add1']);
$add2 = mysqli_real_escape_string($conn, $_POST['add2']);
$city = mysqli_real_escape_string($conn, $_POST['city']);
$state = mysqli_real_escape_string($conn, $_POST['state']);
$zip = mysqli_real_escape_string($conn, $_POST['zip']);
$sql = "INSERT INTO contact (contact_type, contact_first, contact_last, contact_company, contact_email, contact_phone, contact_add1, contact_add2, contact_city, contact_state, contact_zip) VALUES ('$type', '$first', '$last', '$company', '$email', '$phone', '$add1', '$add2', '$city', '$state', '$zip')";
mysqli_query($conn, $sql);
header("Location: ../newentry.php?Success!");
}else{
header("Location: ../index.html");
exit();
}
?>
Grr I partially fixed it...now everything works, except nothing is showing up in the database...it is connecting, I made sure the table name is correct. It says success. But whe I open phpAdmin and open the table, it is blank.
Check if the variable $_POST['submit'] exists

Registration page with PHP & MySQL

I have a registration page, which is tied to this process.php code below. When I run this code, it returns "Error". Did I make a mistake somewhere?
<?php
require_once ('newmeowconnection.php');
if (isset($_POST['form_input']) && $_POST['form_input'] == 'registration') {
registerUser();
}
function registerUser() {
$query = "INSERT INTO users (first_name, last_name, email, password, created_at, updated_at)
VALUES('{$_POST['first_name']}','{$_POST['last_name']}','{$_POST['email']}', '{$_POST['password']}', NOW(), NOW())";
$run = mysqli_query($query);
if ($run) {
$_SESSION['loggedin'] = TRUE;
$_SESSION['user'] = $_POST['email'];
header('Location: http://localhost/homepage.php');
} else {
echo 'Error';
}
}
?>
mysqli_query need run on connection object or pass connection to it:
$run = mysqli->query($connection, $query);
or
$run = $connection->query($query);
The problem is you are using single quotes-inside single-quotes. For instance '{$_POST['first_name']}' is read as {$_POST[ being one thing first_name as a SQL variable and ]} another string.
Try the following
...
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO users (first_name, last_name, email, password, created_at, updated_at) VALUES('{$first_name}','{$last_name}','{$email}', '{$password}', NOW(), NOW())";
...

mysql_query not sending form information to database

I can't seem to figure out why my form data isn't being sent to the database. I've tried multiple variations of coding and this is the only one where I could get a "result"
here's my code:
<?php
#if the submit button has be selected...
if(isset($_POST['submit_registration'])) {
# assign variables to each form control to capture the values
$first = $_POST['first_name'];
$last = $_POST['last_name'];
$email = $_POST['email'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$phone = $_POST['phone'];
$distance = $_POST['distance'];
# assign null to values for use with isset function to identitfy required fields with no value
$nofirst = null;
$nolast = null;
$noemail = null;
$noaddress1 = null;
$noaddress2 = '';
$nocityErr = null;
$nostate = null;
$nozipcode = null;
$nophone = null;
$nodistance = null;
# if value of variable for required field is nothing, assign something other than null to $no variable
if($first == "") {$nofirst = '';}
if($last == "") {$nolast = ''; if($email == "") {$noemail = '';}
if($address1 == "") {$noaddress1 = '';}
if($address2 == "") {$noaddress2 ='';}
if($city == "") {$nocity = '';}
if($state == "") {$nostate = '';}
if($zipcode == "") {$nozipcode = '';}
if($phone == "") {$nophone = '';}
else {
$insertsql = "INSERT INTO `runner`(`fname`, `lname`, `email`, `address1`, `address2`, `city`, `state`, `postalcode`, `phone`, `distance`)
VALUES ('$first','$last','$email','$address1','$address2','$city','$state','$zipcode','$phone','$distance')";
echo $insertsql;
mysql_query($lrconnect, $insertsql) or die("Insert failed ". mysql_error($lrconnect));
echo "connected";
$inserted = '';
}
}
?>
Here's my the error I get:
INSERT INTO `runner`(`fname`, `lname`, `email`, `address1`, `address2`, `city`, `state`, `postalcode`, `phone`, `distance`) VALUES ('Crystal','Yang','cykher#gmail.com','55555 Avenue','','Chicago','FL','39485','5555555555','5K')
Insert failed
Using mysqli_query functions, you would put the connection first as you have. However, you are using mysql_query instead which puts the query first and the connection second.
http://php.net/manual/en/function.mysql-query.php
As mentioned in the comments, though, you really should not be just inserting data that users submit through $_POST directly into the database. Also mentioned in the comments, you should be using mysqli_* instead. This would have made your syntax correct.
There's not a lot of work to do to convert it to mysqli. Basically you just add an i on to the end of each place where you'd normally call mysql. You'd also switch the connection and query to have the connection come first, as you have in your code. Finally, your connection takes a 4th parameter now instead of 3, which is nice because you don't need a separate call to specify which database you want to use.
Here's an example:
<?php
$link = mysqli_connect('HOST', 'USER', 'PASS', 'DATABASE');
$q_test = "SELECT id FROM table";
$r_test = mysqli_query($link, $q_test) or trigger_error("Cannot Get ID: (".mysqli_error().")", E_USER_ERROR);
while ($row_test = mysqli_fetch_array($r_test)) {
print "ID: ".$row_test['id'];
}
No need to use connection with mysql_query function.
If you are using mysqli_query function than you must have to use connection parameter in that function.
so solution of your problem is.
mysql_query($insertsql) or die("Insert failed ". mysql_error($lrconnect));

PHP is inserting two duplicate rows in MYSQL database

I am having trouble with PHP and MYSQL. I have an HTML form which when submitted runs the following PHP script.The problem is that the following PHP code is inserting the data into the database twice. I think it is something to do with the following PHP and not the database:
<?php
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$display_name = $_POST['displayname'];
$email = $_POST['email'];
$password = $_POST['password'];
$add_line1 = $_POST['addline1'];
$add_line2 = $_POST['addline2'];
$city = $_POST['city'];
$county = $_POST['county'];
$postcode = $_POST['postcode'];
$sql = "INSERT INTO members (memberID,
memberPassword,
memberFirstName,
memberLastName,
memberAddressLine1,
memberAddressLine2,
memberCity,
memberCounty,
memberPostcode,
memberDisplayName)
VALUES ('$email',
'$password', '$first_name', '$last_name',
'$add_line1', '$add_line2','$city',
'$county', '$postcode', '$display_name')";
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error($conn));
}
mysqli_query($conn,$sql);
echo 'Guest Added';
mysqli_close($conn);
?>
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error($conn));
}
mysqli_query($conn,$sql);
You have mysqli_query($conn,$sql); in your code twice. Once in the if(), and once outside. Each of these will insert into your database.
The point to note here is that the mysqli_query inside the if is evaluated - that is, it is run and the if statement executes on the result of the function call. Thus, you do not need to call it again.
Tushar pointed out the twin mysqli queries and he is right, besides that, the code as is now will cause you security troubles since it allows sql injection...
Please modify your code as follows:
$first_name = mysqli_escape_string($conn, $_POST['firstname']);
$last_name = mysqli_escape_string($conn, $_POST['lastname']);
$display_name = mysqli_escape_string($conn, $_POST['displayname']);
$email = mysqli_escape_string($conn, $_POST['email']);
$password = mysqli_escape_string($conn, $_POST['password']);
$add_line1 = mysqli_escape_string($conn, $_POST['addline1']);
$add_line2 = mysqli_escape_string($conn, $_POST['addline2']);
$city = mysqli_escape_string($conn, $_POST['city']);
$county = mysqli_escape_string($conn, $_POST['county']);
$postcode = mysqli_escape_string($conn, $_POST['postcode']);

SQL first entry not adding to database

Could someone please help with the code below. I am trying to create a registration query, however when it is submitted, I get an error for the following line:
$insert_query = "insert into members (First_name, last_name, Address_1, Address_2, Postcode, Email, Membership_Number, Password) values('$fname','$lname','$address1','$address2','$postcode','$email','$member','$password')";
This is only affecting the first_name, as the other field names are successfully submitted.
Your help would be much appreciated!!
<?php
$con = mysql_connect("localhost","root","") or die(mysql_error());
$select_db = mysql_select_db("thistlehc",$con);
if(isset($_POST['register']))
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$address1 = mysql_real_escape_string($_POST['address1']);
$address2 = mysql_real_escape_string($_POST['address2']);
$postcode = mysql_real_escape_string($_POST['postcode']);
$email = mysql_real_escape_string($_POST['email']);
$member = mysql_real_escape_string($_POST['member']);
$password = mysql_real_escape_string($_POST['password']);
$query = "select membership_number from members where membership_number='$member'";
$link = mysql_query($query)or die(mysql_error());
$num = mysql_num_rows($link);
if ($num>0){
echo 'Membership Number already exists'; //Membership number already taken
}
else {
$insert_query = "insert into members (First_name, last_name, Address_1, Address_2, Postcode, Email, Membership_Number, Password) values('$fname','$lname','$address1','$address2','$postcode','$email','$member','$password')";
$result = mysql_query($insert_query)or die(mysql_error());
echo "Registered Successfully!";
}
?>
Look's to me like you forgot to encapsulate the contents of your if statement.
if(isset($_POST['register']))
Because it doesn't have curly brackets around the code to be executed, only the first line immediately after is executed. In your case, the if statement seemingly returned false, and the line defining $fname was not executed, hence an undefined variable.
You want to use something similar to this -
if(isset($_POST['register'])){
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$address1 = mysql_real_escape_string($_POST['address1']);
...
}

Categories