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.
Related
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.
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 form to submit with post, to my table in my database. However whenever I hit submit is says failure. I had several validation scripts that I removed to try and figure out why the form was not submitting.
I checked many of the answered questions regarding INSERT using mysqli_query, but none seemed to answer my question. I am aware the HTML structure is probably poor, this is just to get the script working correctly first. its really not complicated, I don't understand whats wrong here.
I have a registration form, and my other forms on the site I'm working on all work fine, update date their tables correctly. Don't know what I'm missing here.
<?php
include('db.php');
$event_name='';
$place='';
$time='';
$date='';
$description='';
$event_name=strip_tags($_POST['event_name']);
$place=strip_tags($_POST['place']);
$time=strip_tags($_POST['time']);
$date=strip_tags($_POST['date']);
$description=strip_tags($_POST['event_description']);
if(isset($_POST['submit'])) {
$query = "INSERT INTO user_posts (title, location, time, date, description)";
$query .= "VALUES ($event_name','$place','$time','$date','$description')";
if (mysqli_query($connection, $query)) {
echo "<h2> your post has been submitted </h2>";
}
else {
die('failure');
}
}
and the html form
<body>
<div class="box-1">
<form action="create_post_script.php" method="post" id="event_form">
<div class="box-2">
<input type="text" name="event_name" placeholder="event title" />
</div>
<div class="box-3">
<input type="text" name="place" placeholder="location" id="box-3" />
</div>
<div class="box-4">
<input type="time" name="time" id="box-4" />
</div>
<div class="box-4">
<input type="date" name="date" id="box-4" />
</div>
<div class="box-5">
<h4> <center> ... </center> </h4>
<textarea class="text-area" name="event_description" id="event_form" >
</textarea>
<input type="submit" value="submit" name="submit" placeholder="submit"/>
</div>
<div class="box-6">
<div class="box-7">
<h4> </h4>
</div>
</div>
</form>
</div>
When I hit submit, the resulting page confirms my connection and says 'failure', is this because of the way that I have the submit input field for the <text-area>?
try this
$query = "INSERT INTO user_posts (title, location, time, date, description) ";
$query .= "VALUES ('$event_name','$place','$time','$date','$description')";
you missing single quotes
<?php
$query = "INSERT INTO user_posts (title, location, time, date, description)";
$query .= "VALUES ('$event_name','$place','$time','$date','$description')";
// ^^^
// here missing single quotes
echo $query;
?>
Code look's fine, but only one thing you're missing a single quote ' in inserting values.
$query .= "VALUES ($event_name','$place','$time','$date','$description')";
Change To
$query .= "VALUES ('$event_name','$place','$time','$date','$description')";
I have a scenario. Let's say someone is on my website and there is a form which adds an event for example and there is a field as follows:
<input type="text" name="title" id="title">
Let's say that person used F12 developer tools and changes the id="title" to id="whatever", or even remove the id attribute, then how would I make my PHP script stop running so that nothing is posted to MySQL?
Here's an example for a Bookmarks feature I have: (front-end form)
<form action="bookmarks.php" method="post" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label" for="input-mini">Title*</label>
<div class="controls">
<input class="span12" id="title" name="title" type="text" placeholder="e.g. Oliver's pet cat...">
</div>
</div><!-- /control-group -->
<div class="control-group">
<label class="control-label" for="input-mini">Link*</label>
<div class="controls">
<input class="span12" id="link" name="link" type="text" placeholder="e.g. http://boopeo.com">
<input type="hidden" name="parse_var" id="parse_var" value="addbookmark" />
<br /><input name="submit" type="submit" class="btn btn-success span12" value="Bookmark" /></form>
Back-end PHP:
if (isset($_POST['parse_var'])){
$parser = $_POST['parse_var'];
$parser = htmlspecialchars($parser);
if ($parser == "addbookmark"){
$title = $_POST['title'];
$title = htmlspecialchars($title);
$linkurl = $_POST['link'];
$linkurl = htmlspecialchars($linkurl);
$sqlrecentmark = $db->query("SELECT link_url FROM tablenamehere WHERE mem_id='$id' ORDER BY id DESC LIMIT 20");
while($row = $sqlrecentmark->fetch(PDO::FETCH_ASSOC)) {
$recent_link = $row["link_url"];
}
if ( $linkurl != $recent_link ){
$dataact = array( 'mem_id' => $id, 'title' => $title, 'link_url' => $linkurl );
$sqlactivity = $db->prepare("INSERT INTO tablenamehere (mem_id, title, link_url) value (:mem_id, :title, :link_url)");
$sqlactivity->execute($dataact);
} else {
$not_msg = '<br /><br /><div class="alert alert-error">Oops! You have added that bookmark before. Just look and you shall find!</div>';
}
}
}
Never trust data from the user. Always sanitize and validate. You are using prepared statements which is good, so you'll be mostly protected from injection. The other thing you'll want to do is determine if the data the user has sent you matches up with what you were expecting, if it does then proceed to use it with the database. (Which you are for the most part doing, so in all honesty there should be no bad effects from a malicious user)
The id of input field doesn't get passed as posted data, so there's no way to tell in the back-end php code. Maybe you're talking about the name attribute.
<input type="text" name="theTitle" id="aTitle">
In my above example, the input field will be posted as $_POST["theTitle"]
You could use javascript to check these elements before the form is submitted, but if you're worried about the user manipulating the DOM, that probably won't help much.
After reading your concern about the Undefined index error, you simply need to check if the variable is set before you use it:
if(isset($_POST["title"])) {
$title = $_POST['title'];
} else {
//output error
}
Hey Fellow Programmers,
I have a slight problem and I cant find the right answer online.
Basically what I need to do is, a user inserts content into a text box and then selects a check box. Whichever check box is selected is what table the text box content is supposed to insert into. **Both check boxes can be selected so the user can upload to two diff tables, before you ask no I cannot just upload to a diff row it has to be a completely diff table.
Let me know if I am not clear, and thanks in advance
HTML CODE:
<body class="login">
<div class="wrapper">
<h1><img src="img/logo-big.png" alt="" class='retina-ready' width="59" height="49">FLAT</h1>
<div class="login-body">
<form action="db_pre_panel.php" name="login" class='form-validate' id="test" method="post">
<div class="control-group">
<div class="email controls">
<h3>TEST</h3>
<input type="text" name="content" maxlength="500" placeholder="Content" />
</div>
</div>
<div class="control-group">
<input type="checkbox" name="Ck_1" /> <label>Ck_1</label>//If selected then INSERT content into tbl_connect
<input type="checkbox" name="Ck_2" /> <label>Ck_2</label>//If selected then INSERT content into tbl_share
</div>
<div class="submit">
<input type="submit" value="Simplicity" />
</div>
PHP CODE:
<?php
//Define Content, Post & Share
$content=$_POST['content'];
$post=$_POST['ck_1'];
$share=$_POST['ck_2'];
//Insert into the db
$sql_post="INSERT INTO $tbl_connect (wall) VALUES ('$connect', '$post')";
$sql_share="INSERT INTO $tbl_share (wall) VALUES ('$connect', '$share')";
//Make sure it insert into db
$result_post = mysql_query($sql_post);
$result_share = mysql_query($sql_share);
if($result_post){
header("location:alert.php");
}else{
header("location:error.html");
}
if($result_share){
header("location:http://www.google.com");
}else{
header("location:error.html");
}
?>
Just keep it simple:
//Define Content, Post & Share
$content = $_POST['content']; // you should sanitize this to prevent SQL injection
if ( !empty($_POST['ck_1']) ) {
$sql_post = "INSERT INTO `tbl_connect` (wall) VALUES ('$connect')"; // if you have more than one value, then you need to specify more than one column...
}
if ( !empty($_POST['ck_2']) ) {
$sql_share = "INSERT INTO `tbl_share` (wall) VALUES ('$connect')";
}