Delete button to delete database table row - php

I want to give the users of my website the ability to add, edit and remove questions of a FAQ that's stored on a database. They select the title from a form and then they can press 'select' (to edit the q&a) or 'delete'. Deleting doesn't work.
The first problem is: when they click delete, it leads them to the 'edit' form instead of deleting the database table row.
The second problem: when I make them click the button, I ask to confirm the delete. Whether they press 'Ok' or 'Cancel' doesn't matter, they are always lead to the 'edit' form.
The code in the admin panel (index.php):
if(isset($_POST['actie']) && $_POST['actie'] != "")
{
$actie = $_POST['actie'];
if($actie == "csd_faq") { verwerk_csd_faq($DB); }
if($actie == "csd_faq_edit") { verwerk_edit_csd_faq($DB); }
}
if($GLOBALS['logged_in'] && isset($_GET['actie']) && $_GET['actie'] != "")
{
$actie = $_GET['actie'];
if($actie == "csd_faq") { toon_csd_faq($DB); }
if($actie == "csd_faq_edit") { edit_csd_faq($DB); }
}
The code for the functions:
//ADD FAQ
function toon_csd_faq($DB)
{?>
<h2>Een FAQ toevoegen:</h2>
Gebruik het formulier hieronder om een FAQ toe te voegen.
<br /><br />
<form action='index.php?actie=csd_faq' method='post'>
<input type='hidden' name='actie' value='csd_faq' />
<input type='hidden' name='naam' value='<? echo $GLOBALS['nickname']; ?>' />
Vraag (Q): <br />
<input type='text' name='q' size='80' /><br /><br />
Antwoord (A): <br />
<textarea name='a' cols='80' rows='10'></textarea><br /><br />
<input type='submit' value='Toevoegen' />
</form>
<?}
function verwerk_csd_faq($DB)
{
$naam = $_POST['naam'];
$q = clean($_POST['q']);
$a = clean($_POST['a']);
$DB->q("INSERT INTO `csd_faq` (`datum`, `naam`, `q`, `a`) VALUES (NOW(), '$naam', '$q', '$a')");
echo "<b class='roze'>FAQ succesvol toegevoegd!</b>"
."<br /><br />";
}
// EDIT FAQ
function edit_csd_faq($DB)
{
echo "<h2>Een FAQ bewerken:</h2>";
if(isset($_GET['faq_id'])) //bewerken
{
$faq_id = $_GET['faq_id'];
$faq = $DB->q1("SELECT * FROM `csd_faq` WHERE `faq_id` = '$faq_id'");
?>
Gebruik het formulier hieronder om de FAQ te bewerken
<br /><br />
<form action='index.php?actie=csd_faq_edit' method='post'>
<input type='hidden' name='actie' value='csd_faq_edit' />
<input type='hidden' name='faq_id' value='<? echo $faq_id; ?>' />
<input type='hidden' name='naam' value='<? echo $GLOBALS['nickname']; ?>' />
Vraag (Q): <br />
<input type='text' name='q' size='80' value='<? echo $faq[3]; ?>' /><br /><br />
Antwoord (A): <br />
<textarea name='a' cols='80' rows='10'><? echo $faq[4]; ?></textarea><br /><br />
<input type='submit' name='update' value='Update' />
</form>
<br />
« <a href='javascript:history.go(-1)'>Kies een andere FAQ</a>
<?}
else { //selectie box tonen ?>
Selecteer de te bewerken FAQ.
<br /><br />
<form action='index.php' method='get'>
<input type='hidden' name='actie' value='csd_faq_edit' />
Titel: <br />
<select name='faq_id' size='10' style='width:500px;'>
<?
$result = $DB->q("SELECT * FROM `csd_faq` ORDER BY `datum` DESC");
$lijst = "";
while($faq = $DB->fa($result))
{
$lijst .= "<option value='".$faq[0]."'>".$faq[3]."</option>";
}
echo $lijst;
?>
</select>
<br /><br />
<input type='submit' name='selecteer' value='Selecteer' />
<input type='submit' name='delete' value='Verwijder' onClick='confirm("Zeker dat je deze FAQ wilt verwijderen?")' />
</form>
<?}
}
function verwerk_edit_csd_faq($DB)
{
if(isset($_POST['update'])) {
$faq_id = $_POST['faq_id'];
$naam = $_POST['naam'];
$q = clean($_POST['q']);
$a = clean($_POST['a']);
$DB->q("UPDATE `csd_faq` SET `datum` = NOW(), `naam` = '$naam', `q` = '$q', `a` = '$a' WHERE `faq_id` = '$faq_id'");
echo "<b class='roze'>FAQ succesvol bewerkt!</b>"
."<br /><br />";
}
else if(isset($_GET['delete'])) {
$faq_id = $_GET['faq_id'];
$DB->q("DELETE FROM `csd_faq` WHERE `faq_id` = '$faq_id'");
echo "<b class='roze'>FAQ succesvol verwijderd!</b>"
."<br /><br />";
}
}

