html form with white fields to mysql - php

I don't understand what is the correct way to pass the html form fields to mysql database in case one of the fields is empty.
I have this html:
<form name="formName" method="POST" action="" onsubmit="registra();">
<label for="datetime1">datetime one</label>
<input type="datetime-local" id="datetime1" name="datetime1">
<label for="datetime2">datetime two</label>
<input type="datetime-local" id="datetime2" name="datetime2">
<button type="submit">Salva</button>
</form>
<script>
function registra() {
var datetime1 = document.forms['formName']['datetime1'].value;
datetime1 = new Date(datetime1).toISOString().slice(0, 19).replace('T', ' ');
var datetime2 = document.forms['formName']['datetime2'].value;
datetime2 = new Date(datetime1).toISOString().slice(0, 19).replace('T', ' ');
jQuery.ajax({
type: "POST",
url: "./functions.php",
data: {
action: 'registraForm',
id: <?php echo $id; ?>,
datetime1: datetime1,
datetime2: datetime2
}
}).done(function( response ) {
alert( response );
});
}
</script>
And this php:
<?php
/* AJAX */
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'registraForm' : registra_form();break;
}
}
function registra_form() {
$dbhost = "localhost";
$dbuser = "user";
$dbpass = "pass";
$db = "db";
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s\n". $conn -> error);
$id = $_POST['id'];
$datetime1 = ($_POST['datetime1']?$_POST['datetime1']:NULL);
$datetime2 = ($_POST['datetime2']?$_POST['datetime2']:NULL);
if ( /* update mysql row */ ) {
$sql = "UPDATE table SET datetime1='$datetime1', datetime2 = '$datetime2', WHERE id=$id";
} else {
$sql = "INSERT INTO table (id, datetime1, datetime2) VALUES ($id, '$datetime1', '$datetime2')";
}
if ($conn->query($sql) === TRUE) {
echo 'done!';
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
die();
$conn -> close();
}
In the database both datetime1 and datetime2 are set as timestamp type with default null.
If both datetime1 and datetime2 are filled, the registration is successful. If instead one of the two fields of the form is not filled I receive a sql syntax error.
Something like error: UPDATE table SET datetime1='2020-04-17 11:06:00', datetime2='' WHERE id=5 Incorrect datetime value:'' for column db.table.datetime2 at row 2
I think this is the problem $datetime2 = ($_POST['datetime2']?$_POST['datetime2']:NULL); but I don't know how to solve it.
Thanks
Fosco

Ok this is "an answer" and not a pretty one, based upon your supplied code/issue.
Personally I would not code it this way, but we cannot give tutorials on here.
This is more a demonstration on how to go about working something out, without all the in between bits.
This is an example. Test Code (something we should learn to write), I used to test getting the correct SQL Statements.
function test_datetime_sql()
{
$_POST['datetime1'] = '';
$_POST['datetime2'] = '2020-04-17 11:06:00';
// There must be a more elegant way to do this
$datetime1 = $_POST['datetime1']?"'".$_POST['datetime1']."'":'NULL';
$datetime2 = $_POST['datetime2']?"'".$_POST['datetime2']."'":'NULL';
echo '<pre>';
echo 'LINE: '. __LINE__. ' Module '.__CLASS__.'<br>';
var_dump($datetime1);
echo '</pre>';
echo '<pre>';
echo 'LINE: '. __LINE__. ' Module '.__CLASS__.'<br>';
var_dump($datetime2);
echo '</pre>';
$id = 5;
$sql = "UPDATE table SET
datetime1 = $datetime1,
datetime2 = $datetime2,
WHERE id=$id";
var_dump($sql); // What SQL do we get
}
Give that a try by generating the SQL and testing it.
Notice that its a change to the Ternary AND the SQL statement - notice the lack of '' in the $sql for datetime1 and datetime2 as they are generated in the ternary.
What is happening here is if it is a "Not Empty" Value, it's getting wrapped in '' to make it a string.
The same occurs with NULL
I strongly suggest you copy and paste this somewhere and play with it to see what happens.
In your original code, when you set $datetime1 as NULL it appears in your SQL as $datetime1 = '' and NOT as $datetime1 = NULL ( Not the string 'NULL' ).

Related

how to insert date using php into mysql query? [duplicate]

This question already has answers here:
Using Mysqli bind_param with date and time columns?
(5 answers)
Closed 1 year ago.
what i'm trying to do is get date from html input, execute a query using that date. but i can't seem to figure out what is the problem, i'm doing everything right (or am i?)
Here is some code index.php
<head>
<script>
function showReport(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("report").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "/reports.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form>
Select Date: <input type="date" onchange="showReport(this.value)">
</form>
<p>Results: <span id="report"></span></p>
</body>
</html>
here is the ajax handler reports.php
// get the q parameter from URL
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "chaska";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$input_date=$_REQUEST['q'];
$date=date("Y-m-d",strtotime($input_date));
$sql = "SELECT `tec_sale_items`.product_name, `tec_sales`.date, sum(`tec_sale_items`.quantity) AS sum FROM `tec_sale_items` LEFT JOIN `tec_sales` ON `tec_sale_items`.sale_id = `tec_sales`.id WHERE DATE(`tec_sales`.date) = $date AS DATE group by `tec_sale_items`.product_name, DATE(`tec_sales`.date)";
$result = $conn->query($sql);
echo $date;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "product: " . $row["product_name"]. " - Quantity: " . $row["sum"]. " ". "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
The query returns nothing. When I replace $date AS DATE by CURRENT_DATEthe query executes fine but I want a specific date to work as well
The following is illegal SQL syntax for two reasons; it's missing quotes around the $date variable (which is a string), and you try to give it an alias (all you're doing is comparing two values, so aliasing makes little sense here).
WHERE DATE(`tec_sales`.date) = $date AS DATE
You should also be using a prepared statement with MySQLi, as shown below. Using a prepared statement means that you no longer need to worry about quoting your variables.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "chaska";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$input_date = $_REQUEST['q'];
$date = date("Y-m-d",strtotime($input_date));
$sql = "SELECT `tec_sale_items`.product_name,
`tec_sales`.date,
sum(`tec_sale_items`.quantity) AS sum
FROM `tec_sale_items`
LEFT JOIN `tec_sales`
ON `tec_sale_items`.sale_id = `tec_sales`.id
WHERE DATE(`tec_sales`.date) = ?
GROUP BY `tec_sale_items`.product_name, DATE(`tec_sales`.date)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $date);
$stmt->execute();
$stmt->bind_result($product_name, $date, $sum);
if ($stmt->fetch()) {
do {
echo "product: ".$product_name. " - Quantity: " . $sum. " <br>";
} while ($stmt->fetch());
} else {
echo "0 results";
}
$stmt->close();
WHERE DATE(`tec_sales`.date) = $date
Use single quotes around date value, otherwise it is evaluated as arithmetic operation - 2019-07-23 = 2012 - 23 = 1989.
Correct condition:
WHERE DATE(`tec_sales`.date) = '$date'
There is no risk of sql injection, because input value is parsed by strtotime.
what you did is right
Select Date: <input type="text" onchange="showReport(this.value)" >
but use text instead of date

