Unable to Submit to Database - php

Using the MVC Framework, I have made some code that is meant to add information to the Database.
In Index.php (views)
<form method="post" action="<?php echo URL;?>note/updatetopic">
<select>
<option value="1">Coasts</option>
<option value="2">Energy Demand</option>
</select>
<input type="submit" name="topic_selection" value="Choose" />
</form>
The Code above is meant to post information about what a user would like to revise.
In note.php (controllers)
public function updatetopic() {
if (isset($_POST['topic_selection'])) {
$note_model = $this->loadModel('Note');
$note_model->updatetopic($_POST['topic_selection']);
}
header('location: ' . URL . 'note');
}
The Code above is meant to get information from the code in index.php and forward it onto the note_model where it runs a function.
In note_model.php (models)
public function updatetopic($topic_selection)
{
$topic_selection = strip_tags($topic_selection);
$sql = "INSERT INTO users (topic_revising) VALUES (:topicselected) WHERE user_id=:user_id";
$query = $this->db->prepare($sql);
$query->execute(array(':topicselected' => $topic_selection, ':user_id' => $_SESSION['user_id']));
$count = $query->rowCount();
if ($count == 1) {
return true;
} else {
$_SESSION["feedback_negative"][] = TOPIC_UPDATE_FAILED;
}
// default return
return false;
}
This is meant to validate the submitted information and insert it into the database but it outputs:
$_SESSION["feedback_negative"][] = TOPIC_UPDATE_FAILED;
Can someone please help me and tell me what im doing wrong? Thanks.

You are not choosing any name for your select tag:
try like this:
<select name="topic">
<option value="1">Coasts</option>
<option value="2">Energy Demand</option>
</select>
And now get the the value of yuor drop down list:
if (isset($_POST['topic'])) {
$note_model = $this->loadModel('Note');
$note_model->updatetopic($_POST['topic']);
// $_POST['topic'] == 1 or 2 depends upon selection
}
you can change it like:
<select name="topic">
<option value="coasts">Coasts</option>
<option value="Energy_Demand">Energy Demand</option>
</select>
now u'll get the real value of selected list item and can move further....

Your SQL query will not work as you have tagged mysql which does not support this kind of syntax:
INSERT INTO users (topic_revising) VALUES (:topicselected) WHERE user_id=:user_id
Basically there is no WHERE in MySQL (MySQL Insert Where query)
You should check for duplicated either in select query, or if there are unique keys - use ON DUPLICATE KEY. Also take a look at the linked topic

Related

Show existing value as pre-selected in drop down, radio buttons and checkboxes fields

I have a network that I am building which groups freelancers together and allows potential customers to browse a profile containing their details.
In my database I store some values that the user will enter via a form using drop down or radio/checkbox fields. Through an edit page they can amend that data.
I'm struggling with how to get those fields pre-populated (if the value exists in the DB) with the value they've already made, probably at the time of creating their profile. I have managed to do it with the regular text/input fields by echoing out the column value as a form field value but can't figure out how to achieve it with these other fields.
UPDATE: I need to pull the value from the database and have the form fields show that as the pre-selected/default entry.
If I leave them blank it means the user will overwrite any existing data with nothing and in erase anything they've entered for that field before.
An example drop down field is below;
<div class="item-content">
<div>Experience</div>
<select class="form-control" name="profile_experience" id="profile_experience">
<option value="1">Amateur</option>
<option value="2">Semi Professional</option>
<option value="3">Professional</option>
</select>
</div>
I'm fetching the values with the following;
<?php
$id=$_SESSION['user']['id'];
$result = $db->prepare("SELECT * FROM profiles WHERE user_id= :userid");
$result->bindParam(':userid', $id);
$result->execute();
for($i=0; $currentprofile = $result->fetch(); $i++){
?>
<!--FORM HERE-->
<?php
}
?>
Retrieve and stote the stored values
<?php
$query = "SELECT id FROM Tablename WHERE YOUR_CONDITION";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
$selectedOption = $row['id'];
}
else
{
$selectedOption = ''; // Your default selection of $cc
}
$profile_experience_array = array(1=>'Amateur',
2=>'Semi Professional',
3=>'Professional');
?>
The below code displays all the options of profile_experience_array. $key will check with the database value ($selectedOption) and that text will get selected by default.
<div class="item-content">
<div>Experience</div>
<select class="form-control" name="profile_experience" id="profile_experience">
<option value="0">Select</option>
<?php
foreach ($profile_experience_array as $key => $text)
{
if ($key == $selectedOption)
{
echo '<option value="'.$key.'" selected="selected">'.trim($text).'</option>';
}
else
{
echo '<option value="'.$key.'">'.trim($text).'</option>';
}
}
?>
</select>
</div>

