Insert User Data to Database with INSERT statement - php

From a user form: I am trying to insert the following data:
1) First Name 2) Last Name 3) Major 4) Graduation Year
I am able to connect to the database, and select the database I need--but I am unable to insert the data from the form. I am able to create records, but the data is not being saved to the database. Basically, right now I'm creating blank forms.
The variable $uInput holds the user data. I tried passing $uInput into the function doAction(), but I believe that is where the problem is. I'm trying to figure out how to pass the user data into the function doAction().
<?php
//Call function mainline
mainline();
// Declare the function mainline
function mainline() {
$uInput = getUserInput();
$connectDb = openConnect(); // Open Database Connection
selectDb($connectDb); // Select Database
doAction($uInput);
//closeConnect();
//display();
}
//Declare function getUserInput ------------------------------------------------------------------------------------
function getUserInput() {
echo "In the function getUserInput()" . "<br/>";
// Variables of User Input
$idnum = $_POST["idnum"]; // id (NOTE: auto increments in database)
$fname = $_POST["fname"]; // first name
$lname = $_POST["lname"]; // last name
$major = $_POST["major"]; // major
$year = $_POST["year"]; // year
$action = $_POST["action"]; // action (select, insert, update, delete)
$userInput = array($idnum, $fname, $lname, $major, $year, $action);
//echo "info from getUserInput: " . $action;
return $userInput;
}
function doAction($pUserInput) {
// if user selects INSERT from dropdown menu, then call function insert
//and pass $uInput
if ($pUserInput[5] == "ins") {
insert($uInput);
}
}
// Create a database connection --------------------------------------------------------
function openConnect() {
$connection = mysql_connect("localhost", "root_user", "password");
echo "Opened Connection!" . "<br/>";
if(!$connection) {
die("Database connection failed: " . mysql_error());
}
return $connection;
}
// Select a database to ----------------------------------------------------------------
function selectDb($pConnectDb) {
$dbSelect = mysql_select_db("School", $pConnectDb);
if(!$dbSelect) {
die("Database selection failed: " . mysql_error());
} else {
echo "You are in the School database! <br/>";
}
}
// function insert ---------------------------------------------------------------------
function insert($pUInput) {
$sql="INSERT INTO tblStudents (first_name, last_name, major, year)
VALUES
('$pUInput[1]','$pUInput[2]','$pUInput[3]', '$pUInput[4]')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
}
?>

Your doAction() function is buggy. You are taking the parameter into the function as $pUserInput but sending to the insert() function as $uInput.
You should do it like this:
function doAction($pUserInput)
{
// if user selects INSERT from dropdown menu, then call function insert
//and pass $uInput
if ($pUserInput[5] == "ins")
{
insert($pUserInput); // <-- FIXED: Not using correct parameter.
}
}

Change insert($uInput); function to insert($pUserInput);

Related

INSERT not complete before SELECT query