Not able to insert the data from url to database in php

final.php
Here I am trying to get the data from the url using GET method and trying to insert into the database. I was able to insert the data for first few rows after that the data is not inserted. Can anyone help me regarding this?
when I try to run the url: www.myii.com/app/final.php?name=123&glucose=3232...
the data is not inserting.
<?php
include("query_connect.php");
$name = $_GET['name'];
$glucose = $_GET['glucose'];
$temp = $_GET['temp'];
$battery = $_GET['battery'];
$tgs_a = $_GET['tgs_a'];
$tgs_g = $_GET['tgs_g'];
$heartrate = $_GET['heartrate'];
$spo2 = $_GET['spo2'];
$rr = $_GET['rr'];
$hb = $_GET['hb'];
$ina22 = $_GET['ina22'];
$accucheck = $_GET['accucheck'];
$isactive = $_GET['isactive'];
$address = $_GET['address'];
$deviceno = $_GET['deviceno'];
$sql_insert = "insert into query (name,glucose,temp,battery,tgs_a,tgs_g,heartrate,spo2,rr,hb,ina22,accucheck,isactive,address,deviceno) values ('$name','$glucose','$temp',$battery','$tgs_a','$tgs_g','$heartrate','$spo2','$rr','$hb','$ina22','$accucheck','$isactive','$address','$deviceno')";
mysqli_query($sql_insert);
if($sql_insert)
{
echo "Saving succeed";
//echo $date_time;
}
else{
echo "Error occured";
}
?>
Query_connect.php
This is my database config php file.
<?php
$user = "m33root";
$password = "me3i434";
$host = "localhost";
$connection = mysqli_connect($host,$user,$password);
$select = mysqli_select_db('miiyy',$connection);
if($connection)
{
echo "connection succesfull<br>";
}
else {
echo "Error";
}
?>
Make sure that all columns can contain NULL so that not filled fields will stay NULL instead of throwing an error.
Try below to see mysql error:
mysql_query($sql_insert);
echo mysql_error()
Try these
In SQL
Change the table name of query to some other name. Because "query" is reserved in SQL
In code
if (!mysqli_query($con,$sql_insert ))
{
echo("Error description: " . mysqli_error($con));
}
else
{
echo "Success";
}
Use mysqli_error() function