Using the result of a select clause for a where clause to MySQL

I have a MySQL database containing 12 columns. I created a dropdown from it using distinct values of the column named 'activity' and the column named 'logdate' which is a datetime.
Like this..
<form action="define_activity" id="activityform" method="post"> <!-- Form to select an activity -->
<select name="activities" id="select1"> <!-- List of activities -->
<option value="" selected="">Select One</option>
<option value="NewActivity" id="newactivity" onclick="newactivity();">New Activity</option>
<?php
foreach($db_found->query("SELECT DISTINCT activity, logdate FROM NetLog ORDER BY activity") as $act) {
echo ("<option value='$act[activity]'>$act[activity] of $act[logdate]</option>");
}
?>
</select>
<input type="submit" name = "Submit" />
</form>
This all works great. what I want to do is use the results of the selected option to do another query against the same database that pulls all of the records associated with the selected activity and logdate values. I know how to write the query but I don't know how to find and then use the selected values.
Can someone please show me how to get the selected value from the
Thanks in advance for your consideration.
I make some changes in your code, I didn't test it, but I think that's going to help you:
<?php
//Returns an associative array with the query result:
function select($yourSQLQuery){
//Array with result:
$result = array();
//Database conection
$db = new PDO($dsn,$username,$password);
$stmt = $db->query($yourSQLQuery);
//This going to save an array with your data:
$result = $stmt->fetchAll(PDO::FETCH_NUM);
$db = null;
return $result;
}
//*********************************************************************************************
//Do here your query:
$result = select("SELECT DISTINCT activity, logdate FROM NetLog ORDER BY activity");
//*********************************************************************************************
//Form handler:
if($_SERVER[REQUEST_METHOD] == "POST"){
//If the form was submited:
//Get selected activity
if ( isset($_POST['activities']) ) {
/*Instead of sending your activity you can send the number of the submitted record in $records, then extract activity and logdate and make your query:*/
$rowNumber = $_POST['activities'];
//Get your log date:
$act = $result[$rowNumber]; //if doesn't work try '$rowNumber'
$activity = $act['activity'];
$logdate = $act['logdate'];
//Pull records asocciated with submitted activity:
$sql = "SELECT * FROM putHereYourTable WHERE activity = '$activity' AND logdate='$logdate'";
$records = select($sql);
//Pulled activities are now in $records
//do something with the records that you want. e.g.:
print_r($records);
}
}
?>
<!-- Your HTML: -->
<form action="define_activity" id="activityform" method="post"> <!-- Form to select an activity -->
<select name="activities" id="select1"> <!-- List of activities -->
<option value="" selected="">Select One</option>
<option value="NewActivity" id="newactivity" onclick="newactivity();">New Activity</option>
<?php
foreach($result as $key => $act) {
//Send the number of register instead of $act[activity]:
echo ("<option value='$key'>$act[activity] of $act[logdate]</option>");
}
?>
</select>
<input type="submit" name = "Submit" />
</form>
You need to submit the form first.
<form action="define_activity" id="activityform" method="post">
You need to submit to a valid page in your action param. So if 'define_activity' is not a valid URL (ie: not handled by htaccess) then you need to either A) use the same script/file your using or B) create another page to handle the data.
I would do this:
<form action="process.php" id="activityform" method="post">
process.php
<?php
if ( isset($_POST['activities']) ) {
// do something with the submitted data
$selectedValue = $_POST['activities'];
}
Now you have the selected value. You have also any other value that is submitted in the form, $_POST['othervalue'].
For a clear view of what is sent, dump it.
die('<pre>' . print_r($_POST, true) . '</pre>');
or you could use var_dump: die( var_dump($_POST) );
Keith,
You have to remember that web applications work in a client server environment over the HTTP protocol.
After your page is done loading the first time, the php script is basically done executing. In order for more code to run, another request needs to be sent to the server. This happens when you either:
a) submit a form or click a link that sends a new http request to the page
b) make some javascript send a new HTTP request to the page.
Since you're just getting started, lets assume you just want that form to send the new request off to the page.
So at the top of your php script, just add this statement:
print_r($_REQUEST);
As you visit the page that is running the script both with and without clicking the submit post button, you will be able to see the various request parameters show up based on your form post. One of those params will be 'activity' .. just throw an if statement checking to see if that parameter is present, then run your query inside that if statement, using the value of 'activity'
if(isset($_REQUEST['activities'])) {
//do your query here..
}