You probably want to check for $_POST['delete'] and $_POST['faq_id'], not $_GET['delete'] and $_GET['faq_id'] as the method of the form is POST.

Related

Something wrong while deleting data from DB

I'm trying to delete some information from the database, but when I ask the user to confirm action, something goes wrong. Can you help me?
The script prints the categories to choose if nothing is settled. Then, It asks the user to delete or not delete the categories chosen. In the end, it deletes what was chosen.
But there's some error in the last part(first in the script) and I cannot understad where it's going wrong:
<?php
//If the user confirm to delete...
if(isset($_POST['eliminazione_conferma']) and $_POST['eliminazione_conferma']=='conferma'){
//if conferma_eliminazione=1, don't delete
if(isset($_POST['conferma_eliminazione']) and $_POST['conferma_eliminazione']=='1'){
echo 'Eliminazione annullata';
}else{//Delete if conferma_eliminazione=0
while($row=$categoria){
$delete= "DELETE FROM categorie WHERE $row = category_id";
$query=mysql_query($delete);
echo "$row eliminato\n";
}
}
}else{//ELSE, print the form to confirm action
if(isset($_POST['eliminazione']) and $_POST['eliminazione']=='delete'){
//Array with the chosen "categories"
$categoria=isset($_POST['categoria']) ? $_POST['categoria'] : array();
//Print the chosen categories to ask confirmation
echo'Sicuro di voler eliminare le seguenti categoire?<br />';
foreach($categoria as $row){
echo "$row<br />\n";
}
//Yes = 0, No = 1
echo '<form method="post" action="',$_SERVER['REQUEST_URI'],'">
<input type="radio" name="conferma_elimiazione" value="0" />Si<br />
<input type="radio" name="conferma_eliminzione" value="1" />No<br />
<input type="hidden" name="eliminazione_conferma" value="conferma" />';
foreach($categoria as $row){
echo'<input type="hidden" name="categoria[]" value="',$row,'" />',"\n",'' ;
}
echo'
<input type="submit" value="Conferma" />
</form>';
}else{//In the end, if nothing is settled, print the form to check the category to delete
//Select the categories from the database
echo'<form method="post" action="',$_SERVER['REQUEST_URI'],'" />',"\n",'';
$select = "SELECT nome,category_id FROM categorie ORDER BY category_id" ;
$select_result=mysql_query($select) or die("Mysql Error: ".mysql_error());
while($row = mysql_fetch_assoc($select_result)){
echo '<input type="checkbox" name="categoria[]" value="',$row['category_id'],'">',$row['nome'],'<br />';
}
echo'<input type="hidden" name="eliminazione" value="delete" />
<input type="submit" name="submit" value="Elimina" />
</form>';
}
}
The problem with the query
$delete= "DELETE FROM categorie WHERE $row = category_id";
is
here
WHERE $row = category_id";
What is category_id?
Do you have a value for that?
Probably you want WHERE category_id=/*something here like $row['column_name']*/
Thanks everyone for the help, but I've solved my problem in this way(the script wasn't transformig the value of "conferma_eliminazione" in the integer type):
<h2>Modifica o Elimina Categoria </h2>
<?php
if(isset($_POST['eliminazione_conferma']) and $_POST['eliminazione_conferma']=='conferma'){
$categoria=isset($_POST['categoria']) ? $_POST['categoria'] : array();
$a=(int)$_POST['eliminazione'];
if($a=='1'){
echo 'Eliminazione annullata';
echo "\n";
}elseif($a=='0'){
foreach($categoria as $row){
$delete= "DELETE FROM categorie WHERE $row = category_id";
$query=mysql_query($delete);
echo "$row eliminato\n";
}
}
}else{
if(isset($_POST['eliminazione']) and $_POST['eliminazione']=='delete'){
$categoria=isset($_POST['categoria']) ? $_POST['categoria'] : array();
echo'Sicuro di voler eliminare le seguenti categoire?<br />';
foreach($categoria as $row){
echo '',$row,'<br />',"\n";
}
echo '<form method="post" name="form_eliminazione_categoria" action="',$_SERVER['REQUEST_URI'],'">',"\n",'
<input type="radio" name="eliminazione" value="0" />Si<br />' ,"\n",'
<input type="radio" name="eliminazione" value="1" />No<br />',"\n",'
<input type="hidden" name="eliminazione_conferma" value="conferma" />',"\n",'';
foreach($categoria as $row){
echo '<input type="hidden" name="categoria[]" value="',$row,'" /><br />',"\n",'';
}
echo'
<input type="submit" value="Conferma" />
</form>';
}else{
echo'<form method="post" action="',$_SERVER['REQUEST_URI'],'" />',"\n",'';
$select = "SELECT nome,category_id FROM categorie ORDER BY category_id" ;
$select_result=mysql_query($select) or die("Mysql Error: ".mysql_error());
while($row = mysql_fetch_assoc($select_result)){
echo '<input type="checkbox" name="categoria[]" value="',$row['category_id'],'">',$row['nome'],'<br />';
echo "\n";
}
echo'<input type="hidden" name="eliminazione" value="delete" />',"\n",'
<input type="submit" name="submit" value="Elimina" />',"\n",'
</form>';
}
}