PHP Insert form using Stored Procedure

I'm new to PHP and mysql. I have created a form which accepts some inputs from the user and I want this inputs to be inserted into the mysql using stored procedure.
Hurray I got this, now form data is inserting into the mysql using stored procedure.
dbconn.php
<?php
// Set connection variables.
$host = "localhost";
$user = "root";
$pwd = "root";
$db = "eservice";
// Connect to mysql server
$mysqli = new mysqli($host,$user,$pwd,$db);
/* Check if any error occured */
if (mysqli_connect_errno())
{
echo "Failed to connect to mysql : " . mysqli_connect_error();
exit;
}
?>
Add.php
<?php
// If the form was submitted.
if($_POST)
{
// Connect to db.
include 'dbconn.php';
// Retrieve data from form.
$srn = $_POST['srn'];
$client = $_POST['client'];
$type = $_POST['type'];
$fy = $_POST['fy'];
$category = $_POST['category'];
$sd = $_POST['sd'];
$fd = $_POST['fd'];
$assignto = $_POST['assignto'];
$edoc = $_POST['edoc'];
$current = date('m/d/Y');
$date = strtotime("+".$edoc." days", strtotime($current));
$ecd = date("Y/m/d", $date);
$reviewed = $_POST['reviewed'];
$path = $_POST['path'];
// Stored procedure code
if(!$mysqli->query("DROP PROCEDURE IF EXISTS addproc")
|| !$mysqli->query("CREATE PROCEDURE addproc
(IN client varchar(50), IN type varchar(30), IN fy INT, IN category varchar(30), IN sd varchar(80),
IN fd varchar(80), IN assignto varchar(50), IN edoc date, IN reviewed varchar(40), IN upload varchar(100))
BEGIN
INSERT INTO main(client, type, fy, category, sd, fd, assignto, edoc, reviewed, upload) VALUES(client, type, fy, category, sd, fd, assignto, edoc, reviewed, upload);
END; "))
{
echo "Stored procedure creation failed : (" .$mysqli->errno .") " .$mysqli->error;
}
if(!$mysqli->query("CALL addproc('$client','$type','$fy','$category','$sd','$fd','$assignto','$ecd','$reviewed','$path')"))
{
echo "CALL failed : (" .$mysqli->errno .")" .$mysqli->error;
}
else
{
?>
<script language="javascript">
alert("Task created successfully" + "\n\n" + " <?php echo "Service Request Number : " .$srn ?>");
top.location.href = "Home.php"; // Page redirection.
</script>
<?php
}
if(!$res = $mysqli->query("SELECT * FROM main"))
{
echo "SELECT failed : (" .$mysqli->errno .")" .$mysqli->error;
}
}
?>
$query = "INSERT INTO main(client, type, fy, category, sd, fd, assignto, edoc, reviewed, upload) VALUES('$client', '$type', '$fy', '$category', '$sd', '$fd', '$assignto', '$edoc', '$reviewed', '$upload')";
if(mysqli_query($mysqli,$query))
& others.

Checkbox that updates dynamically

I have a checkbox that dynamically updates a MySQL database when it is checked/unchecked using PHP and Ajax.
I am now trying to pass the users name so that the Ajax script can update the database with the users full name.
I have the name held in a variable called $full_name. I cannot seem to get this working though. Please see the code below:
Javascript:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function chkit(uid, chk) {
chk=document.getElementById("chk").checked;
$.ajax({
type: 'GET',
url: 'ajax.php',
data: { chkYesNo: chk, record_id: uid, full_name: user},
success:function(data){
// successful request; do something with the div background color
if(data==1)
{
$("#replace").addClass("checked_div_status").removeClass("replace");//removing first class and adding second class
}
else
{
$("#replace").addClass("replace").removeClass("checked_div_status");//removing second class and adding first class
}
}
});
}
</script>
HTML:
<?php
$record_id = $_GET['veh_id'];
include '../dbconnect.php';
//fetching data from database
$select=mysql_fetch_array(mysql_query("select invoice_checked from vehicle_details where veh_id = '$record_id' "));
?>
<!--The checkbox whose enable to change div his background color and onclick call function to update database-->
<table width=“100%”>
<td id="replace2" class="<?php if($select['invoice_checked']==1) { echo 'checked_div_status2'; } else{ echo 'replace2'; } ?>">
<input name="chk2" type="checkbox" id="chk2" value="1" onclick="chkit2(<?php echo $record_id;?>,'chk2');" <?php if($select['invoice_checked']==1) { echo 'checked'; } else{ echo ''; } ?> />
Invoice Checked
</td>
</table>
Ajax.php:
<?php
mysql_connect("server", "username", "password") or die("Could not connect: " . mysql_error());
mysql_select_db("database");
//here $get variable receive checkbox value true(1) either false(0)
$get=$_GET['chkYesNo'];
//here $get_id variable receive value of current id that you passed
$get_id=$_GET['record_id'];
$get_user=$_GET['full_name'];
if($get=="true")
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='1', check_user='".$get_user."' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
else
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='0', check_user='0' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
?>
Any help would be greatly received.
Thanks,
John
Some debug lession for you. Please, check my comments:
// Do not need to replicate your code, if the same things happens in it.
//instead, use a condition to set your variables, and use these variables later.
if ($get == "true") {
$hpi_registered = 1;
//Escape your variable to avoid sql injection
$checkUser = mysqli_real_escape_string($conn, $_GET["full_name"]);
} else {
$hpi_registered = 0;
$checkUser = 0;
}
//Store your query in a variable, so you can debug / dump it
//Let's dump it, see, what is your query, and try to run in directly in sql.
//Maybe it has syntax error.
$sql = "UPDATE vehicle_details SET"
. " hpi_registered='" . intval($hpi_registered) . "',"
. " check_user='" . $checkUser . "'"
. " WHERE veh_id='" . intval($get_id) . "'";
mysqli_query($conn, $sql);
//What happens, if you run it directly in sql? If this fails, now here is your
//error.
$sql = "SELECT hpi_registered"
. " FROM vehicle_details"
. " WHERE veh_id='" . intval($get_id) . "'";
//Do the same like previous query.
$res = mysqli_query($conn, $sql);
$select = mysqli_fetch_array($res);
echo $select['hpi_registered'];
DO NOT use mysql functions, because they are deprecated. Use mysqli or PDO instead.
Avoid sql injection by escaping your variables.

Php code does not send query to database

I am trying to update my database using ajax, but I cannot seem to understand why the php code does not update the database. The script:
function Insert () {
if (XMLHttpRequestObject) {
XMLHttpRequestObject.open("POST","list_insert.php");
XMLHttpRequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
var returnedData = XMLHttpRequestObject.responseText;
var messageDiv = document.getElementById('messageDiv');
messageDiv.innerHTML = returnedData;
}
}
var item = document.getElementById('items').value;
var desc = document.getElementById('description').value;
var data = item + '|' + desc + '|';
XMLHttpRequestObject.send("data=" + data);
}
return false;
}
This is the php code for list_insert:
<?php
include "function_list.php";
$myData = $_POST['data'];
$datetime = date('Y-m-d H:i:s');
list($items,$description) = explode ('|',$myData);
$statement = "INSERT INTO record ";
$statement .= "(items,description) ";
$statement .= "VALUES (";
$statement .= "'".$items."', '".$description."')";
print $statement;
insert($statement);
print "done";
?>
My php function to insert into the db (function_list):
<?php
$con=mysqli_connect("localhost","shop");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function insert($statement) {
global $con;
mysqli_query($con,$statement);
}
?>
When I print the statement out, the query is correct (I have verified this by manually copy pasting it in mysql). I think the issue is with my insert function.
Any help is appreciated,
thank you.
Firstly, all mysql statements must end in a semicolon.
Secondly, have you made sure $items and $description are the values you expect them to have? Do they have any unescaped quotes?
Also, typically you would send each of the fields as a separate value like so:
var item = document.getElementById('items').value;
var desc = document.getElementById('description').value;
XMLHttpRequestObject.send("items=" + item + "&desc=" + desc);
$$items = $_POST['items'];
$description = $_POST['desc'];
By default, the username for mysql is root, and the password is blank, even though you aren't prompted for these, they are set by default.
I think this might be the issue
in ur global variable $con letz say you put this
$con = new mysqli("host", "user", "pwd", "dbname");
then
function insert($statement) {
$con->query($statement);
$con->close();
}

Categories