php: change value of variable based on dropdown list

Learning PHP and having an issue that I can't figure out. I have read that PHP only has scope for functions, so I'm not sure why my switch statement isn't changing the value of variables.
Goal: to change the mysql SELECT statement based on user selection of drop-down.
Form:
<form action="contacts_show.php" method="POST">
<select name="grade" id="grade">
<option value="all">All Levels</option>
<option value="elementary">Elementary</option>
<option value="middle">Middle</option>
<option value="senior">Senior</option>
<input type="submit" name="browse" id="browse" value="Browse" />
</form>
PHP (edited to shorten code):
$levelSelected = $_POST['grade'];
if ($levelSelected == "all") {
$querySelect = "SELECT * FROM teachers ORDER BY school ASC";
} else {
$querySelect = "SELECT * FROM teachers WHERE school LIKE %$levelSelected% ORDER BY school ASC";
}
$query = $querySelect;
$result = mysqli_query($connection, $query);
confirm_query($result);
the confirm_query function, if needed:
function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed.");
}
}
When "All Levels" from drop-down is selected, code runs as expected. When any other option is selected, my confirm_query function states that the query fails.
I'm not sure why the variable's values are not switching.
To elaborate on my comment:
Change LIKE %elementary% to => LIKE '%elementary%' and do the same for the others.
You need to wrap the pattern match in quotes, and as per the manual:
http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html#operator_like
mysql> SELECT 'David!' LIKE '%D%v%';
mysql> SELECT 10 LIKE '1%';
You're also not checking for DB errors.
Add or die(mysqli_error($connection)) to mysqli_query()
If that still doesn't work, then it's also a scope issue.
Pass the connection to your function, do not make it global.

Posted multiselect box selection to database only adding the first selected item

i am using the following multiselect box to take input from users, this then gets posted to my php form which adds it to the database, the problem is, all I am getting added is the first selection, if the user selects more than one field I still only get the first field.
If the user selects lets say internet, drawing,maths I want that to be put into the database, at the moment all that is inserted is internet, or whatever is the first thing selected in the list.
My form looks like this >>
<form action="../files/addtodb.php" method="post" style="width:800px;">
<select name="whatisdeviceusedfor[]" size="1" multiple="multiple" id="whatisdeviceusedfor[]">
<option value="games">Games</option>
<option value="takingphotos">Taking Photos</option>
<option value="maths">Maths</option>
<option value="reading">Reading</option>
<option value="drawing">Drawing</option>
<option value="internet">Internet</option>
<option value="other">Other (enter more info below)</option>
</select>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
The php side looks like this >>
<?php
// Implode what is device used for
$usedfor = $_POST['whatisdeviceusedfor'];
$arr = array($usedfor);
$whatisdeviceusedfor = implode(" ",$arr);
// Insert posted data into database
mysql_query("INSERT INTO itsnb_year5questionaire (whatisdeviceusedfor) VALUES '$whatisdeviceusedfor'") or die(mysql_error());
?>
you are already getting array by select so you dont need to use $arr = array($usedfor);this again
just try
$usedfor = $_POST['whatisdeviceusedfor'];
$whatisdeviceusedfor = implode(" ",$usedfor);
or
$usedfor = $_POST['whatisdeviceusedfor'];
$strings ='';
foreach ($usedfor as $item){
$strings .=' '. $item;
}
echo $strings;
and
<select name="whatisdeviceusedfor[]" size="5" multiple="multiple" id="whatisdeviceusedfor[]">
^^
||change to option you want to select
i have changed size="5" so it will select now 5 at a time ...you have only 1 so it will let only 1 select at a time
result
warning
your code is vulnerable to SQL injection also use of mysql_* function are deprecated use either PDO or MySQLi
If you have selected mutliple items via a SELECT or via CHECKBOXES, the form will return an array-like data structure. You will always need to loop over that data and store each item individually into the database or concatenate the values to a string before inserting.
first change size = "5" to see good the list
then try to make like that (its second option if you like it)
if ($_POST) {
// post data
$games = $_POST["games"];
$takingphotos = $_POST["takingphotos"];
.
...
// secure data
$games = uc($games);
$boats = uc($takingphotos);
.
...
}
// insert data into database
$query = "INSERT INTO itsnb_year5questionaire (games, takingphotos,....)
VALUES('$games','$takingphotos',......)";
mysql_query($query) or die(mysql_error());
echo 'Thanks for your select!';
Because $usedfor is contain the array you can directly use it in foreach to save the each value in the value.Try this it may help you:
<?php
$usedfor = $_POST['whatisdeviceusedfor'];
foreach($usedfor as $arr){
mysql_query('INSERT INTO itsnb_year5questionaire(whatisdeviceusedfor) VALUES("'.$arr.'"') or die(mysql_error());
}

