mysql_query not sending form information to database - php

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));

Related

How to convert MySQL code into PDO statement?

I need to change the first if statement into a PDO statement but I'm not sure how to go about it. Please can someone help?
When users submit a form I want their email address to be pulled from the users table on the database into this page on the website, using the numbered $id they are assigned when they sign up.
$table = 'suggestions';
$id = (isset($_SESSION['u_id']) ? $_SESSION['u_id'] : null);
if ( NULL !== $id) {
$sql = mysqli_query($conn, "SELECT email FROM users WHERE u_id='$id'");
$fetch = mysqli_fetch_assoc($sql);
$email = $fetch['email'];
}
$email;
$optionOne = '';
$optionTwo = '';
$suggestions = selectAll($table);
if (isset($_POST['new-suggestion'])) {
global $conn;
$id;
$email;
$optionOne = $_POST['optionOne'];
$optionTwo = $_POST['optionTwo'];
$sql = "INSERT INTO $table (user_id, email, option_1, option_2) VALUES (?, ?, ?, ?)";
if (!empty($optionOne) && !empty($optionTwo)) {
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssss', $id, $email, $optionOne, $optionTwo);
$stmt->execute();
} else {
echo "All options must be entered";
}
}
Make a connection
Firstly you need to replace your mysqli connection with a PDO one (or at least add the PDO connection alongside the mysqli one!).
// Define database connection parameters
$db_host = "127.0.0.1";
$db_name = "name_of_database";
$db_user = "user_name";
$db_pass = "user_password";
// Create a connection to the MySQL database using PDO
$pdo = new pdo(
"mysql:host={$db_host};dbname={$db_name}",
$db_user,
$db_pass,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => FALSE
]
);
Updating your code
Prepared statements with mysqli and PDO
It's almost always better to use prepared statements when putting variable data into an SQL query. Not only is it safer (if the data comes from any sort of user generated input) but it also makes it easier to read, and easier to run multiple times with different values.
Prepared query with mysqli:
$sql = "SELECT column1, column2 FROM table WHERE column3 = ? AND column4 = ?";
$query = $mysqli->prepare($sql);
$query->bind_param("si", $string_condition, $int_condition);
$query->execute();
$query->store_result();
$query->bind_result($column1, $column2);
$query->fetch();
echo "Column1: {$column1}<br>";
echo "Column2: {$column2}";
Prepared query with PDO:
$sql = "SELECT column1, column2 FROM table WHERE column3 = ? AND column4 = ?";
$query = $pdo->prepare($sql);
$query->execute([$string_condition, $int_condition]);
$row = $query->fetchObject();
# $row = $query->fetch(); // Alternative to get indexed and/or associative array
echo "Column1: {$row->column1}<br>";
echo "Column2: {$row->column2}";
Updated code
// Using the NULL coalescing operator here is shorter than a ternary
$id = $_SESSION['u_id'] ?? NULL;
if($id) {
$sql = "SELECT email FROM users WHERE u_id = ?";
$query = $pdo->prepare($sql); // Prepare the query
$query->execute([$id]); // Bind the parameter and execute the query
$email = $query->fetchColumn(); // Return the value from the database
}
// Putting "$email" on a line by itself does nothing for your code. The only
// thing it does is generate a "Notice" if it hasn't been defined earlier in
// the code. Best use:
// - The ternary operator: $email = (isset($email)) ? $email : "";
// - The NULL coalescing operator: $email = $email ?? "";
// - OR initialize it earlier in code, before the first `if`, like: $email = "";
// N.B. Instead of "" you could use NULL or FALSE as well. Basically in this case
// anything that equates to BOOL(FALSE); so we can use them in `if` statements
// so the following (2 commented lines and 1 uncommented) are effectively
// interchangeable.
$email = $email ?? "";
# $email = $email ?? FALSE;
# $email = $email ?? NULL;
// Presumably you will also want to change this function to PDO and prepared statements?
// Although it doesn't actually do anything in the code provided?
$suggestions = selectAll($table);
// Same as with email, we're just going to use the NULL coalescing operator.
// Note: in this case you had used the third option from above - I've just
// changed it so there is less bloat.
$optionOne = $_POST['optionOne'] ?? "";
$optionTwo = $_POST['optionTwo'] ?? "";
$newSuggestion = $_POST['new-suggestion'] ?? "";
// There's no point nesting `if` statements like this when there doesn't appear to be any
// additional code executed based on the out come of each statement? Just put it into one.
// We now don't need to use empty etc. because an empty, false, or null string all.
// equate to FALSE.
if($newSuggestion && $id && $email && $optionOne && $optionTwo) {
// Not sure why you've made the the table name a variable UNLESS you have multiple tables
// with exactly the same columns etc. and need to place in different ones at different
// times. Which seems unlikely so I've just put the table name inline.
$sql = "INSERT INTO suggestions (user_id, email, option_1, option_2) VALUES (?, ?, ?, ?)";
$query = $pdo->prepare($sql);
$query->execute([$id, $email, $optionOne, $optionTwo]);
}
else{
echo "All options must be entered";
}
Without comments
$id = $_SESSION['u_id'] ?? NULL;
if($id) {
$sql = "SELECT email FROM users WHERE u_id = ?";
$query = $pdo->prepare($sql);
$query->execute([$id]);
$email = $query->fetchColumn();
}
$email = $email ?? "";
$suggestions = selectAll($table);
$optionOne = $_POST['optionOne'] ?? "";
$optionTwo = $_POST['optionTwo'] ?? "";
$newSuggestion = $_POST['new-suggestion'] ?? "";
if($newSuggestion && $id && $email && $optionOne && $optionTwo) {
$sql = "INSERT INTO suggestions (user_id, email, option_1, option_2) VALUES (?, ?, ?, ?)";
$query = $pdo->prepare($sql);
$query->execute([$id, $email, $optionOne, $optionTwo]);
}
else{
echo "All options must be entered";
}