Inserting radio button input in the database

I'm creating a quiz-like structure. For that i'm trying to get the answer of each question and insert it into my database with the type of question that was answered. However i'm having trouble putting these data in variables and i'm getting:
Notice: Undefined index: question-0-answer
in the commented part of the code. Any help..
$options = '';
$filter=mysql_query("select afnumber from employees WHERE Status='Employed '");
while($row = mysql_fetch_array($filter)) {
$options .="<option >" . $row['afnumber'] . "</option>";
}
$menu="<form id='filter' name='filter' method='post' action=''>
AFNumber : <select name='SelectAF' id='filter' style='color:grey;'>" . $options . "</select>
Evaluation Test Type : <select name='Type' id='type' style='color:grey;'><option selected='selected'></option><option value='loyalty'>Loyalty</option><option value='performance'>Performance</option></select>
<input type='submit' name='submit1' value='Submit' style='width:80px; height:30px; text-align:center; padding:0px;'>
</form>
<br>
";
echo $menu;
if(isset($_POST['submit1']))
{
$type = $_POST['Type'];
$mysqli = new mysqli("localhost", "root", "Js", "jr");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if ( $result = $mysqli->query( "SELECT questiontext FROM questioninfo WHERE type='$type'" ) ) {
$html=array();
$html[]="
<form action='' method='post' id='quiz'>
<ol>";
$counter=1;
while( $row = $result->fetch_array() ) {
$question=$row['questiontext'];
$answerA=1;
$answerB=2;
$answerC=3;
$answerD=4;
$answerE=5;
$html[]="
<br/>
<h3>Question {$counter}: {$question}</h3>
<li>
<br/>
<input type='radio' name='question-{$counter}-answers' id='question-{$counter}-answersA' value='A' />
<label for='question-{$counter}-answers-A'> {$answerA} </label>
<br/>
<input type='radio' name='question-{$counter}-answers' id='question-{$counter}-answersB' value='B' />
<label for='question-{$counter}-answers-B'> {$answerB} </label>
<br/>
<input type='radio' name='question-{$counter}-answers' id='question-{$counter}-answersC' value='c' />
<label for='question-{$counter}-answers-C'> {$answerC} </label>
<br/>
<input type='radio' name='question-{$counter}-answers' id='question-{$counter}-answersD' value='D' />
<label for='question-{$counter}-answers-D'> {$answerD} </label>
<br/>
<input type='radio' name='question-{$counter}-answers' id='question-{$counter}-answersE' value='E' />
<label for='question-{$counter}-answers-E'> {$answerE} </label>
</li>";
$counter++;
}
$html[]="
</ol>
<input type='submit' name='submit' value='Submit' style='width:80px; height:30px; text-align:center; padding:0px;'>
<input type='hidden' name='type' value='{$type}' />
</form>";
echo implode( PHP_EOL, $html );
$result->close();
}
}
/*
if( isset( $_POST['submit'] ) ){
$numQuestions=10;
for( $counter=0; $counter < $numQuestions; $counter++ ){
$answer=$_POST['question-'.$counter.'-answers'];
$sql="insert into `question` (`type`,`value`) values ('".$type."','".$answer."')";
$db->query( $sql );
}
}
*/
The $counter for outputting the radiobuttons is initialized with the value 1 but when reading the values of radiobuttons at the end of your script, you are starting with $counter = 0;.
Please change
for( $counter=0; $counter < $numQuestions; $counter++ ){
to
for( $counter=1; $counter <= $numQuestions; $counter++ ){
You are running loop statically 10 times in comment and what if database have less than 10 records? You need to run loop a many times as db having records or you can put condition before insert by isset($_POST['question-'.$counter.'-answers'])

mysql_data_seek not working

my code is,
$query3 = "SELECT * FROM db_exam_skip WHERE user='$session'";
$result3 = mysql_query($query3) or die(mysql_error());
$length3 = mysql_num_rows($result3);
while($rows3 = mysql_fetch_array($result3))
{
$query1 = "SELECT * FROM db_exam_questions WHERE id='$rows3[ques_id]'";
$result1 = mysql_query($query1) or die(mysql_error());
$length1 = mysql_num_rows($result1);
}
if(isset($_POST['next']))
{
if(isset($_SESSION['list']))
{
mysql_data_seek($result1,$_SESSION['list']);
}
else
{
$list = $_POST['list'];
mysql_data_seek($result1,$list);
}
}
<?php
while($rows1 = mysql_fetch_row($result1))
{
$start = $rows1[0];
$_SESSION['start'] = $start;
?>
<form action="" method="post">
<p style="font-size:20px;font-weight:bold"><?php echo $rows1[5]; ?></p>
<ul style="list-style-type:none">
<input type='hidden' name='number' value='<?php echo $_SESSION['order']++; ?>' />
<input type='hidden' name='list' value='<?php echo $_SESSION['list']++; ?>' />
<input type='hidden' name='ques_id' value='<?php echo $rows1[0]; ?>' />
<input type='hidden' name='correct' value='<?php echo $rows1[10]; ?>' />
<li><input type="radio" name="answer" value="1" /> <?php echo $rows1[6]; ?> <br><br>
<input type="radio" name="answer" value="2" /> <?php echo $rows1[7]; ?> <br><br>
<input type="radio" name="answer" value="3" /> <?php echo $rows1[8]; ?> <br><br>
<input type="radio" name="answer" value="4" /> <?php echo $rows1[9]; ?> <br></li>
</ul>
<input type="submit" class="button4" value="Next" name="next" />
</form>
<?php
break;
}
?>
my question is, after the first question is loaded, when i press next button to load the second question I am getting the below error.
Warning: mysql_data_seek(): Offset 2 is invalid for MySQL result index 8 (or the query data is unbuffered) in C:\wamp\www\Albert\ICAMS\start_skip_question.php on line 15
I have tried a lot to solve this error. But till now no success. Is there any method to solve. Any help will be appreciated.
Thank you.
I guess the result set is empty.I think query is returning empty set.
You will get this error if result set is empty
check the PHP DOCS
First check if you are getting ant rows from the result
if (mysqli_num_rows($sql) > 0)
{
}

PHP/MySQL throwing me index error but it's already listed

PHP it's throwing at me
Notice: Undefined index: username in D:\xampp\htdocs\0100348514\pages\account.php on line 16
Warning: mysql_query() expects parameter 1 to be string, resource given in D:\xampp\htdocs\pages\account.php on line 19
But in my database I have it exactly the same 'username' but it's still throwing it at me any ideas?
Code on that page
<?php
$page = "My Account";
session_start();
include '../includes/config.php';
?>
<div id="searchbar">
<form action="search.php" method="get">
<input type="text" name="search" />
<input type="submit" name="submit" class="btn btn-primary" value="Search" />
</form>
</div>
</div>
<?php
$username = $_SESSION['username'];
$sql = "SELECT * FROM login WHERE username = '$username'";
$result = mysql_query($con, $sql) or die(mysql_error($con)); //run the query
$row = mysql_fetch_array($result);
?>
<div id="wrapper">
<section id="content" class="shadow">
<div id="titlebar">
<?php
echo $page = '<h1> My ACCOUNT </h1>';
?>
</div>
<br />
<?php
//user messages
if(isset($_SESSION['error'])) //if session error is set
{
echo '<div class="error">';
echo '<p class="center">' . $_SESSION['error'] . '</p>'; //display error message
echo '</div><br />';
unset($_SESSION['error']); //unset session error
}
elseif(isset($_SESSION['success'])) //if session success is set
{
echo '<div class="success">';
echo '<p class="center">' . $_SESSION['success'] . '</p>'; //display success message
echo '</div><br />';
unset($_SESSION['success']); //unset session success
}
?>
<div id='left'>
<form id="registration" form action="accountprocessing.php" method="post">
<br />
<fieldset><h1>Update Your Details</h1><br />
<ol>
<li>
<label>Username*</label> <input type="text" name="username" required value="<?php echo $row['username'] ?>" readonly />
</li>
<?php
//generate drop-down list for state using enum data type and values from database
$tableName='member';
$colState='state';
function getEnumState($tableName, $colState)
{
global $con; //enable database connection in the function
$sql = "SHOW COLUMNS FROM $tableName WHERE field='$colState'";
//retrieve enum column
$result = mysql_query($con, $sql) or die(mysql_error($con));
//run the query
$row = mysql_fetch_array($result); //store the results in a variable named $row
$type = preg_replace('/(^enum\()/i', '', $row['Type']); //regular expression to replace the enum syntax with blank space
$enumValues = substr($type, 0, -1); //return the enum string
$enumExplode = explode(',', $enumValues); //split the enum string into individual values
return $enumExplode; //return all the enum individual values
}
$enumValues = getEnumState('member', 'state');
echo '<select name="state">';
if((is_null($row['state'])) || (empty($row['state']))) //if the state field is NULL or empty
{
echo "<option value=''>Please select</option>"; //display the 'Please select' message
}
else
{
echo "<option value=" . $row['state'] . ">" . $row['state'] .
"</option>"; //display the selected enum value
}
foreach($enumValues as $value)
{
echo '<option value="' . $removeQuotes = str_replace("'", "",
$value) . '">' . $removeQuotes = str_replace("'", "", $value) . '</option>'; //remove the quotes from the enum values
}
echo '</select><br />';
?>
</li>
<p> </p>
<li>
<label>Postcode*</label> <input type="text" name="postcode" required value="<?php echo $row['postcode'] ?>"/>
</li><br />
<li>
<label>Country*</label> <input type="text" name="country" required value="<?php echo $row['country'] ?>"/>
</li><br />
<li>
<label>Phone</label> <input type="text" name="phone" value="<?php echo $row['phone'] ?>"/>
</li><br />
<li>
<label>Mobile</label> <input type="text" name="mobile" value="<?php echo $row['mobile'] ?>" />
</li><br />
<li>
<label>Email*</label> <input type="email" name="email" required value="<?php echo $row['email'] ?>" />
</li><br />
<li><label>Gender*</label>
<?php
//generate drop-down list for gender using enum data type and values from database
$tableName='member';
$colGender='gender';
function getEnumGender($tableName, $colGender)
{
global $con; //enable database connection in the function
$sql = "SHOW COLUMNS FROM $tableName WHERE field='$colGender'";
//retrieve enum column
$result = mysql_query($con, $sql) or die(mysql_error($con));
//run the query
$row = mysql_fetch_array($result); //store the results in a variable named $row
$type = preg_replace('/(^enum\()/i', '', $row['Type']); //regular expression to replace the enum syntax with blank space
$enumValues = substr($type, 0, -1); //return the enum string
$enumExplode = explode(',', $enumValues); //split the enum string into individual values
return $enumExplode; //return all the enum individual values
}
$enumValues = getEnumGender('member', 'gender');
echo '<select name="gender">';
echo "<option value=" . $row['gender'] . ">" . $row['gender'] .
"</option>"; //display the selected enum value
foreach($enumValues as $value)
{
echo '<option value="' . $removeQuotes = str_replace("'", "",
$value) . '">' . $removeQuotes = str_replace("'", "", $value) . '</option>';
}
echo '</select>';
?>
</li>
</ol>
</fieldset>
<br />
<fieldset>
<p>Subscribe to weekly email newsletter?</p><br />
<label>Yes</label><input type="radio" name="newsletter" value="Y" <?php if($row['newsletter'] == "Y"){echo "checked";} ?>><br />
<label>No</label><input type="radio" name="newsletter" value="N" <?php if($row['newsletter'] == "N"){echo "checked";} ?>>
<input type="hidden" name="memberID" value="<?php echo $memberID; ?>">
</fieldset><br />
<p class="center"><input type="submit" name="accountupdate" value="Update Account" /></p><br />
</form>
</div>
<br />
<div id='right'>
<form id="registration" form action="accountimageprocessing.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="memberID" value="<?php echo $memberID; ?>">
<br />
<fieldset><h1>Update Image</h1><br />
<?php
if((is_null($row['image'])) || (empty($row['image']))) //if the photo field is NULL or empty
{
echo "<p class='center'><img src='../images/members/member.png' width=150 height=150 alt='default photo' /></p>"; //display the default photo
}
else
{
echo "<p class='center'><img src='../images/members/" . ($row['image']) . "'" . 'width=150 height=150 alt="contact photo"' . "/></p><br />"; //display the contact photo
}
?>
<label>New Image</label> <input type="file" name="image" />
<br />
<p>Accepted files are JPG, GIF or PNG. Maximum size is 500kb.</p>
<br />
<p class='center'><input type="submit" name="imageupdate" value="Update Image" /></p>
</form>
<br />
<br />
<form action="accountpasswordprocessing.php" method="post">
<h1>Update Password</h1>
<br />
<p>Passwords must have a minimum of 8 characters.</p> <br />
<label>New Password*</label> <input type="password" name="password" pattern=".{8,}" title= "Password must be 8 characters or more" required />
<br />
<input type="hidden" name="memberID" value="<?php echo $memberID; ?>">
<br />
<p class='center'><input type="submit" name="passwordupdate" value="Update Password" /></p>
<br />
</form>
<h1>Delete My Account</h1>
<br />
<p>We're sorry to hear you'd like to delete your account. By clicking the button below you will permanently delete your account.</p>
<br />
<form action="accountdelete.php" method="post">
<p class='center'><input type="submit" value="Delete My Account" onclick="return confirm('Are you sure you wish to permanently delete your account?');" ></p>
<input type="hidden" name="memberID" value="<?php echo $memberID; ?>"><br />
</fieldset>
</form>
</div>
</section> <!-- end #content -->
<div id="footernav" class id="shadow">
<?php
require "../inc/footer.php";
?>
</div>
</div>
Your mysql_query parameteres are reversed. It should be:
mysql_query($sql, $con);
Also as you can see in the linked PHP Manual page, this extension is deprecated and alternatives should be used:
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information. Alternatives to this function include:
mysqli_query()
PDO::query()

stuck at oop upload image + insert

sorry if my querstion is bad, my english is bad
NB : ignore the sql injection filtering
i am using insert() function that I created myself to insert to database
but i am stuck with these code
I want to upload image to ../images directory. If i insert with image included, text is inserted but image not uploaded
i think the query are not going into
if(!empty($gambar))
{
$dir="../images/";
$tmp=$_FILES['gambar']['tmp_name'];
$namafile=time().".jpg";
$ukuran=$_FILES['gambar']['size'];
$file_type=$_FILES['gambar']['type'];
move_uploaded_file($tmp,$dir.$namafile);
$this->perintah="insert into ".$tbl." (".$kol.",gambar) values (".$isi.",".$namafile.")";
$q=mysql_query($this->perintah);
}
but to
else
{
$this->perintah="insert into ".$tbl." (".$kol.") values (".$isi.")";
$q=mysql_query($this->perintah);
}
i have to declare variables
$gambar = $_FILES['gambar'];
and in form tag too
<form method='post' action='controller.php?act=inputsiswa' name='siswa' enctype='multipart/form-data'>
my question:
whats wrong with my code?
at this lines
public function insert($tbl,$kol,$isi,$gambar)
may i declare variable to
public function insert($tbl,$kol,$isi,$gambar = null)
or
public function insert($tbl,$kol,$isi,empty($gambar))
or what?
All of my codes
model.php
public function insert($tbl,$kol,$isi,$gambar)
{
if(!empty($gambar))
{
$dir="../images/";
$tmp=$_FILES['gambar']['tmp_name'];
$namafile=time().".jpg";
$ukuran=$_FILES['gambar']['size'];
$file_type=$_FILES['gambar']['type'];
move_uploaded_file($tmp,$dir.$namafile);
$this->perintah="insert into ".$tbl." (".$kol.",gambar) values (".$isi.",".$namafile.")";
$q=mysql_query($this->perintah);
}
else
{
$this->perintah="insert into ".$tbl." (".$kol.") values (".$isi.")";
$q=mysql_query($this->perintah);
}
echo '<script> alert("Data Berhasil Dimasukkan!"); top.location="index.php?act='.htmlentities($_GET['act']).'";</script>';
if(!$q)
{
echo "<script> alert(\"Gagal Coy !\"); top.location=\"index.php\";</script>";
exit();
}
}
controller.php
case "inputsiswa":
$file = $_FILES['gambar'];
$isi = "'".$_POST['nisn']."','".$_POST['username']."','".$_POST['password']."','".$_POST['nama']."','".$_POST['tempat_lahir']."','".$_POST['tanggal_lahir']."','".$_POST['jenis_kelamin']."','".$_POST['kelas']."','".$_POST['jurusan']."','".$_POST['tipekelas']."','".$_POST['goldar']."','".$_POST['alamat']."','".$_POST['kodepos']."','".$_POST['kontak']."','".$_POST['email']."','Aktif'";
$kol = "nisn,username,password,nama,tempat_lahir,tgl_lahir,jenkel,id_kelas,id_jurusan,id_tipe_kelas,id_goldar,alamat,kode_pos,kontak,email,status";
$as->insert("tbl_siswa",$kol,$isi,$file);
content.php
<form method='post' action='controller.php?act=inputsiswa' name='siswa' enctype='multipart/form-data'>
NISN<br /><input type='text' name='nisn' class='text' required/><br />
Username<br /><input type='text' name='username' class='text' required/><br />
Password<br /><input type='password' name='password' class='text' required/><br />
Ulangi Password<br /><input type='password' name='password2' class='text' required/><br />
Nama Lengkap<br /><input type='text' name='nama' class='text' required/><br />
Tempat Lahir<br /><input type='text' name='tempat_lahir' class='text' required/><br />
Tanggal Lahir <br /><input type='text' name='tanggal_lahir' class='text' required/><br />
Jenis Kelamin <br />
<select name ='jenkel'>
<option value=''>pilih jenis kelamin..</option>
<option value='Pria'>Pria</option>
<option value='Wanita'>Wanita</option>
</select>
<br>
Kelas<br>
<select name='kelas'>
<option value ='0'>pilih kelas..</option>";
$tbl='tbl_kelas';
$isi = $as->select($tbl,'*');
while($r=mysql_fetch_array($isi)){
echo"<option value=$r[id_kelas]>$r[kelas]</option>";
}
echo"</select><br />
Jurusan<br>
<select name='jurusan'>
<option value ='0'>pilih jurusan..</option>";
$tbl='tbl_jurusan';
$isi = $as->select($tbl,'*');
while($r=mysql_fetch_array($isi)){
echo"<option value=$r[id_jurusan]>$r[jurusan]</option>";
}
echo"</select><br />
Tipe Kelas<br>
<select name='tipekelas'>
<option value ='0'>pilih tipe kelas..</option>";
$tbl='tbl_tipe_kelas';
$isi = $as->select($tbl,'*');
while($r=mysql_fetch_array($isi)){
echo"<option value=$r[id_tipe_kelas]>$r[tipe_kelas]</option>";
}
echo"</select><br />
Golongan Darah<br>
<select name='goldar'>
<option value ='0'>pilih golongan darah..</option>";
$tbl='tbl_goldar';
$isi = $as->select($tbl,'*');
while($r=mysql_fetch_array($isi)){
echo"<option value=$r[id_goldar]>$r[nama_goldar]</option>";
}
echo"</select><br />
Alamat<br />
<textarea name='alamat'></textarea><br />
Kode Pos <br /><input type='text' name='kodepos' class='text' /><br />
Kontak <br /><input type='text' name='kontak' class='text' required/><br />
Email <br /><input type='text' name='email' class='text' /><br />
Foto <br /><input type='file' name='gambar' class='text'/><br /><br>
<div style='width:500px; margin-top:-10px;'><input class='graybutton' type='submit' value='Tambahkan'> <input class='graybutton' type='reset' value='Ulangi'></div>
</form>";
In your HTML, you have:
Foto <br /><input type='file' name='gambar' class='text'/><br /><br>
But in your PHP you have:
$file = $_POST['gambar'];
Perhaps I'm missing what you are doing, but surely it should be:
$file = $_FILES['gambar'];
Or am I missing something?
Galih, we've all been noob. But please give us more detail of your problems, instead of "it doesn't work and you're stuck".
Yes, from your codes, the answer from Ralfe is one of the possibilities, and the comment from Kemal Fadillah about query fails is the other one.
From me, if you are doing image upload to the server, make sure the server's directory is writable by the application e.g the PHP.
And be aware from SQL injection since you insert the user's input to MySQL server without any filtering.

Categories