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
Related
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' ).
I'm trying to get a value from the database and compare it with whatever id href was set. But nothing happens.
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "products";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id FROM items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$id = $row["id"];
echo <<<EOT
<br>
<form action='index.php?$id' method="POST">
<input type='submit' name="submit" value="more">
</form>
EOT;
}
} else {
echo "0 results";
}
if (isset($_POST['submit'])) {
while($row = $result->fetch_assoc()) {
if ($_SERVER["QUERY_STRING"] == $row) {
echo 'you clicked something from the database' . $id;
}
}
}
$conn->close();
?>
Trying to eventually get a value from the database then individually show a description if the more href is clicked.
your answer has a high time complexity you can easily make you
SQL query
SELECT id FROM items WHERE id = ?
and if the rows number is 0 this is mean there is no record with this id
you can check row's number from num_rows
You will never see "you clicked something from the database" message because you already fetched the result from your query in the first loop, check this question why-cant-i-loop-twice-on-mysqli-fetch-array-results
An option is to save the result in an array to use it later in your second loop
//your first loop
$savedRows = [];
while($row = $result->fetch_assoc()) {
$savedRows[] = $row;
//the rest of your code
}
// ......
// your second loop
if (isset($_POST['submit'])) {
foreach($savedRows as $row) {
if ($_SERVER["QUERY_STRING"] == $row['id']) {
echo 'you clicked something from the database ' . $id;
}
}
}
Also note that if this is your actual code, you need to make the closing identifier of your herodoc EOT; the first character on it's line, otherwise the rest of the file will be part of this string
I'm making a page where you have to enter a text in a textbox and the click send, another page will save it.
Also, on the first page, the text that was stored previously in the database, has to load. This is the code that i've got:
<?php
$databaseid = 3;
$servername = "jog4fun.be.mysql";
$username = "jog4fun_be";
$password = "****";
$dbname = "jog4fun_be";
$gettitel1 = null;
$gettext1 = null;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Id,Titel,Tekst FROM Teksten";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if ($row["Id"]== $databaseid ){
$gettitel1 = $row["Titel"];
$gettext1 = $row["Tekst"];
}
}
} else {
echo "0 results";
}
$conn->close();
$gettitel1 = strip_tags($gettitel1, '<br>');
$link1 = '<textarea id = "klein" rows="4" cols="50" name="titel3" form="usrform">' . $gettitel1 . '</textarea>';
$link2 = '<textarea id = "groot" rows="4" cols="50" name="text3" form="usrform">' . $gettext1 . '</textarea>';
echo $link1;
echo $link2;
?>
The problem is that it sends the text from textbox with name text3 as text1 with the post function. Can someone figure out what's wrong with it? I've been tying for an hour and i did not find it.
Thanks for your time and help,
Jonas
Simply here:
while($row = $result->fetch_assoc()) {
if ($row["Id"]== $databaseid ){
$gettitel1 = $row["Titel"];
$gettext1 = $row["Tekst"];
}
you overwrite the value of the two variables each time you iterate. So after this block of code you will keep stored the last values returned from the db.
YOu should add to your query a WHERE clause to identify the one and only record you need so you will fetch only the relevant data. Example:
$sql = "SELECT Id,Titel,Tekst FROM Teksten WHERE Id='1'";
I'm scratching my head on the PHP to MySQL stored procedure problem, i have a stored procedure in MySQL that awaits for two input parameters. I'm trying to calling the procedure from my PHP code by pass them 2 variables that the php page received via a HTML form. But I kept getting below error:
PHP Warning: Wrong parameter count for mysqli_stmt::bind_param() in /var/www/html/admin.php on line 26, referer:..... admin.php
PHP Warning: mysqli_error() expects exactly 1 parameter, 0 given in /var/www/html/admin.php on line 27, referer: http://...../admin.php
My PHP code looks like below, which i can find no clue why it fails:
<?PHP
if (isset($_POST['Submit1'])) {
$ServerSet = $_POST['ServerSet'];
$Time = $_POST['Time'];
if ( (strcasecmp ($ServerSet, 'A') == 0) Xor (strcasecmp ($ServerSet, 'B') == 0) ) {
$servername = "localhost";
$username = "appm";
$password = "appm";
$dbname = "ITD_infra";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (empty($Time)) {
print "Fit A B and Time null";
print " Server is $ServerSet";
$stmt = $conn->prepare("call ext_swing_update_v2(?, null)");
$stmt->bind_param($ServerSet);
$stmt->execute() or die("Call fail: ".mysqli_error());
$conn->close();
}
else {
print "Both time and server not null";
print " $ServerSet and $Time";
$stmt = $conn->prepare("call ext_swing_update_v2(?,?)");
$stmt->bind_param($ServerSet, $Time);
$stmt->execute() or die("Call fail: ".mysqli_error());
$conn->close();
}
}
else {
print "Server string not match";
}
}
?>
<Form Name="form1" method = "POST" Action= "admin.php" >
<br>
<br>
<br>
<h2> Infra Admin Page </h2>
<br>
<b>Give live external server set as A or B below: </b>
<br>
<br>
Server Set:
<INPUT TYPE = "Text" NAME = "ServerSet">
<br>
Time is in format of YYYY-MM-DD HH:MM:SS, HH is 24hr.
<br>
Time:
<INPUT TYPE = "Text" NAME = "Time">
<br>
<INPUT TYPE = "Submit" Name ="Submit1" VALUE ="Login" >
</form>
<br>
<br>
In my table I have various requests each with their own reference number.
a user can see the number of requests on the page, but I want the user to be able to click on each request separately and be taken to a new page to see the specific details for that request.
I am trying to echo the reference in a hyperlink when the request is clicked and on the next page when I run my query to retrieve the name etc of that request it will only show the information which matches that reference number, i.e. 'SELECT * WHERE reference = $row['reference'].
However I am not sure on how to to do this, also I am concerned is this secure, if my query is checking against the reference in my url, i.e. mypage.php?reference=1234, whats to stop a user just manually typing in the url with a different reference number?
'mypage.php?reference=2468
the user should only be able to view the page if they actually clicked on the request, they should never be able to enter it directly into the url as this poses a security risk.
could I potentially mask my reference into a string? and echo out mypage.php?reference=$someString
page1.php
<div class="results_area">
<h44>Existing Supplier Request's</h44>
<?php
$conn = new mysqli($host, $username, $password, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
$sql = "select * from new_supplier_request where status!= 'complete' AND action_taken='actioned'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo '<div class="table_header"><p>Request By</p><p>Date Requested</p><p>Status</p><p>Supplier Name</p><p>Description</p><p>Action</p></div>'; ?>
</div>
<div class="results_area"><?php
while($row = $result->fetch_assoc()) {
echo '<div class="request"><a href="ns_application.php?ns_request='.$row['reference'].'/">';
mypage.php
$reference = $row['reference'];
<?php
$conn = new mysqli($host, $username, $password, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
$sql = "select * from new_supplier_request where status!= 'complete' WHERE reference = $reference Limit 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<h44>New Supplier Request: ' .$reference. ' </h44><br>';
echo 'The name of this supplier is, '.$reference['name'].';
} } ?>
</div>
You can use JavaScript to solve this problem.
I don't think that this will be 100% secure but actually it's more secure way than you are using now.
echo "<div .... onclick='showuniquereference('".$row['reference']."')'>"."</div>";
And Function like this
function showuniquereference(code)
{
var reference = code;
var form = document.createElement("form");
form.method = "POST";
form.action = "mypage.php";
var input = document.createElement("input");
input.name = "reference";
input.value = reference;
input.type = "hidden";
form.appendChild(input);
document.body.appendChild(form);
form.submit();
}
You can use this posted data to show unique reference to users.