Why does insert work only when calling the database twice?

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";
}
}
?>

Catchable fatal error: Object of class mysqli_result could not be converted to string on line 12

I'm getting this error for the following php code on line 12. I'm trying to insert data into a table and if it succeeds, redirect to another page after alert.
<?php
session_start();
include 'dbconn.php';
$name = $_POST["name"];
$hof = $_POST["hof"];
$tier = $_POST["tier"];
$services = $_POST["services"];
$proced = $_POST["proced"];
$addr = $_POST["addr"];
$phone = $_POST["phone"];
$depname = $_SESSION['depname'];
$qry = "INSERT INTO '.$depname.'(name,hof,tier,services,method,address,phone) VALUES ('$name','$hof','$tier','$services','$proced','$addr','$phone')"; //This is where the problem is;
if(mysqli_query($conn,$qry) === TRUE) {
echo "<script type='text/javascript'>alert('Success');
window.location='welcome.php';
</script>";
}
else{
echo "<script type='text/javascript'>alert('Error');
window.location='welcome.php';
</script>";
}
?>
In addition to what everyone else said this should fix your errors. You will still have security problems that you need to fix.
Also, I don't use mysqli I use PDO so you will have to forgive me if the syntax is slightly wrong.
Your problem is that mysqli_query() doesn't return a row. You need to need to fetch a row from your result and then assign it to $_SESSION['depname']
Login.php should look like this
// Note we are using prepared statements to prevent SQL injections
// Also note the use of backticks `, which are used for identifiers
$mysqli = new mysqli('host', 'user', 'password', 'database');
$stmt = $mysqli->prepare('SELECT `id`,`depname` FROM `admin` WHERE `username` = ? and password = ?');
$stmt->bind_param('ss', $myusername, $mypassword);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows == 1) {
session_start();
$row = $result->fetch_assoc();
$_SESSION['depname'] = $row['depname'];
header("location: welcome.php");
exit;
}
Other Script
<?php
session_start();
include 'dbconn.php';
$name = $_POST["name"];
$hof = $_POST["hof"];
$tier = $_POST["tier"];
$services = $_POST["services"];
$proced = $_POST["proced"];
$addr = $_POST["addr"];
$phone = $_POST["phone"];
$depname = $_SESSION['depname'];
$qry = "INSERT INTO `{$depname}` (`name`,`hof`,`tier`,`services`,`method`,`address`,`phone`) VALUES (?,?,?,?,?,?,?)";
// prepare our query to prevent sql injections
$stmt = $mysqli->prepare($qry);
$stmt->bind_param('sssssss', $name, $hof, $tier, $services, $proced, $addr, $phone);
$stmt->execute();
// not sure why you aren't using header here like #JayBlanchard said, but whatever
if($stmt->affected_rows == 1) {
echo "<script type='text/javascript'>alert('Success');
window.location='welcome.php';
</script>";
}
else
{
echo "<script type='text/javascript'>alert('Error');
window.location='welcome.php';
</script>";
}

Get id after insert and save it as value into another table

