I'm building a custom CMS and I've written a script that is supposed to edit already existing information in my database.
I've used the code for a different database before and it has worked without any troubles, but I've changed the index names to reference a new database and now it won't work.
The information is displayed on a page with an 'edit' button the links the user to a html form which displays the selected piece of info in a text box.
There's no problem displaying the info in the form, but once the submit button is pressed the code does not execute it, and the info is not updated and no error message is displayed..
so I'm fairly sure there's a problem somewhere in this... (Ignore the comments)
if (isset($_GET['edittimeslot']))
{
$timeslotid = $_GET['timeslotid'];
try
{
$sql = "SELECT timeslotid, Time FROM timeslots WHERE timeslotid = timeslotid" ;
//echo $sql;
$data = $pdo->query($sql);
$timeslots = $data->fetch();
//print_r($acts);
}
catch(PDOException $e)
{
echo "this didnt work" .$e->getMessage() ;
}
$pagetitle = 'Edit your date here';
$timeslotid = $timeslots['timeslotid'];
$time = $timeslots['Time'];
$button = 'Edit timeslot';
include 'timeslot.form.php';
exit();
}
// is all of the requested feilds appropiate
if (isset($_POST['submit']) && $_POST['submit'] == 'Edit timeslot')
{
// get the form data that was posted ready to insert into the stage database
$timeslotid = $_POST['timeslotid'];
$time= htmlspecialchars($_POST['time']);
try
{
// prepare the query to insert data into stages table
$sql = "UPDATE timeslots
SET Time = :Time,
WHERE timeslotid = :timeslotid";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':Time', $time);
$stmt->bindParam(':timeslotid', $timeslotid);
$stmt->execute();
}
catch(PDOException $e)
{
//error message goes here if the insert fails
}
}
HTML:
<!doctype html>
<head>
<style type="text/css">
.container {
width: 800px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="container">
<h1><?php echo $pagetitle;?></h1>
<form action='.' method='post'>
<!-- stage name -->
<p><label for='time'> What is the timeslots you would like to add? 00:00-00:00 </label></p>
<p><input type='text' name='time' id='time' value='<?php echo $time;?>'> </p>
<p><input type='submit' name='submit' value='<?php echo $button;?>'></p>
</form>
</div>
</body>
Shouldn't WHERE timeslotid = timeslotid be WHERE timeslotid = $timeslotid ?
Also, using a form value directly is a bad idea. Use it at least like $timeslotid = (int)$_GET['timeslotid'];.
Okay one thing that I see right away is this line:
$timeslotid = $_POST['timeslotid'];
Where is that form field in your form? I don't see it anywhere. Also try to assign the execution to a variable and var_dump it so you can see if it returns TRUE or FALSE:
$success = $stmt->execute();
var_dump($success);
Furthermore make sure that you DB column is named Time and not time with all lowercase.
Related
my code looks like this
when I refresh the page it's duplicating the last value how to avoid this problem. This is the quoa.php code! I have tried adding distinct but its working fine but there is no use problem still on there?
phpcode
<?php
/* connection inclution code will be here */
include 'connection/conn.php';
//defining the variables to the text fields
$question = $_POST['qst'];
$questionext = $_POST['qsttextarea'];
//validating the text fields , if there is no text show the msg after else
if(isset($_POST['qst']) && isset($_POST['qsttextarea']))
{
} else {
$pleasefill = "please fill all the fields";
}
//sending data to the database
$mysqlinsert = "INSERT INTO questions(qsttable,qstext) VALUES ('$question','$questionext')";
//header("Location: success.php");
if (!mysqli_query($connection,$mysqlinsert)) {
echo " record not inserted";
} else {
$submited = (" your question is submited please wait for the response");
}
//getting data from the database
if ($data = mysqli_query($connection,"select distinct * from questions")); {
}
?>
show record code
<?php
while($row=mysqli_fetch_array($data)) {
echo '
<div id="question_div"> <span class="fa fa-chevron-right" id="spantick"></span> '.''.$row['qsttable'].' <br />'.'<p id="qstext">'.$row['qstext'].' </p> </div> ' ;
}echo ' Read more ';
?>
You should perform html validation in your input fields ,in that way when you refresh the page all the fields will be empty and previous values will not be stored.
Just add 'required' keyword in your fields ,that will do.
eg.
I am using a form. (I wanted the message text as a text area but changed back to normal text to see if this was the problem)
This is the form I am using
<form name="addmessage" method="POST" action="addmessage.php" >
<input type="text" name="message_title" id="message_title">Message Title</input>
<input type="text" name="message_text" id="message_text">Message</input>
<input type="submit" name="submit" value = Add>
</form>
Below is the PHP code. I understand i need to protect against sql injection however, i can do this later.
<?php
include_once("config.php");
if(isset($_POST["message_title"]) && strlen($_POST["message_title"])>0)
{
$message_title=$_POST['message_title'];
$message_text=$_POST['message_text'];
session_start();
$barber_id = $_SESSION['barber_id'];
$insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."',".$message_text.")");
}
else
{
//Output error
header('HTTP/1.1 500 Error You have left it blank');
exit();
}
header("location:messages.php");
?>
If manually enter data using phpMyAdmin, I can get it to display using the code below.
include_once("config.php");
session_start();
$barber_id = $_SESSION['barber_id'];
$results = $mysqli->query("SELECT * FROM messages WHERE barber_id ='$barber_id' ");
//get all records from table
while($row = $results->fetch_assoc())
{
$prices_id = $row['prices_id'];
echo '<div data-role="collapsible">';
echo '<h1>';
echo ' Message Title: ';
echo $row['message_title'];
echo '</a>';
echo '</h1>';
echo '<p>';
echo $row['message_text'];
echo ' Delete</div>';
}
$mysqli->close();
?>
At $insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."',".$message_text.")");
you should write
$insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."','".$message_text."')");
Everytime you pass a String or other non int values you must pass them like that: 'xx', otherwise mysql will see it as query param and it crashes.
I have this function on my php:
function getLastMatchs($nb) {
try
{
$db = new PDO(DBHOST, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
die('connexion failed: '.$e->getMessage());
}
$i=0;
$get5tmatchs = $db->query('SELECT wid, lid, date, cwid, clid FROM `match`');
while ($nb<$i)
{
$data5matchs = $get5tmatchs->fetch();
echo '<tr>
<td>'.$data5matchs['wid'].'</td>';
echo '<td>'.$data5matchs['lid'].'</td>';
echo '<td>'.$data5matchs['cwid'].'</td>';
echo '<td>'.$data5matchs['clid'].'</td>';
echo '<td>'.$data5matchs['date'].'</td>
<br>
</tr>';
$i++;
}
}
And my form is:
echo '<form action="index.php" method="post">
<h3>My question......</h3>
<p>
<input type="text" name="nbmatchs" />
<input type="submit" value="ok" />
</p>
</form>';
echo getLastMatchs('nbmatchs');
How can i do for show nbmatch time the guys want my table ?
When i do now, nothing happen.
Thanks for your help
PS: For exemple i tape 5, i can see 5 time the tabe i have put in my function.
What you indended to accomplish (as far I understood) to allow a visitor enter a numer and then submit it after what some "matches" data it shown. The number visitor entered acts as a limiter.
1. Where do you get your POST variables? You have placed a function below the form with an input value of string 'nbmatchs'. I guess you wanted to submit the form and get the 'nbmatches' value and then apply it to the SQL query for filtering. The way you have done it doesn't work. You have action attribute on your form element set to index.php. That's where we are going to submit the form data. So we need to have a way to get the submitted POST variables. We do it like this:
$nbmatchs = $_POST['nbmatchs'];
Never trust data client has given you. As we know that it must a number let's do a check on it:
$nbmatches = is_numeric(trim($_POST['nbmatchs'])) ? $_POST['nbmatchs'] : 1;
Above we checked if the data client has given really is a number. If it is we'll assign this nubmer to variable $nbmatches. If the data client has given is not a number (eg. some string) we assign number 1 to the variable. At this point we may end the script execution a let the visitor know he must enter a number but we just assign 1 to the variable if anything seems suspicious. After that we can submit this variable to the function getLastMatchs which takes the variable and assigns it to the SQL query as a results limiter. Assuming that all the code will be in one file 'index.php' you should have the following code:
<?php
function getLastMatchs($nbmatches) {
try{
$db = new PDO(DBHOST, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
die('connexion failed: '.$e->getMessage());
}
try {
$select = $db->prepare('SELECT wid, lid, date, cwid, clid FROM `match` LIMIT '.$nbmatches.';');
$select->execute();
$results = $select->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $ex) {
echo "<span style='color:red'>".$ex->getMessage()."</span></p>";
}
echo '<table>';
foreach($results as $result){
$output = '<tr>';
$output .= '<td>'.$result['wid'].'</td>';
$output .= '<td>'.$result['lid'].'</td>';
$output .= '<td>'.$result['cwid'].'</td>';
$output .= '<td>'.$result['clid'].'</td>';
$output .= '<td>'.$result['date'].'</td>';
$output = '</tr>';
echo $output;
}
echo '</table>';
}
if(isset($_POST['nbmatchs'])){
$nbmatches = is_numeric(trim($_POST['nbmatchs'])) ? $_POST['nbmatchs'] : 1;
getLastMatchs($nbmatches);
}
?>
<form action="index.php" method="post">
<h3>My question......</h3>
<p>
<input type="text" name="nbmatchs" />
<input type="submit" value="ok" />
</p>
</form>
Let me know if this works the way you wanted.
I'm trying to write a function that will allow a user to enter a name into a field, insert the field to a MySQL table and then update a dropdown menu to include those names (while allowing for further additions).
On first load of the page, the dropdown menu shows the correct names that I seeded into the table. When I input a name into the form, it inserts to the table correctly, but then none of the options show in the dropdown list and it removes my entry form. If I refresh the page, everything comes back fine, and the names previously entered show up in the list.
I know I'm missing something obvious in the code to refresh the page, but I'm not even sure what to search for. I thought that by setting my form action to .$_SERVER['PHP_SELF']. it would cause the page to process and reload. I have a hunch this is where my problem is, but I'm not sure what it is.
The dropdown code was something I found off the web, perhaps I have to rewrite it myself, though it's the one part of this mess that's actually working.
Also, the mysql login is hardcoded in db_tools.php b/c I can't get it to work otherwise.
Sorry for the following wall of text, but I'm just trying to provide the most information possible. Thank you for your replies and pointing me in the right direction.
I have 2 files, db_tools.php and dropdown.inc
db_tools.php:
<?php
require_once 'db_login.php';
require_once 'MDB2.php';
require_once("dropdown.inc");
//Define a function to perform the database insert and display the names
function insert_db($name){
//initialize db connection
//$dsn = 'mysql://$db_username:$db_password#$db_hostname/$db_database';
$dsn = "mysql://redacted";
$mdb2 =& MDB2::connect($dsn);
if (PEAR::isError($mdb2)) {
//die($mdb2->getMessage());
die($mdb2->getDebugInfo());
}
//Manipulation query
$sql = " INSERT INTO participants (id, name) VALUES (NULL, \"$name\");";
$affected =& $mdb2->exec($sql);
if (PEAR::isError($affected)){
//die($affected->getMessage());
die($affected->getDebugInfo());
}
//Display query
$query = "SELECT * FROM participants;";
$result =& $mdb2->query($query);
if (PEAR::isError($result)){
die ($result->getMessage());
}
while ($row = $result->fetchRow()){
echo $row[1] . "\n";
}
$mdb2->disconnect();
}
?>
<html>
<head>
<title>Event Bill Splitter</title>
<body>
<?php
$name = $_POST['name'];
if ($name != NULL){
insert_db($name);
}
else {
echo '
<h1>Enter a new participant</h1>
<form name="nameForm" action="'.$_SERVER['PHP_SELF'].'" method="POST">
Name:<input name="name" type="text" />
</form>';
}
?>
<p>Participants:<br />
<?php dropdown(id, name, participants, name, participant_name1); ?></p>
</body>
</head>
</html>
dropdown.inc
require_once ('db_login.php');
$connection = mysql_connect($db_host, $db_username, $db_password);
if (!$connection) {
die ("Could not connect to the database: <br />". mysql_error() );
}
$db_select = mysql_select_db($db_database);
if (!$db_select) {
die ("Could not select the database: <br />". mysql_error() );
}
function dropdown($intNameID, $strNameField, $strTableName, $strOrderField, $strNameOrdinal, $strMethod="asc") {
//
// PHP DYNAMIC DROP-DOWN BOX - HTML SELECT
//
// 2006-05, 2008-09, 2009-04 http://kimbriggs.com/computers/
echo "<select name=\"$strNameOrdinal\">\n";
echo "<option value=\"NULL\">Select Value</option>\n";
$strQuery = "select $intNameID, $strNameField
from $strTableName
order by $strOrderField $strMethod";
$rsrcResult = mysql_query($strQuery);
while($arrayRow = mysql_fetch_assoc($rsrcResult)) {
$strA = $arrayRow["$intNameID"];
$strB = $arrayRow["$strNameField"];
echo "<option value=\"$strA\">$strB</option>\n";
}
echo "</select>";
}
?>
The problem of the form disappearing is simple, just remove the else after the insert section:
<body>
<?php
$name = $_POST['name'];
if ($name != NULL){
insert_db($name);
}
// else { // gone
echo '
<h1>Enter a new participant</h1>
<form name="nameForm" action="'.$_SERVER['PHP_SELF'].'" method="POST">
Name:<input name="name" type="text" />
</form>';
// } // gone
?>
Apart from that I would definitely re-write the dropdown code and add some security, a whitelist for table names, etc.
By the way, you are calling your function in a strange way:
<?php dropdown(id, name, participants, name, participant_name1); ?>
I assume these are variables so it should be $id etc, but where do they come from? If you mean to send values directly, it should be:
<?php dropdown('id', 'name', 'participants', 'name', 'participant_name1'); ?>
I need some help I am trying to create a PHP form using sqlite3 database. I am looking up values from from an existing sqlite3 database in the table2 where the column id = 340 and display those values as a dropdown selection. Then once the value is selected by the user then the form is submitted by the users which updates the new values to the table1 with the values from the php form. I get it to display the names in the dropdown but when I click on the update button to submit the data it updates what the value is in the array.
For example lets say I have 3 fruits in the table and I select pear it updates the table with a "1" instead of the word "pear"
apple
pear
peach
PHP entry page Code:
<html>
<head>
<title></title>
</head>
<div class = "controlbox">
<body style="font-size:12;font-family:verdana">
<form action="post.php" method="post">
<p>
<h1> </h1>
<br>
<br>
Slot1 : <select name="slot1">
<option>--Available Options--</option>
<?php
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e)
{
echo $e->getMessage();
}
$stmt2 = $db->query ("SELECT * FROM table2 where ID = '340' ");
$rowarray = $stmt2->fetchall(PDO::FETCH_ASSOC);
$slot1 = 0;
foreach($rowarray as $row)
{
echo "<option value = $slot1 >$row[FirstName] $row[LastName]</option>";
$slot1++;
}
?>
</select><br>
<p>
<input type="submit" name="update" value="update">
</p>
</form>
</body>
</html>
PHP Code: Post.php
<?php
$slot1 = sqlite_escape_string($_POST['slot1']);
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e)
{
echo $e->getMessage();
}
if (!empty($slot1)) {
try
{
$stmt = $db->prepare("UPDATE table1 SET Slot1place = :slot1 WHERE ID = '340'");
$stmt->bindParam(':slot1', $slot1,PDO::PARAM_STR);
$stmt->execute();
}
catch(Exception $e)
{
echo $e->getMessage();
}
echo "submitted successfully";
}
?>
You dont use sqlite_escape_string if youre using a prepared statement like that. The values are going to be quoted witn they are bound to the statement.
I think you should check your html syntax (Is it missing tags, and the ).
Check it out at: http://www.w3schools.com/html5/tag_option.asp
echo "<option name = $name >$row[FirstName] $row[LastName]</option>";
Everything else is the right syntax