I have a PHP script that is split into two separate PHP scripts (As they each serve a purpose and are quite lengthy). For simplicity let's call these 1.php and 2.php.
Script 1.php does an API call to a website passes the payload to a function. Once has truncated and inserted the new records into the table, it then includes the 2nd script. This is where the issue begins. Seemingly when I query the marketPlace table it returns a null array however if I insert a sleep(1) before I include 2.php it works! I can only summize that somehow the truncate and insert queries in 1.php had not completed before the next queries were called? (I've never come across this before!).
There is only one database connection and is defined by a database class which is contained in 1.php:
class Database
{
// This class allows us to access the database from any function with ease
// Just call it with Database::$conn
/** TRUE if static variables have been initialized. FALSE otherwise
*/
private static $init = FALSE;
/** The mysqli connection object
*/
public static $conn;
/** initializes the static class variables. Only runs initialization once.
* does not return anything.
*/
public static function initialize()
{
Global $servername;
Global $username;
Global $password;
Global $dbname;
try {
if (self::$init===TRUE)return;
self::$init = TRUE;
self::$conn = new mysqli($servername, $username, $password, $dbname);
}
catch (exception $e) {
date('Y-m-d H:i:s',time()) . " Cant' connect to MySQL Database - re-trying" . PHP_EOL;
}
}
public static function checkDB()
{
if (!mysqli_ping(self::$conn)) {
self::$init = FALSE;
self::initialize();
}
}
}
The function that trunctated and inserted into the marketplace is:
function processMarketplace($marketData) {
// Decode to JSON
$outputj = json_decode($marketData, true);
$marketplaceCounter = 0;
// Check for success
if (($outputj['success']==true) && (!stristr($marketData, "error"))) {
// Create the blank multiple sql statement
$sql = "TRUNCATE marketplace;"; // Clears down the current marketPlace table ready for new INSERTS
//Loop through each multicall
foreach ($outputj['multiCall'] as $orderBook) {
foreach ($orderBook['marketplace'] as $orderLine) {
$type = $orderLine['type'];
$price = $orderLine['amountCurrency'];
// Add new SQL record (This ignores any duplicate values)
$sql .="INSERT IGNORE INTO marketplace (type, price) VALUES ('" . $type . "'," . $price . ");";
}
$marketplaceCounter++;
}
// Now run all the SQL's to update database table
if (strlen($sql) > 0) {
if (Database::$conn->multi_query($sql) === TRUE) {
echo mysqli_error(Database::$conn);
//echo "New records created successfully";
} else {
echo mysqli_error(Database::$conn);
echo "Error: " . $sql . "<br>" . Database::$conn->error;
}
}
echo date('Y-m-d H:i:s',time()) . " == Marketplace Orderbook retreived == <BR><BR>" . PHP_EOL;
} else {
echo date('Y-m-d H:i:s',time()) . " Failed to get Marketplace data. Output was: " . $marketData . "<BR>" . PHP_EOL;
die();
}
}
I've chased this around for hours and hours and I really don't understand why adding the sleep(1) delay after I have called the processMarketplace() function helps. I've also tried merging 1.php and 2.php together as one script and this yields the same results. 2.php simply does a SELECT * FROM marketPlace query and this returns NULL unless i have the sleep(1).
Am I missing something easy or am I approaching this really badly?
I should add I'm using InnoDB tables.
This is how its called in 1.php:
$marketData = getData($user,$api); // Get Marketplace Data
processMarketplace($marketData); // Process marketplace data
sleep(1); // Bizzare sleep needed for the select statement that follows in 2.php to return non-null
include "2.php"; // Include 2nd script to do some select statements on marketPlace table
2.php contains the following call:
$typeArray = array('1','2','3');
foreach ($typeArray as $type) {
initialPopulate($type);
}
function initialPopulate($type) {
// Reset supplementary prices
mysqli_query(Database::$conn, "UPDATE marketPlace SET price_curr = '999999' WHERE type='" . $type . "'");
echo mysqli_error(Database::$conn);
// Get marketplace data <--- This is the one that is strangely returning Null (after the first loop) unless I place the sleep(1) before including 1.php
$query = "SELECT * FROM marketPlace WHERE type='" . $type . "'";
$result = mysqli_query(Database::$conn, $query);echo mysqli_error(Database::$conn);
$resultNumRows = mysqli_num_rows($result);echo mysqli_error(Database::$conn);
// Create array from mysql data
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
// Get information from the offertypes table
$query2 = "SELECT offerID FROM queryTypes WHERE type='" . $type . "'";
$result2 = mysqli_query(Database::$conn, $query2);echo mysqli_error(Database::$conn);
// Create array from mysql data
$rows2 = array();
while($r2 = mysqli_fetch_row($result2)) {
$rows2[] = $r2;
}
// Loop through marketplace data and apply data from the offertypes table
$sql1 = ""; // Create a blank SQL array that we will use to update the database
$i = 0;
foreach ($rows as $row) {
$sql1 .= "UPDATE marketPlace SET enrichmentType = " . $rows2[$i][0] . " WHERE type='" . $type . "';";
$i++;
}
// Now run all the SQL's to update database table
if (strlen($sql1) > 0) {
if (Database::$conn->multi_query($sql1) === TRUE) {
echo mysqli_error(Database::$conn);
//echo "New records created successfully";
} else {
echo mysqli_error(Database::$conn);
echo "Error: " . $sql1 . "<br>" . Database::$conn->error;
}
}
}
You are using mysqli:multi_query.
Unlike query, multi_query does not retrieve the results immediately. Retrieving the results must be done using mysqli::use_result
An example from the documentation:
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->use_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->close();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
You don't need to print the results, but if you don't retrieve them, you are not guaranteed the INSERT has completed.
Note in the documentation for use_result at
https://www.php.net/manual/en/mysqli.use-result.php
it states
"Either this or the mysqli_store_result() function must be called
before the results of a query can be retrieved, and one or the other
must be called to prevent the next query on that database connection
from failing."
As a result of not calling store_result or use_result, you are having unpredictable results.

Insert query gives "Couldn't fetch mysqli_stmt" warning but sends still data to database

I have a form with 2 drop down lists. Both with values from database tables.
When a visitor submits then the next things will occure:
A select query will compare the choices (id's)/POST values with the values (id's) in the database tables. The query will be fetched in the while loop. In the while loop is a if-else which controls if the values are equal to each other. When they are then run else.
In else there is the insert query which saves the values (id's) in a new database table.
I use prepared statements for both the select and the insert queries.
After fetching the select query I close it in else ($selControl->close();) and start the 2nd query (insert).
When I run the website with a submit then I get the error "Couldn't fetch mysqli_stmt" for the select query. But still it works and inserts into the DB table.
When I write $selControl->close(); (inclusive/exclusive $insKeuze->close(); from insert) after } of the 3rd else or after } after while then I get the error that the 1st query must be closed before a new prepare statement (that's logic).
Without a close statement gives also a "close-before-prepare" error.
I updated my code.
I added bind_param. It sends the data to the database, but gives the error.
What do I need to do to stop the error?
If someone can help me, thanks in advance!
The code: insert.php
<?php
// Include database configuration file
include ("dbConfig.php");
$kLand = $_POST["landen"];
$kGerecht = $_POST["gerechten"];
// If submit and landKeuze is not empty and gerechtKeuze is not empty
// --> control and validate the values and send to database.
if (isset($_POST["submit"]) && !empty($kLand) && !empty($kGerecht))
{
// If query is prepared then execute the query.
// Query to select data from table landen with inner join table gerechten.
if ($selControl = $mysqli->prepare("SELECT landen.land_id, gerechten.gerecht_id FROM landen INNER JOIN gerechten ON landen.land_id = gerechten.land_id WHERE landen.land_id = ? AND gerechten.gerecht_id = ?"))
{
$selControl->bind_param("ii", $kLand, $kGerecht);
if (!$selControl->execute())
{
echo "Failed to execute the query controle: " . $mysqli->error;
}
else
{
$selControl->bind_result($lLand_id, $gGerecht_id);
while ($selControl->fetch()) // <-- Coudn't fetch
{
// If selected land (land_id) is not the same as land_id in table landen
// or selected gerecht (gerecht_id) is not the same as gerecht_id in table gerechten --> send echo.
if ($kLand != $lLand_id || $kGerecht != $gGerecht_id)
{
// Message when the combination is not correct
echo "<script>alert('Deze combinatie bestaat niet. Doe een nieuwe poging!');</script>";
}
// Else insert the selected values in table landGerecht.
else
{
$selControl->close();
// If query is prepared --> bind the columns and execute the query.
// Insert statement with placeholders for the values to database table landGerecht
if ($insKeuze = $mysqli->prepare("INSERT INTO lab_stage_danush . landGerecht (land_id, gerecht_id) VALUES ( ?, ?)"))
{
// Bind land_id and gerecht_id as integers with $landKeuze and $gerechtKeuze.
$insKeuze->bind_param('ii', $kLand, $kGerecht);
// If statement is not executed then give an error message.
if (!$insKeuze->execute())
{
echo "Failed to execute the query keuze: " . $mysqli->error;
}
$insKeuze->close();
}
// Else give an error message.
else
{
echo "Something went wrong in the query keuze: " . $mysqli->error;
}
}
}
}
}
else
{
print_r($mysqli->error);
}
// After sent to database go back to keuze.php.
echo "<script>location.replace('keuze.php');</script>";
}
?>
This structure gives the same error:
<?php
while ($selControl->fetch())
{
echo "<script>alert('". $kLand . $kGerecht . $lLand_id . $gGerecht_id . "')</script>";
// If selected land (land_id) is not the same as land_id in table landen
// or selected gerecht (gerecht_id) is not the same as gerecht_id in table gerechten --> send echo.
if ($kLand == $lLand_id && $kGerecht == $gGerecht_id)
{
$selControl->close();
// If query is prepared --> bind the columns and execute the query.
// Insert statement with placeholders for the values to database table landGerecht
if ($insKeuze = $mysqli->prepare("INSERT INTO lab_stage_danush . landGerecht (land_id, gerecht_id) VALUES ( ?, ?)"))
{
// Bind land_id and gerecht_id as integers with $landKeuze and $gerechtKeuze.
$insKeuze->bind_param('ii', $kLand, $kGerecht);
// If statement is not executed then give an error message.
if (!$insKeuze->execute())
{
echo "Failed to execute the query keuze: " . $mysqli->error;
}
$insKeuze->close();
} else // Else give an error message.
{
echo "Something went wrong in the insert query connection: " . $mysqli->error;
}
} else // Else insert the selected values in table landGerecht.
{
// Message when the combination is not correct
echo "<script>alert('Deze combinatie bestaat niet. Doe een nieuwe poging!');</script>";
}
}
?>
So as you said in the comments, you believe you're getting a conflict between your mysql connections. I've gone ahead and created a class that should resolve this.
landen.php
class landen{
//define our connection variable, this is set in __construct
private $mysqli;
//this function is called when you create the class. $l = new landen($mysqlconn)
public function __construct($mysqli){
$this->mysqli = $mysqli;
}
//setter for kLand
private $kLand = 0;
public function setKland($k){
$this->kLand = $k;
}
//setter for kGerecht
private $kGerecht = 0;
public function setKGerecht($k){
$this->kGerecht = $k;
}
//run is our main function here.
//if there was a return from select, it runs the insert.
//will return true if select + insert BOTH pass.
public function run(){
if($this->select()){
return $this->insert();
}
return false;
}
private function select(){
$q = "SELECT landen.land_id, gerechten.gerecht_id FROM landen INNER JOIN gerechten ON landen.land_id = gerechten.land_id WHERE landen.land_id = ? AND gerechten.gerecht_id = ?";
if($stmt = $this->mysqli->prepare($q)){
$stmt->bind_param("ii",$this->kLand,$this->kGerecht);
if($stmt->execute()){
while ($stmt->fetch()){
/*
In your original code, you had a check to see if
your post variable was the same as your returned query variables.
This was not required as you are selecting from your database with those.
They will **always** equal the post variables.
Line I'm disputing: if ($kLand != $lLand_id || $kGerecht != $gGerecht_id)
*/
return true;
}
}else{
print_r("Error in select execute: {$this->mysqli->error}");
}
}else{
print_r("Error in select prepare: {$this->mysqli->error}");
}
return false;
}
private function insert(){
$q = "INSERT INTO lab_stage_danush . landGerecht (land_id, gerecht_id) VALUES ( ?, ?)";
if($stmt = $this->mysqli->prepare($q)){
$stmt->bind_param("ii",$this->kLand,$this->kGerecht);
if($stmt->execute){
return true;
}else{
print_r("Error in insert execute {$this->myqsli->error}");
}
}else{
print_r("Error in insert prepare {$this->mysqli->error}");
}
return false;
}
}
And here's an example on how you run this;
insert.php
<?php
require_once("dbConfig.php");
if(isset($_POST["submit"]) && !empty($_POST['landen']) && !empty($_POST['gerechten'])){
//Call the class code when we need it
require_once("landen.php");
//create the class when we need it.
$landen = new landen($mysqli);
//set our variables
$landen->setKland($_POST['landen']);
$landen->setKGerecht($_POST['gerechten']);
//landen run returns True if the select + insert statment passed.
//It will return false if they fail.
//if they fail, the page will not change and the errors will be outputted.
//Or it's failing because nothing has been returned by the select function.
if($landen->run()){
//send out header to go to Keuze page,
//you had a javascript location function here.
header("Location: keuze.php");
die();
}else{
//by default, let's say our queries are running fine and the only reason the select failed is because
//the database couldn't find anything.
echo "Nothing found with {$_POST['landen']} and {$_POST['gerechten']}. Please try again!";
}
}

How to prevent duplicate data in sql databse

I have a form where i save students login data to a database. The form includes the "admission_number", "username" and "password" fields. i want to show an error if the admission number is already existing and a user tries to add it again. Here's my php code for inserting the record.
<?php
if(isset($_POST['submit']))
{
$server = 'localhost';
$username = 'root';
$password = '';
$course_code=$_POST['course_code'];
$course_title=$_POST['course_title'];
$course_units=$_POST['course_units'];
$course_semester=$_POST['course_semester'];
$con=($GLOBALS["___mysqli_ston"] = mysqli_connect($server, $username, $password));
if(!$con)
{
exit('Error: could not establish connection to the server');
}
else
{
$con_db=((bool)mysqli_query($con, "USE esther"));
if(!$con_db)
{
exit('Error: Failed to connect to the database');
}
else
{
if(!empty($course_code) && !empty($course_title) && !empty($course_units) && !empty($course_semester))
{
$insert="INSERT INTO `course_table` VALUES('', '".$course_code."' ,'".$course_title."','".$course_units."','".$course_semester."')";
$query=mysqli_query($GLOBALS["___mysqli_ston"], $insert);
$dup_admission_number = mysql_query("SELECT admission_number FROM users_table WHERE admission_number = $admission_number");
}
if (#mysql_query($dup_admission_number)) {
echo 'Your admission number is already in our database.';
exit;
}
if($query)
{
echo 'course added successfully!';
header("location:add_course.php");
}
else { echo 'Error while adding Course.'; }
}
else
{
echo '*** fields cannot be blank ***.';
}
}
}
?>
To check admission number is unique or not you have to execute bellow query
$sql: "select id from student where admission_number = <> LIMIT 0,1";
if this query show result then you current form's admission number is not unique.
this process you can do using ajax request or you can check it before insert query being process.
or you can manage it in mysql by giving unique key constraint to admission number.
This is the Mysql Query
INSERT INTO sometable (data1, data2, data13)
SELECT 'username' FROM sometable
WHERE NOT EXISTS
(SELECT username FROM sometable WHERE login='someusername');

Insert to database into two tables

This code really made me confused.
The first and second time I ran it, it worked perfectly but after that it stopped working
Let me explain it:
I work with 2 tables.
The first table I insert to it the current date, current time and the id of the user the id I take it from the session.
Which I believe works fine.
My problem is in the second table the error I get is the error i typed in the " print " after the second insert.
this is my code :
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(!isset($_SESSION['con_id'])) {
header("location: login.html");
exit();
}
$DB_USER ='root';
$DB_PASSWORD='';
$DB_DATABASE='';
$con= mysql_connect($DB_HOST ,$DB_USER , $DB_PASSWORD);
if (!$con) {
die('Failed to connect to server :'.mysql_error());
}
$db=mysql_select_db($DB_DATABASE);
if (!$db) {
die("unable to select database");
}
//first table
$qry="insert into shipment values('',NOW(),CURTIME(),'".$_SESSION['con_id']."');";
$resultop=mysql_query($qry);
//to take the id frome last insert because i need it in the second insert
$SNo=mysql_insert_id();
if ($resultop) {
$options=$_POST['op'];//this is the name of the check boxe's
if (empty($options)) {
header("location: manage_itemsE.php");}
// this is the second table .. my reaaal problem
$qun=$_POST['Quantit'];
$size =count($options);
for ($i =0; $i<$size; $i++) {
$qqry="insert into shipmentquantity values('".$options[$i]."','".$SNo."','".$qun[$i]."');"; // $options is array of the id's which i took from the checkbox's in the html ... $qun is array of the values i took form html ... i sure this is right ;)
$resultqun=mysql_query($qqry);
}
if ($resultqun) {
header("location: shipment_order.php");
}
else print "error in the Quantity";
}
else print "error in the shipmet";
Just add some debug statements to find out what is going wrong. Something like -
$resultqun = mysql_query($qqry) or print mysql_error();
You need to do some reading about SQL injection as this script is vulnerable. Checkout these pages on the use of prepared statements - PDO::prepare and mysqli::prepare
UPDATE - here is an example using PDO to interact with your db -
<?php
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(!isset($_SESSION['con_id'])) {
header("location: login.html");
exit();
}
$DB_USER ='root';
$DB_PASSWORD='';
$DB_DATABASE='';
$db = new PDO("mysql:dbname=$DB_DATABASE;host=127.0.0.1", $DB_USER, $DB_PASSWORD);
//first table
$qry = "INSERT INTO shipment VALUES(NULL, CURRENT_DATE, CURRENT_TIME, ?)";
$stmt = $db->prepare($qry);
$resultop = $stmt->execute(array($_SESSION['con_id']));
if(!$resultop){
print $stmt->errorInfo();
} else {
$SNo = $db->lastInsertId();
$options = $_POST['op'];//this is the name of the check boxe's
if (empty($options)) {
header("location: manage_itemsE.php");
exit;
}
// this is the second table .. my reaaal problem
$qun = $_POST['Quantit'];
$size = count($options);
$stmt = $db->prepare("INSERT INTO shipmentquantity VALUES(?, ?, ?)");
for($i = 0; $i < $size; $i++) {
$resultqun = $stmt->execute(array($options[$i], $SNo, $qun[$i]));
}
if($resultqun) {
header("location: shipment_order.php");
} else {
print $stmt->errorInfo();
}
}
What is your primary key for the 'shipmentquantity' table? It looks like you are trying to enter two values of '3' for the primary key and that's where it's going awry.
DESCRIBE `shipmentquanitity`

Check To See A Match In MySql

I have a form which has a textbox with an attribute called ref. once this is submitted, it updates on of my fields in the database. I have this code working and fine but what i need now is for it to check if the data entered into the textbox exists in the database and if it does, then it should notify the user to choose another reference. here is my code for the php end:
$ref = mysql_real_escape_string($_REQUEST['ref']);
$id = $_GET['public'];
$con = mysql_connect("localhost", "*****", "******");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('*****', $con);
$sql = "UPDATE public SET ref = '$ref' WHERE public_id = '$id'";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo '<hr><h2>Reference Number Has Been Assigned Successfully</h2><hr>';
}
any ideas guys?
thanks
You can get the number of rows affected:
$rowsAffected = mysql_affected_rows($con);
if($rowsAffected) {
//something WAS changed!
}
else {
//NOTHING was changed ... :-(
}
Also I would watch out for Bobby Tables
You might want to use mysqli or PDO's prepared queries for what you want to do.
Based on OP's comment below:
...
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
$rowsAffected = mysql_affected_rows($con);
if($rowsAffected) {
echo '<hr><h2>Reference Number Has Been Assigned Successfully</h2><hr>';
}
else {
//show some error message?
}
}
In this case First you run a select command to search for the record with particular reference number. If the result is eof , then run insert command. If not EOF then send a warning to the user saying reference number exist and choose another one.

Categories