I have a form that adds / edits an event.
Namely, I wanted to extend it with the function of adding value automatically (just like increment and ++).
I have statistic_tips in the database containing two lines: stat_win and stat_false
Only during editing (because in principle the editing will usually consist in changing one record) after making changes, I would like to automatically increase the stat_win or stat_false line depending on the selected option (win, loss from results).
How do you achieve this, my dear?
Prompt? Possibly I would like to hear better solutions with a pleasant desire.
I apologize for a mistaken question, but I am a beginner
In red I marked the fragment, where I tried to figure it out, but unfortunately it failed.
<?php
function undefinedIndex(){
}
set_error_handler("undefinedIndex", E_NOTICE);
if(isset($_POST['add_tip'])){
$team1=$_POST['team1'];
$team2=$_POST['team2'];
$league=$_POST['league'];
$datentime=$_POST['datentime'];
$draw=$_POST['draw'];
$results=$_POST['results'];
$sql_insert="INSERT INTO premium_tips(datentime, league, team1, team2, draw, results) VALUES ('$datentime','$league','$team1','$team2','$draw','$results')";
if ($conn->query($sql_insert) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
if(isset($_POST['update_tip'])){
$team1=$_POST['team1u'];
$team2=$_POST['team2u'];
$league=$_POST['leagueu'];
$datentime=$_POST['datentimeu'];
$draw=$_POST['drawu'];
$results=$_POST['resultsu'];
$id=$_POST['id'];
[color="#FF0000"] $win1=$mysqli->query('SELECT stat_win FROM statistic_tips');
$loss1=$mysqli->query('SELECT stat_false FROM statistic_tips');
if($results=="win"){
$sql_insert="
UPDATE statistic_tips (stat_win) VALUES '$win1+=1'";
}
if($results=="loss"){
$sql_insert="
UPDATE statistic_tips (stat_false) VALUES '$loss1+=1'";
}[/color]
$sql_insert="
UPDATE premium_tips SET datentime='$datentime', league='$league',team1='$team1', team2='$team2',draw='$draw', results='$results' WHERE id='$id'";
if ($conn->query($sql_insert) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
And here is the file responsible for the editing form
$sql_get = "SELECT * FROM matches WHERE match_id='$q'";
$result = $conn->query($sql_get);
if($result->num_rows>0){
while($row = $result->fetch_assoc()){
echo '<form role="form" method="post" action=""
onreset="resetAction()">
<div class="form-group">
<label>Match info</label>
<input class="form-control" placeholder="Date of match" type="datetime-local" name="datentime" required><br>
<input class="form-control" placeholder="League" name="league" required><br>
<input class="form-control" placeholder="Stadium" name="stadium" required>
</div>
<div class="form-group">
<label>Home</label>
<input class="form-control" placeholder="Enter team name" name="team1" required>
</div>
<div class="form-group">
<label>Away</label>
<input class="form-control" placeholder="Enter team name" name="team2" required>
</div>
<button type="submit" class="btn btn-default" name="add_match">Add Match</button>
<button type="reset" class="btn btn-default">Reset</button>
</form>';
In fact, I mean automatic statistics on the WON / LOSS chart
At the beginning, when adding, each type has $ result = actual and when editing it is changed to either $ result = win or $ result = loss
I do not know if he combines well with these statistics.
UPDATE statistic_tips (stat_win) VALUES '$win1+=1'
This isn't valid SQL syntax.
What you're looking for is:
UPDATE statistic_tips SET stat_win = stat_win + 1 WHERE id = ?
Note that you don't need to select the previous value from the database beforehand -- the UPDATE query will increment it in place.
Related
How to convert Array to String?
I insert data into the database in the
form of an array. Mysql database show me Array keyword instead of String. I have multiple text boxes with the same name. Interface
<?php
$conn = mysqli_connect('localhost', 'root', '','registeruserdb');
if(!$conn){
die("Failed to Connect. Contact Network Administrator");
}
// insert Category into category table
if (isset($_POST['submitbtn']))
{
$name = $_POST['Name'];
$relationship = $_POST['Relationship'];
$cnic = $_POST['Cnic'];
$contact = $_POST['Contact'];
$query="INSERT INTO registeruser(name,relationship,cnic,contactnumber) VALUES('$name','$relationship','$cnic','$contact')";
if(mysqli_query($conn, $query))
{
echo '<script>
alert("Added successfully.");
window.location="index.php";
</script>';
}
else
{
echo '<script>alert("ERROR: Could not able to execute $sql. ") </script>';
}
}
?>
Register Form:
<form class="form-horizontal" method="post">
<div class="control-group">
<div class="inc">
<div class="controls">
<input type="text" required name="Name[]" placeholder="Name"/>
<input type="text" required name="Relationship[]" placeholder="Relationship"/>
<input type="text" required name="Cnic[]" placeholder="Cnic#"/>
<input type="text" required name="Contact[]" placeholder="Contact#"/>
<button style="margin-left: 50px" class="btn btn-info" type="submit" id="append" name="append">
Add Textbox</button>
<br>
<br>
</div>
</div>
<button type="submit" class="btn btn-info" name="submitbtn"/>Submit</button>
</div>
</form>
You have two options to convert an array to string:
The simplest one is the implode function. This however can create problems when the delimiter you use is featured in any of the array-elements.
The second common method is serialize. It's a common practice to store a serialized array as string in a database, but know that it can lead to some headaches if you want to commit extended searches in the future based on that field. However for simply reading the data, you can just unseralize it.
But the best solution for this sort of problem is usually to create a table for your values with some foreign keys. It really depends on your intentions for the future: if you're expecting lots of records and you intend to query them a lot, I would really advise that method. If not, you can use the above methods to save some time.
I have a small app where the user adds 3-4 ticket in a single Form via the 'Add Another Ticket' button. These text boxes are generated via Jquery .append() and each ticket has 5 input boxes in it. Code Below
<form action="ticket-addcode.php" method="post" enctype="multipart/form-data" class="my-form">
<span id="tixmegaform">
<input type="hidden" name="Eventid" value="<?php echo $eventid; ?>" />
<div class="AddRow">
<label>Package Name</label>
<input class="requierd" type="text" name="ticketgroup" placeholder="Enter the Package Name. Most Preferably Event name" id="EN" value="<?php echo $ticketgroup; ?>">
</div>
<h5>Ticket 1</h5>
<div class="AddRow">
<label>Ticket Title</label>
<input class="requierd" type="text" name="tname[]" placeholder="Enter the Package Name. Most Preferably Event name" id="EN">
</div>
<div class="AddRow">
<label>Ticket Desc</label>
<input class="requierd" type="text" name="tdesc[]" placeholder="Enter the Details" id="EN">
</div>
<div class="AddRow">
<label>Ticket Cost</label>
<input class="requierd" type="text" name="tprice[]" placeholder="Enter the ticket Cost in Numbers. No Currency" id="EN">
</div>
<div class="AddRow">
<label>Ticket Book URL</label>
<input class="requierd" type="text" name="turl[]" placeholder="Enter the URL without http" id="EN">
</div>
<div class="AddRow">
<label>Time</label>
<input type="text" class="left requierd" name="eventTime[]" id="timeformatExample1" placeholder="Start">
</div>
<div class="AddRow">
<label>Date</label>
<input class="requierd" type="text" name="tdate[]" placeholder="Enter the Package Name. Most Preferably Event name" id="from">
</div>
</span>
<input type="submit" name="submit" class="add_field_button_submit">
</form>
</div>
</div>
</div>
<div class="add_field_button">Add Another Ticket</div>
</div>
So, when I hit the Submit button, a nested foreach runs through an array generated by the submit button. I'm able to fetch the values out of the array but somehow the output is not useful to me. Below is the foreach & the output
foreach ($_POST as $pos => $newarr) {
foreach($newarr as $res => $final){
echo $pos.'-----'.$final.'<br>';
}
}
Output
**tname-----VIP tix
tdesc-----Early Bird Desc
tdesc-----VIP Desc Tix
tprice-----5000
tprice-----10000
turl-----google.com
turl-----yahoo.com
eventTime-----00:30:00
eventTime-----00:00:45
tdate-----2-2-2016
tdate-----3-3-2016**
I tried to use an Insert Statement, but it just won't work. It seems that my foreach is resolving the sub array (tname array) and the outer array. If my foreach could just fetch values of different key and not the entire subarray, I would be able to insert the record into db.
Can you guide me on how to achieve this and where to put the INSERT Statement?
I don't think looping over $_POST as you have done will do you any good. Notice how the order of your information coming out makes it difficult?
Instead pick any of your array fields to determine first the number of tickets you have. Then use the number of tickets for iterating over each ticket. This way you can get the index of each group (ticket) of related information together. With the index, you can get all the information related for the group.
Once you have the necessary information, you can either store each information by doing one insert at a time or by doing one big insert. For simplicity, we shall use the former approach (using PDO).
Below is a rough and untested sketch of how it might look:
try {
$dbh = new PDO($dsn, $user, $password);
// prepare your SQL statement
$sth = $dbh->prepare("INSERT INTO table (title, desc, price, url) VALUES(?, ?, ?, ?)");
// loop over each ticket information
for ($i = 0, $numTickets = count($_POST['tname']); $i < $numTickets; $i++) {
$title = $_POST['tname'][$i];
$desc = $_POST['tdesc'][$i];
$price = $_POST['tprice'][$i];
$url = $_POST['turl'][$i];
// insert information into database
$sth->execute(array($title, $desc, $price, $url));
}
} catch (PDOException $e) {
// if something goes wrong, add some logic
}
For more information on PDO, read the documentation.
Use below format of SQL for insertion:
Example:
INSERT INTO tbl_name
(a,b,c)
VALUE (7,8,9);
As per your code:
$sql01 = "INSERT INTO tbl_name (tname,tdesc,tprice, turl) VALUES ";
foreach ($_POST as $pos => $newarr) {
$sql01 .= "(";
$sql01 .= isset($_POST['tname'])?array_merge($_POST['tname'],","):"";
$sql01 .= isset($_POST['tdesc'])?array_merge($_POST['tdesc'],","):"";
$sql01 .= isset($_POST['tprice'])?array_merge($_POST['tprice'],","):"";
$sql01 .= isset($_POST['turl'])?array_merge($_POST['turl'],","):"";
$sql01 .= ")";
}
mysql_query($sql01);
I have a forum where a user can enter in a job they are looking for which would be submitted to a database and then displayed on the following page. Only I can't get any of the data to upload, and I'm not sure why.
I'm also struggling with ways to error check. Any ideas?
// Check for job submission
if(isset($_POST['submit']))
//empty error array
$error = array();
// check for a things in the field
if(empty($_POST['job']))
{
$error[] = 'Please fill in all required fields';
}
// iff there are no errors, insert the job listing into the database.
// otherwies, display error.
if(sizeof($error) == 0)
{
// insert job listing
$query = "INSERT INTO job (
job_id,
user_id,
jobtitle,
company,
location,
summary,
responsibilities,
skills
) VALUES (
null,
'{$_SESSION['user_id']}',
'{$_POST['jobtitle']}',
'{$_POST['company']}',
'{$_POST['location']}',
'{$_POST['summary']}',
'{$_POST['responsibilities']}',
'{$_POST['skills']}',
NOW()
)";
$result = mysqli_query($dbc, $query) or die('Query failed: ' . mysqli_error($dbc));
// display a confirmation
echo "<div class=\"alert alert success\">Your job listing has been added</div>";
} else {
// display error message
foreach($error as $value)
{
echo "<div class=\"alert alert-danger\"{$value}</div>";
}
}
?>
<!-- Job listing Form -->
<form method="post" action="listings.php">
<div class="form-group">
<label> Job Title </label>
<input name ="jobtitle" type="text" class="jobform"/>
<label>Company/Organization</label>
<input name="company" type="text" class="jobform"/>
<label> Job Location </label>
<input name ="location" type="text" class="jobform"/>
<label> Job Responsibilities </label>
<textarea name="summary" rows="8" cols="20" class="jobfourm"></textarea>
<label> Job Responsibilities </label>
<textarea name="responsibilities" rows="8" cols="20" class="jobfourm"></textarea>
<label> Job Skills </label>
<textarea name="skills" rows="8" cols="20" class="jobforum"></textarea>
</div>
<div class="form-group">
<input name="submit" type="submit" value="Submit" class="btn btn-large btn-primary" />
</div>
</form>
</div>
My bets are on your query:
(
job_id,
user_id,
jobtitle,
company,
location,
summary,
responsibilities,
skills
) VALUES (
null,
'{$_SESSION['user_id']}',
'{$_POST['jobtitle']}',
'{$_POST['company']}',
'{$_POST['location']}',
'{$_POST['summary']}',
'{$_POST['responsibilities']}',
'{$_POST['skills']}',
NOW()
for what should be job_id, you're passing null. Now, I'm going to assume that all jobs must have a job ID, correct? You need to actually pass in a valid id, as I'm going to bet money (or rep) that that's a non nullable field in the table. Additionally, you've added a column in your values that you have not declared in your column name parameter.
I've created a simple customer signup form (signup.html) to capture 3 fields (email, subdomain and plan).
I also want to assign them a random password, I've lifted the code to generate this from this SO article (Generating a random password in php).
My PHP code (insert.php) is saving the form data fine into MySQL, but not the result from the randomPassword function, where it places "()" in the field instead of the randomly generated password I am hoping for.
I gather I'm not calling the result from the randomPassword() function properly. What am I doing wrong here?
SIGNUP.HTML
<form action="insert.php" method="post" class="inline-form">
<div class="form-group">
<label for="email">Your email address</label>
<input type="email" name="email" class="form-control input-lg" id="email" placeholder="Enter email">
</div><br><br>
<label>Select your plan</label><br>
<div class="radio">
<label>
<input type="radio" name="plan" id="plan" value="optionA" checked>
Option A
</label>
</div><br>
<div class="radio">
<label>
<input type="radio" name="plan" id="plan" value="optionB">
Option B
</label><br><br>
</div>
<div class="form-group">
<label for="subdomain">Pick your subdomain
</label>
<input type="text" name ="subdomain" class="form-control input-lg" id="subdomain">
</div>
<br><br>
<button type="submit" class="btn btn-teal" name="Sign Up">Sign me up!</button>
</form>
INSERT.PHP
<?php
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function randomPassword() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass); //turn the array into a string
}
$sql="INSERT INTO accounts (email, plan, subdomain, password)
VALUES
('$_POST[email]','$_POST[plan]','$_POST[subdomain]','$randomPassword()')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
It doesn't look like you assign a variable to contain the password at all. Functions don't just execute on their own. Use the following:
$myPass=randomPassword();
$sql="INSERT INTO accounts (email, plan, subdomain, password)
VALUES
('$_POST[email]','$_POST[plan]','$_POST[subdomain]','$myPass')";
A function on it's own is just sitting there WAITING to be executed, but doesn't fire off on it's own. In this case, the function returns a value (the password it makes). To actually get it, you write code like $myPass=randomPassword(); which then executes the function and the value is passed into the variable.
As you don't appear to be a veteran, I will expand some more. If you aren't sure why to have a function rather than just execute the code in the first place, a function can be used over and over. Lets say I did the following:
$myPass1=randomPassword();
$myPass2=randomPassword();
With that one function I now have two totally different passwords stored in the variables. You can do all sorts of other fancy things, but think of a function as a snippet of code that is to be re-used within your code, hopefully on a number of occasions - without the need to have it written many times.
Perhaps this would work
$sql="INSERT INTO accounts (email, plan, subdomain, password)
VALUES ('$_POST[email]','$_POST[plan]','$_POST[subdomain]','randomPassword()')";
I'm designing a crud app to store storage data in a database. Using php, mySQL (with the help of XAMPP). I keep running into this problem, though, where I click "Submit" on my form and the function appears to run successfully (I get a the success message on the php page), but when I look at the actual database, the row fills 3 of the fields (the first 1 and the last 2) with just "0" regardless of what's in the form when I click submit. And then the other two columns don't have anything in them at all.
Here's my code for the form:
<div id="newprojform">
<fieldset><legend>Create New Project</legend>
<form action='projectadded.php' name="addnewproject" onsubmit="return(validate());">
<div id="newprojfields"><br />
Project Name:
<div class="field">
<input type="text" name="projname" size="50">
</div>
<br /><br />
Customer:
<div class="field">
<input type="text" name="custname" size="50">
</div>
<br /> <br />
Move ID:
<div class="field">
<input type ="text" name="moveID" size="50">
</div>
<br /><br />
<label for="unit">Unit of Measurement: </label>
<div class="field" id="uomdd">
<select id="unit" name="unit">
<option value="Select">Select</option>
<option value="CWT">CWT</option>
<option value="Vault">Vault</option>
<option value="SqFt">SqFt</option>
<option value="Pallet">Pallet</option>
<option value="Piececount">Piece Count</option>
</select>
</div>
<br /><br />
Cost Per Unit:
<div class="field">
<input type="text" name="cost" size="50">
</div>
<br /> <br />
<input type="submit" value="Add Project" id="submit"><br />
</div>
</form></fieldset>
</div>
And here's the php
<?php
$con=mysqli_connect("localhost","root","", "storagelog");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO newproject (moveid, projectname, customername, UoM, PPU)
VALUES
('$_POST[moveID]','$_POST[projname]','$_POST[custname]','$_POST[unit]','$_POST[cost]')";
if(!mysqli_query($con,$sql))
{
die ('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Can anybody please tell me what I'm doing wrong? I've gone over the syntax and names of the forms a million times, but every time I click "submit," I just get a row that either has zeros in it or nothing at all. This is all very new to me, so i'm expecting a lot of stupid or clunky mistakes, but this is the first time I'v ever been so stuck..
any help is appreciated.
The problem is that you aren't specifying POST as the method in your form, but you are trying to read the form variables from the $_POST variable. See this thread: What is the default form HTTP method? for information about the form defaults. To fix it, you just need to change your form to this:
<form action='projectadded.php' name="addnewproject" onsubmit="return(validate());" method="POST">
There are some other things you should change in here, like sanitizing your inputs before putting them into the database, but those aren't the root of your problem.
So first things first. I don't recommend using unfiltered $_POST and $_GET variables when dealing with the database (in a production setting of course).
Second, when using the form element, you have to specify whether you're using a post method, or a get method:
<form action="location_of_file.php" method="POST">
Also, make sure you check that your column names in the table absolutely match the names in your sql insert syntax.
Maybe even try the following to see if it inserts:
$sql="INSERT INTO newproject (`moveid`, `projectname`, `customername`, `UoM`, `PPU`)
VALUES ('" . $_POST["moveID"] . "','" . $_POST["projname"] . "','" . $_POST["custname"] . "','" . $_POST["unit"] . "','" . $_POST["cost"] . "')";
Sometimes, SQL can be touchy.
Lol, dang... seanmk beat me to the punch. If what we suggest works, choose his answer as he was first to post it.
For future reference (aside from the excellent advice in the other answers) you should consider printing out $sql to see what your actual insert statement looks like. You'd see immediately that your values are empty strings and would know to go chase after the $_POST to see why it's arriving empty.