I have read through hundreds of posts on here and on other sites. I am not overly familiar with PHP and mysql, but already have my tables built in mysql, have called them using single checklists and filtered them based on date and time. However, in the multi-checkbox arena, I cannot seem to pin down what I'm doing wrong for an array code and customizing the resulting table. This is the basic html:
<html> <body> <form method="POST" action="php/minute_feedback.php">
Date: <input type="text" name="from_date" id="from_date" value="2016-04-07">
<input type="checkbox" name="check_list[]" value="gate" id="gate">
<input type="checkbox" name="check_list[]" value="pressure" id="pressure">
<input type="checkbox" name="check_list[]" value="flow" id="flow">
<input type="submit" name="submit" value="submit">
This is the basic PHP (I'll only include the date parameters vs. date & time to keep it shorter since the inclusion will be the same):
<?php
$servername = "myhostaddress.com";
$username = "myusername";
$password = "mypassword";
$dbname = "mydatabasename";
$conn=new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
if($_POST['submit'] == "submit") {
$from_date = ($_POST['from_date']);
$to_date = ($_POST['from_date']);}
if(isset($_POST['submit'])) {
Now ... I know there should be some sort of an array code in here like:
$checklist[] = $_POST[check_list];
But - I'm not sure what the correct syntax/code is.
Next question is about my query. I've seen most queries using a WHERE + IN combo and a '*' for SELECT. However, I need something closer to:
$sql = "SELECT Fdate, Ftime, (list of variable columns from the checked options such as 'gate', 'pressure', 'flow' --> but only if they've been checked) FROM minute_db WHERE Fdate BETWEEN '$from_date' AND '$to_date'";
$result = $conn->query($sql);}
if ($result->num_rows > 0) {
Now - as for my table headers, I can use the following code if I had a single value being looked up:
echo "<table><tr><th>Date</th><th>Time</th><th>Level (ft)</th></tr>";}
But, I need the header to be dynamically populated with the results of the checked items (1, 2, or 3 or more variables as needed) plus the date and time records.
echo "<table>";}
else {
echo "0 results";}
$conn->close();
?>
My end result is that the user can enter a date and time range and choose which data to display, so for example, if they want to know just the gate setting and pressure on 4/7/2016, they'd enter that date and check those two boxes so they will get a table (no formatting below - just trying to represent), for example:
Date | Time | Gate Setting | Pressure
----------------------------------------------------
2016-04-07 | 11:00 | 21 | 50
I will ultimately have a table with tens of thousands of rows of data to select from (and will include limiters to the amount of data that can be pulled), and up to 56 columns of variables to select from. I'm not using any special/fancy math functions to group time periods, etc. - I've already manually separated it all out and uploaded it so it's ready to go. I've tried a lot of different solutions from the internet, but have ultimately failed. The * option for SELECT doesn't seem like what I what, neither does the IN option - but I am not sure (just speculating as neither has worked). I'm on a netfirms mysql platform, so it's pretty updated (and I'll be changing everything to mysqli to avoid whatever problems stem from not using it - so any feedback with that in advance would be AWESOME!!. I appreciate any ideas you have!
Thanks to Deep's solution above - it works perfectly as-is! AWESOME. As for the use of the table array, I was struggling because I could populate the table, but was getting duplicates of date and time (as noted in my replies above). However - I simply moved the script around a bit and it works. Now, the user will get back columns with the date, time, and then the additional variables they are looking for, side by side, across the page, as comparative values (note - I have not yet gotten to the point of mysqli or pdo, so if this is old, please update as you need). Hopefully this helps - and thanks again! So - from the sql line from Deep's post above (fully filled out), this is the table -->
$sql = "SELECT Fdate, {$wantedFields} Ftime FROM minute_db WHERE Fdate BETWEEN '$from_date' AND '$to_date' AND Ftime BETWEEN '$from_time' AND '$to_time'";
$result = $conn->query($sql);
}
if ($result->num_rows > 0) {
//header fields
echo "<table><tr><th>Date</th><th>Time</th>";
foreach($tableDynFields as $c) {
echo "<th>$c</th>";
}
echo "</tr>";
//results
while ($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["Fdate"]."</td><td>".$row["Ftime"]." </td>";
foreach($tableDynFields as $c) {
echo "<td>".$row[$c]."</td>";
}
echo "</tr>";
}
echo "</table>";
//result set free
$result->free();
} else {
echo "query failed.<hr/>";
}
$conn->close();
?>
The only thing I'll add is if you're having to filter and sort through as much data as I am - tis good to either put a forced limiter at the end of the select statement, or something to that effect!
$checklist = $_POST['check_list'];
$allowedFields = [
'gate' => 'Gate',
'pressure' => 'Pressure',
'flow' => 'Flow',
'etc' => 'Other field title'
];
$wantedFields = [];
$tableDynFields = [];
foreach ($checklist as $field) {
if (array_key_exists($field, $allowedFields)) {
$wantedFields[] = $field;
$tableDynFields[] = $allowedFields[$field];
}
}
if ($wantedFields) {
$wantedFields = join(',', $wantedFields) . ',';
} else {
$wantedFields = '';
}
$sql = "SELECT Ftime, {$wantedFields} Fdate FROM ...';
// and here you have $tableDynFields array for table generation
Related
I have a problem here with break and loops things in php.I have an input type, if I give the id 2 for ex, if there is 2 in db then only "You liked this url already" should be appear.This works. If I give then id 3 it says "Data added".Good for now.But if I enter again id 3 it says:
Data added!You liked this url already
and a new value of 3 is posting in the db.How to avoid this? Here is my function:
<form method="post">
Url id: <input type="text" name="urlid" id="urlid">
<input type="submit" name="givelikes" value="Give Likes">
<br />
<br />
</form>
<?php
if(isset($_POST['givelikes'])){
$urlid = $_POST['urlid'];
$con = mysqli_connect('localhost','root','root', 'db');
$user = $_SESSION['sess_user'];
$query=mysqli_query($con,"SELECT likes FROM users WHERE user='".$user."'");
$row = mysqli_fetch_array($query);
$array = explode(" ", $row['likes']);
foreach ($array as $value) {
echo $value;
echo $urlid;
if($value == $urlid){
echo "You liked this url already";
break;
}
else{
$array = $row['likes'];
$array .= " ";
$array .= "$urlid";
$query = ("Update users set likes = '".$array."' where user = '".$user."'");
if(mysqli_query($con,$query)){
echo "Data added!";
}
else{
echo "ERROR: Could not able to execute sql: " . mysqli_error($con);
}
}
}
}
?>
Currently you're looping through all "likes" and comparing them. So the sequence of steps is like this:
Enter 2
No likes yet, so the data is added
Enter 2
Loop over likes, find 2, data was already added
Enter 3
Loop over likes, find 2, not match so data is added
Enter 3
Loop over likes, find 2, not match so data is added
Continue looping, find 3, data was already added
Correcting this is going to involve changing your design a bit. Right now you have one de-normalized record with a string of space-delimited "likes". Normalize your data. Have one record per "like". And instead of constantly updating a single record, insert new records.
Then when you want to see if a "like" already exists, you can use a WHERE clause. Something like this:
SELECT * FROM users WHERE user=? AND like=?
(Note: This is using query parameters as a prepared statement. This is highly recommended. Your current code is wide open to SQL injection.)
If any record is found at all, then the item was "already liked" and you can output the message. If no record was found, INSERT a new one for that "like".
No need for a loop.
How can I update a database with the values from an array? For example, let’s say we got a database with three tables:
Meals:
mealnr(PK), name, sort
Ingredients: ingredientnr(PK), name, stock
Structure: mealnr(FK), ingredientnr(FK), amount
I filled the database with some meals and ingredients. Every meal consists of multiple ingredients. The chef decides you only need 75g of ingredient x instead of 100g for meal y, so it needs to be changed in the database. Of course it can be done with SQL-commands, but I want to do it using a form in PHP.
First I made a page where all the meals are displayed. A meal can be edited using the edit-button next to it and based on the mealnr, you can change the amount of one or multiple ingredients for that particular meal. On the edit-page all the ingredient names and amounts are displayed in a table. The amount fields are textfields, those can be edited.
I made this script, but I don’t know exactly how I can update my database with the values of an array. I tried it with a foreach-loop, but it doesn't work.. yet. Can somebody help me?
<?php
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db("eatit", $conn);
$id = $_REQUEST['mealnr'];
$result = mysql_query("SELECT meals.name AS mealname, structure.amount, ingredients.name AS ingredientname
FROM Meals, Structure, Ingredients
WHERE meals.mealnr = structure.mealnr
AND structure.ingredientnr = ingredients.ingredientnr
AND meals.mealnr = '$id'");
if(isset($_POST['save']))
{
$new_amount = $_POST['amount[]'];
foreach ($new_amount as $value) {
mysql_query("UPDATE structure SET amount ='$value', WHERE mealnr = '$id'")
or die(mysql_error());
}
}
mysql_close($conn);
?>
<p><strong>Ingredients:</strong></p>
<?php
echo "<table>";
echo "<tr>";
echo "<th>Ingredient</th>";
echo "<th>Amount (gr)</th>";
echo "</tr>";
while($ingredient = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>";
echo $ingredient['ingredientname'];
echo "</td>";
echo "<td>";
echo '<input type="text" formmethod="post" name ="amount[]" value="' . $ingredient['amount'] . '" />';
echo "</td>";
echo "</tr>";
}
?>
<input type="submit" name="save" value="save" />
In your HTML markup you have declared the elements holding the name amount as an array by using amount[].
So, in your php code that receives the data it's enough to just refer to the amounts this way:
$new_amount = $_POST['amount'];
instead of:
$new_amount = $_POST['amount[]']; // in fact, this is wrong
Your foreach is fine, you should add some checks so that the $value actually contains a value that you expect, for example an int, float or not less than zero (or whatever checks you find necessary).
foreach($new_amount as $value){
if($value != '' && $value >= 1){
//sql statements goes here.
}
}
Receiving form data this way and then directly injecting the result to your SQL statement is always dangerous:
$id = $_REQUEST['mealnr'];
If you declare that you expect an integer (as the id's should be) before you directly inject the code to your SQL statement you have already written safer code.
$id = (int)$_REQUEST['mealnr'];
Also, just for the record - the mysql_* library is deprecated. As pointed out in the comments, try using PDO or mysqli instead - really!
I am attempting to write a page with 2 drop down lists. THe first populating a list of tables from mysql db allowing the user to choose the date in question, the second allowing the user to choose a name from a column in that table. I currently have the form written like below to generate an array of values from the specific table/row specified by the user which I can then echo out in to various fields in the html form.
I am struggling with getting the drop down list populated by the table names. Can anyone assist please? Sorry for the long post it's my first and I wanted to be thourough. I know that the connection to my database is working and the second drop down list is working when I specify in the code what table to use.
I need the first box to list the table names and then set the variable $date.
This is the drop down list for the date:
<select name='Date'>
<?php
$date = $_POST['date'];
$cxn=mysqli_connect("localhost",$userid,$password,$db)
or die ("Could not connect to Database");
$result=mysqli_query($cxn,"Show tables from january");
while($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
echo "<option value='".$row['Value']."'>".$row['Value']."</option>";
}
?>
</select>
This is the drop down list for the names from the table selected above.
<select name='agentname'>
<?php
$name = $_POST['agentname'];
$cxn=mysqli_connect("localhost",$userid,$password,$db)
or die ("Could not connect to Database");
$sql=mysqli_query($cxn,"SELECT Value FROM january.'$date'");
while($row = mysqli_fetch_assoc($sql))
{
echo $value ="<option value='".$row['Value']."'>".$row['Value']."</option>";
}
?>
</select>
<input type='submit' value='Get Dashboard' />
</form>
Creating the form :
<form action='getlist.php' method='post'>
<div align="center">
<p>
<select name='Date'>
<?php
$date = $_POST['date'];
$cxn=mysqli_connect("localhost",$userid,$password,$db)
or die ("Could not connect to Database");
$result=mysqli_query($cxn,"Show tables from january");
while($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
echo "<option value='".$row['Value']."'>".$row['Value']."</option>";
}
?>
</select>
<select name='agentname'>
<?php
$name = $_POST['agentname'];
$cxn=mysqli_connect("localhost",$userid,$password,$db)
or die ("Could not connect to Database");
$sql=mysqli_query($cxn,"SELECT Value FROM january.'$date'"); //I have specified schema's in my DB for the different months
while($row = mysqli_fetch_assoc($sql))
{
echo $value ="<option value='".$row['Value']."'>".$row['Value']."</option>";
}
?>
</select>
<input type='submit' value='Get Dashboard' />
</form>
TO be used in the following query to generate the array:
<?php
$cxn=mysqli_connect("localhost",$userid,$password,$db)
or die ("Could not connect to Database");
$result=mysqli_query($cxn,"SELECT column1, column2, column3 //just listing examples here for my columns there is about 45 columns for this selection
FROM january.'$date'
WHERE Value='$name'");
while($row = mysqli_fetch_array($result))
{
$stats = $row;
}
?>
Alright...
To address your actual question, I think the problem is the index you're referencing in the output of mysqli_fetch_assoc. Generally, the table names of a "SHOW" query are keyed like "Tables_in_databasename", or something like that. You might print_r your $row variable to see what index you should reference.
Now, unrelated to your questions, I do have to insist you rethink how you're storing your data. It is very bad procedure to have meaningful data represented in the names of your databases and tables. Not only is this not the way databases are meant to be used, which will inevitably cause problems for you, you're also making things unnecessarily hard for you.
I'm not sure what kind of statistics you're storing, but let's say it's something like clicks per day for a website. This data can be very easily stored in one database, and one table. For example:
Database: statistics
Table: daily_statistics
Columns: id, stat_date, value
Now you can store the clicks-per-day easily, and in one table.
id, stat_date, value
1, 2014-01-01, 300
2, 2014-01-02, 400
etc...
Let's say that you have multiple values per day. Not a problem
id, stat_date, value
1, 2014-01-01, 300
2, 2014-01-02, 400
3, 2014-01-02, 250
etc...
// The unique ID, alows multiple records per day.
// If you need them categorized in a different way,
// add another column.
This structure will work for years and year to come.
id, stat_date, value
1, 2014-01-01, 300
2, 2014-01-02, 400
3, 2014-01-02, 250
4, 2015-01-01, 250
5, 2016-01-01, 250
etc...
Now you have access to mysql aggregating functions,you have a situation where it will be easier to import and export data, you won't have to deal with having 100s of databases and even more tables as the years go on, and any developer who comes after you won't have to pull their hair out trying to work with this sticky situation.
New to MySQL/php but I am using xampp and trying to create a simple webpage to act like ledger (like checking account kind of deal). So I have debit, gain and balance columns (and some others) in a table which I am inserting a new record:
html
<form id='chk-trans-form' action="example-api.php" method="post">
Detail: <input type='text' name='trans-detail'/><br/>
Date: <input type='text' id='trans-dts'/><br/>
Amount: <input type='text' id='trans-amount'/>
Debit <input type='radio' name='trans-type-group' value='debit' checked/> Gain <input type='radio' name='trans-type-group' value='gain'/>
<button id='submit-trans'>submit</button>
</form>
database.php
<?php
$conn = mysql_connect('localhost', 'root', '');
$db = mysql_select_db('financial');
?>
example-api.php
<?php
include_once('database.php');
$transDate = $_POST['trans-dts'];
$transDetail = $_POST['trans-detail'];
$transAmount = $_POST['trans-amount'];
$transType = $_POST['trans-type-group'];
if ($transType == 'debit')
{
if(mysql_query("INSERT INTO chktrans (chkDTS, chkDetail, chkDebit) VALUES ('$transDate','$transDetail', '$transAmount')"))
echo "Successfully Added";
else
echo "Insertion Failed";
} else {
if(mysql_query("INSERT INTO chktrans (chkDTS, chkDetail, chkGain) VALUES ('$transDate','$transDetail', '$transAmount')"))
echo $transType;
else
echo "Insertion Failed";
}
?>
so this was the approach i learned and it works well for getting the data to the table, though I am not sure if its the best approach, just what I found.
So the next part I am a little unsure about....since this is a transaction like table, I need something like Last Balance + (Debit + Gain) = new balance. So I am not sure if this is something that I should be trying to get in php, or do in mysql....I have found triggers for a calculated-like field approach (here), but I am not sure if that will work because I don't know how to get the last value, or if the best approach is creating triggers for this, or trying to pull the value and use php to get the value, calculate and send everything back??
any help or direction is appreciated as always.
Just SELECT the column that you want, store that in a variable, get the other. In this case you'll be getting the 'chkGain' and the necessities for the debit.
The last balance will remain the same until the statement is finished invocation.
$currBalance = $currBalance + $debit + $gain;
Note that in your equation, 'Last Balance + (Debit + Gain),' parentheses aren't needed. Order of operations, my friend.
I would calculate the balance using a SELECT, something like
select (currBalance + debit + gain) total_balance from chktrans;
If you want to fetch the last row (the last inserted), you could do something like:
select * from chktrans where rowid in (select max(rowid) from chktrans);
Hope it helps.
I've been racking my brain trying to figure out how to get this to work. Now, i'll explain it a bit better here.
What i'm trying to do is, when the user types something into a form it returns the result of the query, then using the results from that query, carry out another query on them. I'm using PHP and an oracle database.
For instance: currently I've a database full of recipes and their ingredients; and I have a form that a user can enter an ingredient into. In this example, it's bacon.
That works just fine. However, what i'm having difficulty achieving is when the user enters another ingredient, the results of the current table there and further queried. Say I enter 'cheese', all the recipes containing bacon AND cheese are then queried and displayed.
This process is easily achieved in simple SQL, however like I saw i'm having difficulty transferring it to use a form.
Now, I've an idea the solution is either something to do with temporary tables, dynamic sql or a combination of the both.
Thank you in advance for any help regarding the matter.
My code is as follows:
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
}
function do_fetch($myeid, $s)
{
print '<table border="1">';
while ($row = oci_fetch_array($s, OCI_RETURN_NULLS+OCI_ASSOC)) {
print '<tr>';
foreach ($row as $item) {
print '<td>'.($item?htmlentities($item):' ').'</td>';
}
print '</tr>';
}
print '</table>';
print '<br>';
}
// Create connection to Oracle
$c = oci_connect("system", "luigi98", "localhost/XE");
// Use bind variable
$query = "SELECT DISTINCT r.recipeTitle AS recipe
FROM RECIPES.recipe r
WHERE recipeID IN(
SELECT r.recipeID
FROM recipes.recipeIng il
INNER JOIN RECIPES.ingredient i ON il.ingredientID = i.ingredientID
WHERE il.recipeID = r.recipeID
AND i.ING = :eidbv)";
$s = oci_parse($c, $query);
$myeid = $name;
oci_bind_by_name($s, ":EIDBV", $myeid);
oci_execute($s);
do_fetch($myeid, $s);
// Close the Oracle connection
oci_close($c);
?>
<p>Enter ingredient</p>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Search"><br>
</form>
There are several ways you can do that.
The easiest is probably to display your original ingredient(s) in the search box again and instruct the user to add more (separated by space, comma, etc.) ingredients if they want to.
Then you can explode your search terms on these characters and add a condition for every ingredient.