I am programming an App and I have a problem now.
When I register a new student with the app a Query runs on my php Script and insert the new student in my database.
What I want to do now is, when I am registering him, I want my php Script to run a multiple query so that all the other tables should be filled with NULL and the query should get the ID from the new created student to link it with the other tables(foreign key).
I tried it with mysqli_multiple_query and LAST_INSERT_ID() but both didn't work.
How would it be possible to get that id in return from my insert?
Here is my php script.
<?PHP
if ($_SERVER['REQUEST_METHOD']=='POST') {
$Name = $_POST['Name'];
$Surname = $_POST['Surname'];
$Street = $_POST['Street'];
$Hometown = $_POST['Hometown'];
if ($Name == '' || $Surname == '' || $Street== '' || $Hometown == '') {
echo 'please fill all values';
} else {
require_once('dbConnect.php');
$sql = "INSERT INTO T_Student(Name,Surname,Street,Hometown) VALUES('$Name','$Surname','$Street','$Hometown')";
$sql .= "INSERT INTO T_University(ID, Teacher, Subject , Classroom, F_ID_Student) VALUES ("","","","","",LAST_INSERT_ID())";
if(mysqli_multi_query($con,$sql)){
echo 'successfully registered';
} else {
echo 'oops! Please try again!';
}
}
mysqli_close($con);
}
echo "Data Inserted";
?>
I hope someone can help me.
Don't concatenate the two queries. Execute the first, save the last id into a variable like
$id = mysqli_insert_id();
, then execute the second query referencing the variable among the values.
Be aware that if those $_POST variables come from a user submitted form it would be useful to do some validation on them before saving them into database. Maybe this answer would be a nice read ;)
I have modify your code. Try and see if it works for you.
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$Name = $_POST['Name'];
$Surname = $_POST['Surname'];
$Street = $_POST['Street'];
$Hometown = $_POST['Hometown'];
if ($Name == '' || $Surname == '' || $Street== '' || $Hometown == '') {
echo 'please fill all values';
} else {
require_once('dbConnect.php');
$sql = "INSERT INTO T_Student(Name,Surname,Street,Hometown)VALUES('$Name','$Surname','$Street','$Hometown')";
mysqli_query($con, $sql);
$id = mysqli_insert_id($con);
if ($id) {
$sql = "INSERT INTO T_University(ID, Teacher, Subject , Classroom, F_ID_Student) VALUES (NULL, NULL, NULL, NULL, NULL, $id)";
mysqli_query($con, $sql);
}
}
mysqli_close($con);
}
echo "Data Inserted";
?>

PHP Registration Script, Inserting to Database not working

I have an issue with my PHP code for a registration form on my website. Some of the code doesn't get executed when the form is submitted.
if ($fnameError = "" && $emailError = "" && $userError = "" && $passError = "" && $cpassError = "" && $tickError = "") {
$con = mysqli_connect("localhost","root","","login")or die("Can't connect to database");
$user = $_POST['user'];
$pass = $_POST['pass'];
$name = $_POST['fname'];
$email = $_POST['email'];
$pwd = crypt('$pass', '$user');
$pwd = md5($pwd);
$tblname = "users";
$flp="INSERT INTO $tblname (Name, Username, Password, Email Address)
VALUES
('$name','$user','$pass','$email')";
$res = mysqli_query($con, $flp)or die("Can't insert to table");
if ($res) {
$complete = "Registered successfully please log in to continue";
} else {
echo "error";
}
}
Everything works fine until it gets to the line starting $flp="INSERT INTO...
Can anyone assist in helping me debug this code, also, please don't link to already written code I want to be able to use this code.
EDIT:
I changed a line to purposely cause an error so I know PHP is reading the line and it does give me the syntax error for the line starting $res=mysqli_...
"Parse error: syntax error, unexpected '$res' (T_VARIABLE) in C:\XamppNew\htdocs\site\regusr.php on line 85"
I removed the semi-colon at the end of the Insert line just to get the error.
EDIT:
I've managed to isolate the problem to the start of the if statement. It seems to be that the line doesn't treat each error as having no content. However, if the error exists it will be displayed on the page next to the form and no such error gets displayed.
Try this:
<?php
//if ($fnameError = "" && $emailError = "" && $userError = "" && $passError = "" && $cpassError = "" && $tickError = "")
//{
// Connect to DB
$mysqli = new mysqli("localhost", "root", "", "login");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
// Parse Input
$user = $mysqli->real_escape_string($_POST['user']);
$pass = $mysqli->real_escape_string($_POST['pass']);
$pwd = md5(crypt('$pass', '$user'));
$name = $mysqli->real_escape_string($_POST['fname']);
$email = $mysqli->real_escape_string($_POST['email']);
// Insert Record
if ($mysqli->query("INSERT INTO users (`Name`, `Username`, `Password`, `Email Address`) VALUES ('$name', '$user', '$pwd', '$email')")) {
printf ("New user has id %d.\n", $mysqli->insert_id);
} else {
printf("Failed to insert row: %s\n", $mysqli->error);
}
// Close DB Connection
$mysqli->close();
//}
?>
You need to quote (with backticks) your column name Email Address since it has a space in it.
Use backticks in Email Address field because it has space.
$flp="INSERT INTO $tblname (`Name`, `Username`, `Password`, `Email Address`)
Try this ..........
$flp="INSERT INTO $tblname (Name, Username, Password, EmailAddress)
VALUES
('".$name."','".$user."','".$pass."','".$email."')";

Categories