<select><option> and action associated with them

I am writing a reservation system. On the main page I would give a choice of category, viewed the equipment available for booking.
For example I have code like this:
<select>
<option value = "a">A</option>
<option value = "b">B</option>
<option value = "c">C</option>
<option value = "d">D</option>
<option value = "e">E</option>
</select>
I wish that each choice was associated with a separate query to the database, and that was the result of a query dynamically displayed on the screen.
It would be great if you could show me some sample code.
Regards
$query = mysql_query("SELECT * FROM choices");
while($row=mysql_fetch_assoc($query)) {
echo '<option value="'.$row['value'].'">'.$row['value'].'</option>';
}
If you need separate query for each choice the code doesns't change much:
$query = mysql_query("(SELECT * FROM choices) UNION (SELECT * FROM choices1) [etc]");
while($row=mysql_fetch_assoc($query)) {
echo '<option value="'.$row['value'].'">'.$row['value'].'</option>';
}
There are two parts to your question; 1 - Detecting which query to run and 2 - Displaying the results dynamically.
Part 1: Detecting which query to run:
Given hard-coded choices and no parameters for the query, using your above code, you can determine which query to run using the following:
For the HTML part, as part of a form, create the select as you did above (but with a name)
<select name="querySelect">
<option value="a">A</option>
<option value="b">B</option>
</select>
And in the PHP:
$querySelect = $_GET['querySelect'];
switch($querySelect)
{
case 'a':
$sql = "SELECT * FROM TableA";
break;
case 'b':
$sql = "SELECT * FROM TableB";
break;
}
$results = mysql_query($sql);
Part 2: Displaying the results dynamically
With the $results, what you do with the data very much depends on what you want to achieve. At a very basic level, you can do the following to dynamically display a table of the results:
if(mysql_num_rows($results) > 0)
{
$header = false;
print "<table>"
while($row = mysql_fetch_assoc($results))
{
if(!$header)
{
$headings = array_keys($row);
print "<tr>";
for($i=0;$i<count($headings);$i++)
{
print "<th>".htmlspecialchars($headings[$i])."</th>";
}
print "</tr>";
$header = true;
}
print "<tr>";
foreach($row as $value)
{
print "<td>".htmlspecialchars($value)."</td>";
}
print "</tr>";
}
print "</table>"
}
else print "<h1>No Results Found!</h1>";
mysql_free_result($results);
There is still alot not covered in my answer because I can't say what level of detail is required. You will also need to cover things like your connection to MySQL, error handling, formatting of the table...
Update
Hmmm, very interested to know why this has been downvoted. If someone can please explain in comments where I have misinterpreted the question or misguided the user, I would appreciate it.
If you use jQuery the code might look like
<select id="select_id">
<option value = "a">A</option>
<option value = "b">B</option>
<option value = "c">C</option>
<option value = "d">D</option>
<option value = "e">E</option>
</select>
<script type="text/javascript">
$('#select_id').change(function(e) {
// this code send selected value to the server
$.post('url', {selected_value: this.value}, function(response) {
// handle the server's response
});
});
</script>
On server side take the value from $_POST and make a query. And remember - do not trust to data from client-side. You never know who is over there. Always check incoming data and DO NOT use such constructions
$sql = "SELECT * FROM table_name WHERE name = '{$_POST['selected_value']}'";
because there might be any string including those can drop all databases, clear data and so forth.

Categories