Access denied to database table for MySQL/PHP code - php

I am new to PHP and MySQL, but not coding in general. I am attempting to migrate an Access database into MySQL.
I get the following error after submitting my form information and trying to add a record to the table:
Access denied for user ''#'localhost' to database 'FltLogbook'
In order for the form to build, I access the database to pull out certain values for drop down menus. All of that works fine. After clicking the "Add Entry" button and using the Post method, the above error is shown.
I am very confused since previous queries ran just fine, but once I try to "add" the record, I get the error. The above error appears to be an anonymous connection. FWIW, the Username I connect with has all priviledges to the database. I have tried adding records with that username inside the form building portion of the code and was successful. You will see in the code below I have commented out my actual Insert code. I was troubleshooting data types and trying to simplify the insert command to eliminate other fields causing the error. The current insert command code works fine in the form building portion of the code, so I know I have the correct code, now I just to solve the connection issue.
After much searching on this site and google, most of the responses to the above error usually involve granting user permissions. I don't think that is the problem here since I can add a record inside the form building portion of the code. It appears I go from being an authenticated user to anonymous since no username is not passed in the error. I used connection_status() in both parts of the code and it returns 0 (Normal).
Any help is certainly appreciated. Cheers, Heed
Code:
$conn = mysqli_connect("localhost", $_POST[user], $_POST[password], "FltLogbook");
if ($_POST[op] != "add") {
//Form not shown, show it
$display="<h1>Add Logbook Entry</h1>";
$CnxSt = connection_status();
$display .= "Connection Status: $CnxSt<br><br>";
$display .= "
<form method=\"post\" action=\"$_SERVER[PHP_SELF]\">
<strong>Details:</strong>
<table border=\"1\" width=\"520\">
<tr>
<td><input type=\"checkbox\" name=\"Sim\">Simulator</td>
<td colspan=\"2\">SimType: <select name=\"SimType\">
<option value=\"\"> NA </option>
<option value=\"Miltary Visual\"> Military Visual </option>
<option value=\"Military Non-Visual\"> Military Non-Visual </option>
<option value=\"ATD\"> ATD </option>
<option value=\"FTD\"> FTD </option>
<option value=\"FFS\"> FFS </option></select></td>
</tr>
<tr>
<td>Date: <input type=\"date\" name=\"FltDate\"></td>
<td>Aircraft: <select name=\"Aircraft\">
<option selected=\"selected\" value=\"26\">C-172M</option>";
$AcftQuery="SELECT Aircraft.AirKey,Aircraft.Aircraft, Aircraft.ME, Aircraft.Complex, Aircraft.HighPerf
FROM Aircraft";
$AcftResult=mysqli_query($conn, $AcftQuery) or die ("Aircraft Query Failed");
While ($AcftRow=mysqli_fetch_array($AcftResult)) {
$AcftKey=$AcftRow['AirKey'];
$AcftAircraft=$AcftRow['Aircraft'];
$AcftME=$AcftRow['ME'];
$AcftComplex=$AcftRow['Complex'];
$AcftHP=$AcftRow['HighPerf'];
$display .= "<option value=\"$AcftKey\"> $AcftAircraft </option>";
}
$display .= "
</select>
</td>
<td>Aircraft ID: <input type=\"text\" name=\"ID\" size=\"8\"></td>
</tr>
<tr>
<td>From: <select name=\"From\">
<option selected=\"selected\" value=\"PVG\">PVG</option>";
$ArfldQuery="SELECT AirfieldID FROM Airfields ORDER BY AirfieldID";
$ArfldResult=mysqli_query($conn, $ArfldQuery) or die ("Airfield Query Failed");
While ($ArfldRow=mysqli_fetch_array($ArfldResult)) {
$Arfld=$ArfldRow['AirfieldID'];
$display .= "<option value=\"$Arfld\"> $Arfld </option>";
}
$display .= "
</select>
</td>
<td>To: <select name=\"To\">
<option selected=\"selected\" value=\"PVG\">PVG</option>";
$ArfldQuery="SELECT AirfieldID FROM Airfields ORDER BY AirfieldID";
$ArfldResult=mysqli_query($conn, $ArfldQuery) or die ("Airfield Query Failed");
While ($ArfldRow=mysqli_fetch_array($ArfldResult)) {
$Arfld=$ArfldRow['AirfieldID'];
$display .= "<option value=\"$Arfld\"> $Arfld </option>";
}
$display .= "
</select>
</td>
<td>Leg: <select name=\"Leg\">
<option value=\"1\">1</option>
<option value=\"2\">2</option>
<option value=\"3\">3</option>
<option value=\"4\">4</option>
<option value=\"5\">5</option>
<option value=\"6\">6</option>
</select>
</td>
</tr>
</table><br>
<strong>Flight Time Info:</strong>
<table border=\"1\" width=\"520\">
<tr>
<td>TPT: <input type=\"text\" name=\"TPT\" size=\"4\"></td>
<td>PIC: <input type=\"text\" name=\"PIC\" size=\"4\"></td>
<td>SIC: <input type=\"text\" name=\"SIC\" value=\"0.0\" size=\"4\"></td>
</tr>
<tr>
<td>Solo: <input type=\"text\" name=\"Solo\" value=\"0.0\" size=\"4\"></td>
<td colspan=\"2\">Dual Received: <input type=\"text\" name=\"Dual\" value=\"0.0\" size=\"4\"></td>
</tr>
<tr>
<td>Cross Country: <input type=\"text\" name=\"XC\" value=\"0.0\" size=\"4\"></td>
<td><input type=\"checkbox\" name=\"FARXCntry\" size=\"4\">FAR X-Cntry</td>
<td><input type=\"checkbox\" name=\"ATPXCntry\" size=\"4\">ATP X-Cntry</td>
</tr>
<tr>
<td>Single Engine: <input type=\"text\" name=\"SE\" size=\"4\"></td>
<td>Multiengine: <input type=\"text\" name=\"ME\" size=\"4\"></td>
<td>Night: <input type=\"text\" name=\"NT\" value=\"0.0\" size=\"4\"></td>
</tr>
<tr>
<td>Complex: <input type=\"text\" name=\"Complex\" value=\"0.0\" size=\"4\"></td>
<td colspan=\"2\">High Performance: <input type=\"text\" name=\"HP\" value=\"0.0\" size=\"4\"></td>
</tr>
<tr>
<td>Instrument: <input type=\"text\" name=\"Inst\" value=\"0.0\" size=\"4\"></td>
<td colspan=\"2\">Sim Instrument: <input type=\"text\" name=\"SimInst\" value=\"0.0\" size=\"4\"></td>
</tr>
<tr>
<td>Instructor: <input type=\"text\" name=\"Instructor\" value=\"0.0\" size=\"4\"></td>
<td>Pre-Post: <input type=\"text\" name=\"PrePost\" value=\"0.0\" size=\"4\"></td>
<td>Ground: <input type=\"text\" name=\"Ground\" value=\"0.0\" size=\"4\"></td>
</tr>
</table><br>
<strong>Actual Approaches:</strong>
<table border=\"1\" width=\"520\">
<tr>
<td>Precision: <input type=\"text\" name=\"PrecAct\" value=\"0\" size=\"3\"></td>
<td>Non-Precision: <input type=\"text\" name=\"NonPrecAct\" value=\"0\" size=\"3\"></td>
</tr>
</table><br>
<strong>Simulated Approaches:</strong>
<table border=\"1\" width=\"520\">
<tr>
<td>Precision: <input type=\"text\" name=\"PrecSim\" value=\"0\" size=\"3\"></td>
<td>Non-Precision: <input type=\"text\" name=\"NonPrecSim\" value=\"0\" size=\"3\"></td>
</tr>
</table><br>
<strong>Landings:</strong>
<table border=\"1\" width=\"520\">
<tr>
<td>Day Landings: <input type=\"text\" name=\"DayLdg\" size=\"3\"></td>
<td>Night Landings: <input type=\"text\" name=\"NtLdg\" size=\"3\"></td>
</tr>
</table><br>
<strong>Remarks:</strong><br>
<textarea name=\"Remarks\" rows=\"5\" cols=\"70\"></textarea>
<input type=\"hidden\" name=\"op\" value=\"add\">
<p><input type=\"submit\" name=\"submit\" value=\"Add Entry\"></p>
</FORM>";
} else if ($_POST[op] == "add") {
if ($_POST[Sim] == "") {
$_POST[Sim] = "0";
} else {
$_POST[Sim] = "1";
}
if ($_POST[FARXCntry] == "") {
$_POST[FARXCntry] = "0";
} else {
$_POST[FARXCntry] = "1";
}
if ($_POST[ATPXCntry] == "") {
$_POST[ATPXCntry] = "0";
} else {
$_POST[ATPXCntry] = "1";
}
// $add_flt = "INSERT INTO FlightData (Date, MakeModel, AircraftID, Simulator, SimType, AfldFrom, AfldTo,
// Leg, TPT, PIC, SIC, Solo, Dual, Night, XCntry, SE, ME, Complex, HighPerf, Inst_Act, Inst_Sim,
// Instructor, PrePost, Ground, Prec_Act, Prec_Sim, NonPrec_Act, NonPrec_Sim, DCL, NCL,
// FAR_XCntry, ATP_XCntry, Remarks)
// VALUES ('$_POST[FltDate]', '$_POST[Aircraft]', '$_POST[ID],$_POST[Sim]', '$_POST[SimType]', '$_POST[From]',
// '$_POST[To]', '$_POST[Leg]', '$_POST[TPT]', '$_POST[PIC]', '$_POST[SIC]', '$_POST[Solo]', '$_POST[Dual]',
// '$_POST[NT]', '$_POST[XC]', '$_POST[SE]', '$_POST[ME]', '$_POST[Complex]', '$_POST[HP]', '$_POST[Inst]',
// '$_POST[SimInst]', '$_POST[Instructor]', '$_POST[PrePost]', '$_POST[Ground]', '$_POST[PrecAct]',
// '$_POST[PrecSim]', '$_POST[NonPrecAct]', '$_POST[NonPreSim]', '$_POST[DayLdg]', '$_POST[NtLdg]',
// '$_POST[FARXCntry]', '$_POST[ATPXCntry]', '$_POST[Remarks]')";
$add_flt = "INSERT INTO FlightData (Date, MakeModel) VALUES ('$_POST[FltDate]', '$_POST[Aircraft]')";
mysqli_query($conn, $add_flt) or die('Error: '. mysqli_connect_error());
$display = "<h1>Entry Added</h1>
<p>Your entry was added.</p><br>
<p>$_POST[FltDate] | $_POST[Aircraft] </p>";
// $CnxSt = connection_status();
// $display .= "Connection Status: $CnxSt<br><br>";
// $display .= "$user / $pwd<br>$add_flt<br>";
// $display .= "$_POST[FltDate] / $_POST[Aircraft] / $_POST[ID] / $_POST[Sim] / $_POST[FARXCntry] / $_POST[ATPXCntry]";
}
?>
<html>
<head>
<title>Add Logbook Entry></title>
</head>
<body>
<?php echo $display; ?>
</body>
</html>

You must check your mysql username and password on line 1
if username="root" & password is null then
$conn = mysqli_connect("localhost", "root", "", "FltLogbook");

Related

PHP method post cannot store data to database, no error generated

After searching for problems identical to mine and found no solution I decided to ask here.
I have 2 tables in 1 db, one is "produk" the other is "sparepart" both have the exact same number and name of columns.
I wrote the exact same code of HTML and PHP, just changed the table name so the data will be stored to their respective table.
the problem is the data from produk.php is stored in produk table but, the data from sparepart.php is not stored in sparepart table after query.
I tried checking for errors, but no error generated and instead it echoes "success".
please take a look at my simplified code :
HTML
<?php echo "<header><h3>TAMBAHKAN PRODUK SPAREPART</h3></header>
<form method=POST action='$aksi?module=sparepart&act=input' enctype='multipart/form-data'>
<div class='module_content'>
<table id='rounded-corner'>
<tr>
<td width=70>Nama Produk</td>
<td> : <input type=text name='nama_produk' size=60></td>
</tr>
<tr>
<td>Kategori</td>
<td> :
<select name='kategori'>
<option value=0 selected>- Pilih Kategori -</option>";
$tampil=mysql_query("SELECT * FROM kategori ORDER BY nama_kategori");
while($r=mysql_fetch_array($tampil)){
echo "<option value=$r[id_kategori]>$r[nama_kategori]</option>";
}
echo "</select>
</td>
</tr>
<tr>
<td>Kategori 2</td>
<td> :
<select name='kategori2'>
<option value=0 selected>- Pilih Kategori2 -</option>";
$tampil2=mysql_query("SELECT * FROM kategori2 ORDER BY nama_kategori2");
while($r2=mysql_fetch_array($tampil2)){
echo "<option value=$r2[id_kategori2]>$r2[nama_kategori2]</option>";
}
echo "</select>
</td>
</tr>
<tr>
<td>Harga </td>
<td> : <input type=text name='harga' size=10></td>
</tr>
<tr>
<td>Stok</td>
<td> : <input type=text name='stok' size=5></td>
</tr>
<tr>
<td>Diskon</td>
<td> : <input type=text name='diskon' size=5></td>
</tr>
<tr>
<td>Potongan</td>
<td> : <input type=tetxt name='potongan' size=10></td>
</tr>
<tr>
<td valign=top>Deskripsi</td>
<td> <textarea name='deskripsi' style='width: 600px; height: 350px;'></textarea></td>
</tr>
<tr>
<td>Gambar</td>
<td> : <input type=file name='fupload' size=40>
<br>Tipe gambar disarankan JPG/JPEG dan ukuran lebar maks: 400 px
</td>
</tr>
<tr>
<td colspan=2>
<input type=submit class='button' value=Simpan>
<input type=button class='button' value=Batal onclick=self.history.back()>
</td>
</tr>
</table>
</form>";?>
and the PHP :
<?php
$module=$_GET[module];
$act=$_GET[act];
$produk_seo = seo_title($_POST['nama_produk']);
if (!empty($lokasi_file)){
// Cek file type
if (($tipe_file =="image/jpeg" OR $tipe_file=="image/gif" OR
$tipe_file=="image/png" OR $tipe_file=="image/wbmp" )){
UploadImage($nama_file_unik);
$query1 ="INSERT INTO sparepart(nama_produk,
produk_seo,
id_kategori,
id_kategori2,
berat,
harga,
diskon,
stok,
deskripsi,
tgl_masuk,
potongan,
gambar)
VALUES('$_POST[nama_produk]',
'$produk_seo',
'$_POST[kategori]',
'$_POST[kategori2]',
'$_POST[berat]',
'$_POST[harga]',
'$_POST[diskon]',
'$_POST[stok]',
'$_POST[deskripsi]',
'$tgl_sekarang',
'$_POST[potongan]',
'$nama_file_unik')";
$sql = mysql_query($query1);
if (!sql) {
die('there is an error');
mysql_errno($sql).":".mysql_error($sql);
} else {
echo "success bro!";
}
}
else
{
$query2 = "INSERT INTO sparepart(nama_produk,
produk_seo,
id_kategori,
id_kategori2,
berat,
harga,
diskon
stok,
deskripsi,
potongan,
tgl_posting)
VALUES('$_POST[nama_produk]',
'$produk_seo',
'$_POST[kategori]',
'$_POST[kategori2]',
'$_POST[berat]',
'$_POST[harga]',
'$_POST[diskon]',
'$_POST[stok]',
'$_POST[deskripsi]',
'$_POST[potongan]',
'$tgl_sekarang')";
$sql=mysql_query($query2);
if(!sql) {
die('there is an error');
mysql_errno($sql).":".mysql_error($sql);
} else {
echo "success bro!";
}
}
I want to know why between the 2 same codes, only 1 works and the other does not echo any error but not working.
I am using mysqli_* in my real project. I just felt more comfortable using Mysql_* when writing this question so thank you for warning me about mysql_* being deprecated.
use the die() method at the end, thats why you are not getting the error.
if (!sql) {
/* die('there is an error'); */ // was like this before
echo mysql_errno($sql).":".mysql_error($sql);
die('there is an error'); // make it like this
}
$a=$_POST['kategori'];
$b=$_POST['kategori2'];
$query=mysql_query("INSERT INTO sparepart VALUES('$a','$b')");
if(!query)
{
die('there is an error');
}
else
{
echo "success bro!";
}
do Something like this note:- use '' in POST.

How do I make my drop down select menu persistently show the same data after a query is done using the menu?

So I am having an issue with a drop down selection box. What I am doing is having someone log into a database, and then the database shows all the tables available in the selection box. The user can then select the table they wish to see, hit select and bam! There's the table information.
I am, however having an issue getting the data in the selection box to persist after they hit select. For some reason, it just makes it empty. I'm using session variables, and maybe that effects it? I'm just now beginning to learn how that works too. Take a look at let me know what you think:
<?php
session_start();
if(!isset($_SESSION['session_level'])):
$_SESSION['session_level'] = 0; ?>
<? endif ?>
<?php
if(isset($_POST['host'])):
$_SESSION['host'] = $_POST['host'];
$_SESSION['dbname'] = $_POST['dbname'];
$_SESSION['username'] = $_POST['username'];
$_SESSION['pw'] = $_POST['pw'];
?>
<?php endif ?>
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Login Test</title>
</head>
<body>
<?
if (isset($_POST['return']))
{
$_SESSION['session_level'] = 0;
}
else if (isset($_POST['submit']))
{
try
{
$db = new PDO("mysql:host=".$_POST['host'].";dbname=".$_POST['dbname'], $_POST['username'], $_POST['pw']);
}
catch(Exception $error)
{
$_SESSION['session_level'] = 0;?>
<a href='<?= $_SERVER['PHP_SELF'] ?>'>Click here to return.</a>
<? echo "\n"; ?>
<?die("Connection to user database failed: " . $error->getMessage());
}
try
{
$db->setAttribute(PDO::ATTR_ERRMODE, PDO:: ERRMODE_EXCEPTION);
$query = "SHOW TABLES";
$results = $db->query($query)->fetchAll();
$_SESSION['session_level'] = 1;
}
catch(Exception $error)
{
echo "Problem with query!";
$_SESSION['session_level'] = 0;?>
<a href='<?= $_SERVER['PHP_SELF'] ?>'>Click here to return.</a>
<? }
}
?>
<?php if($_SESSION['session_level'] == 0){?>
<h1>Database Practice</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name='initialentry'>
<table border='0' style='text-align: center'>
<tr>
<td style='text-align: right;'>Enter host name:</td>
<td style='text-align: left;'>
<input type='text' name='host' value='localhost'>
</td>
</tr>
<tr>
<td style='text-align: right;'>Enter database name:</td>
<td style='text-align: left;'>
<input type='text' name='dbname' value='zxyx999'>
</td>
</tr>
<tr>
<td style='text-align: right;'>Enter user name:</td>
<td style='text-align: left;'>
<input type='text' name='username' value='zxyx999'>
</td>
</tr>
<tr>
<td style='text-align: right;'>Enter password:</td>
<td style='text-align: left;'>
<input type='password' name='pw' width='15' value='12345'>
</td>
</tr>
<tr>
<td style='text-align: right;'><input type="reset" name="reset" value="Reset"></td>
<td style='text-align: left;'><input type="submit" name="submit" value="Submit"></td>
</tr>
</table>
</form>
<?php }
else if ($_SESSION['session_level'] == 1)
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name='getForm'>
<select name='select'>
<? foreach($results as $row)
echo "<option value=" . $row[0] .">" .$row[0]. "</option>"; ?>
</select>
<input type="submit" name="selected" value="Select">
<input type="submit" name="return" value="Return to Main Screen">
</form>
<?php
if(isset($_POST['selected']))
{
try
{
$db = new PDO("mysql:host=".$_SESSION['host'].";dbname=".$_SESSION['dbname'], $_SESSION['username'], $_SESSION['pw']);
}
catch(Exception $error)
{
die("Connection to user database failed: " . $error->getMessage());
}
try
{
$query = $db->prepare("SELECT * FROM " . $_POST['select']);
$query->execute();
$header = true;
}
catch(Exception $error)
{
echo "Query failed.";
}
echo "</br>";
?>
<?php
echo "<table border='1'>";
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
echo "<tr>";
if($header == 'true')
{
foreach($row as $index => $fieldValue)
{
echo "<td>";
echo $index;
echo"</td>";
}
echo "</tr>";
$header = 'false';
}
echo "<tr>";
foreach($row as $index => $fieldValue)
{
echo "<td>";
echo $fieldValue;
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
}
}
?>
</body>
</html>
If I well understand your problem then my advice 'll be to change your form and do it this way :
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name='getForm'>
<input type="hidden" name="selected" value="true">
<select name='select'>
<? foreach($results as $row)
echo "<option value=" . $row[0] .">" .$row[0]. "</option>"; ?>
</select>
<input type="submit" value="Select">
</form>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name='getForm'>
<input type="hidden" name="return" value="true">
<input type="submit" value="Return to Main Screen">
</form>
It means you must create 2 forms instead of 1 with because the name value on a submit button is not intrepreted the same way on all browser. So by removing and replacing it by an input type hidden it 'll assure the field 'll exist after submitting forms.
When you repopulate the select list, if the option selected matches the option being populated, then you can make that bit of code <option selected value=" and that option will now be the default selected item at the moment.
I realize the below code isn't PHP, my point is that it should be a simple If statement, to include the selected tag into the option.
/*
Adding the "selected" tag to an option, makes it the default.
*/
<select>
<option value="" style="display:none;">Select a Value</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br /><br />
<select>
<option value="" style="display:none;">Select a Value</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3" selected>3</option>
<option value="4">4</option>
</select>

adding multiple rows in mysql

I have a big problem that somebody is attacking me by adding multiple rows into my db. Hes using the form I have on my website. I got about 2500 rows in my db and all rows were different. Its been generating by any script. Do you have any suggestions how I can fix it? this is my form I have on my website
<?php
if(isset($_POST['type'])) {$type = mysql_real_escape_string($_POST['type']);}
if(isset($_POST['ip'])) {$ip = mysql_real_escape_string($_POST['ip']);}
if(isset($_POST['port'])) {$port = mysql_real_escape_string($_POST['port']);}
$add_date = time();
if(isset($_POST['email'])) {$email = mysql_real_escape_string($_POST['email']);}
if(isset($_POST['web'])) {$web = mysql_real_escape_string($_POST['web']);}
if(isset($_POST['mod'])) {$mod = mysql_real_escape_string($_POST['mod']);}
echo "
<form action='#' method='post'>
<legend>Formulár pre pridanie serveru</legend>
<table>
<tr>
<td>
Hra:
</td>
<td>
<select name='type'>
<option value='cs16'>Counter Strike 1.6</option>
<option value='source'>Counter Strike Source</option>
<option value='csgo'>Counter Strike Global Offensive</option>
</select>
(vyberte hru)
</td>
</tr>
<tr>
<td>
Typ:
</td>
<td>
<select name='mod'>";
$modes = mysql_query("SELECT * FROM `lgsl_modes`") or die(mysql_error());
while($modes_names = mysql_fetch_array($modes))
{
echo '<option value="'.$modes_names['mod'].'">'.$modes_names['name'].'</option>';
}
echo "</select>
(vyberte herný mód)
</td>
</tr>
<tr>
<td>
IP serveru:
</td>
<td>
<input type='text' name='ip' value='' required>
(iba číslice a bodky)
</td>
</tr>
<tr>
<td>
Port serveru:
</td>
<td>
<input type='text' name='port' value='' required>
(iba číslice)
</td>
</tr>
<tr>
<td>
Web serveru:
</td>
<td>
<input type='text' name='web' value='' required>
(uvádzajte bez začiatočného http://)
</td>
</tr>
<tr>
<td>
Váš email:
</td>
<td>
<input type='text' name='email' value='' required>
(kontaktný email)
</td>
</tr>
<tr>
<td>
<input type='submit' name='odoslat' value='Odoslať'>
</td>
</tr>
</table>
</form>
";
if($ip) if(!preg_match("/^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$/",$ip)) $usermsgip="Ip adresa bola uvedená v zlom tvare.";
if($port) if(!preg_match("/^[0-9]{5}$/",$port)) $usermsgport="Port bol uvedený v zlom tvare.";
if($email) if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/",$email)) $usermsgemail="Email bol uvedený v zlom tvare.";
if($web) if(!preg_match("%^((https?://)|(www\.))([a-z0-9-].?)+(:[0-9]+)?(/.*)?$%i" ,$web)) $usermsgweb="Web bol uvedený v zlom tvare.";
if(isset($_POST['odoslat']) && $usermsgip || $usermsgport || $usermsgemail || $usermsgweb) {
if($usermsgip) echo $usermsgip."<br>";
if($usermsgport) echo $usermsgport."<br>";
if($usermsgemail) echo $usermsgemail."<br>";
if($usermsgweb) echo $usermsgweb."<br>";
}
if(isset($_POST['odoslat']) && !$usermsgip && !$usermsgport && !$usermsgemail && !$usermsgweb) {
$kontrola = mysql_query("SELECT * FROM `lgsl` WHERE `ip`='".$ip."' AND `c_port`=".$port);
if(mysql_num_rows($kontrola)) {echo "Server už bol pridaný do banlistu.";}
else {
mysql_query("INSERT INTO `lgsl` (`type`, `ip`, `c_port`, `q_port`, `disabled`, `add_date`, `email`, `web`, `mod`)
VALUES ('$type', '$ip', '$port', '$port', '1', '$add_date', '$email', '$web', '$mod')");
echo 'Server bol úspešne odoslaný na schválenie.';
}
}
?>
I think you should rewrite the whole script using PDO. With Pdo you can avoid SQL-Injection in easy way. Here's a link where you can find that and all the web is full of guide and examples.
Anyway if you want to fix your script you can use Captcha to avoid automatic form submit and a library to sanitize input.
Here you find a simple captcha example and a good sanitize library.
You can whatch here some good tips to solve problems.
Hope this helps.

PHP combobox not showing in HTML table

I've created in PHP a html table with a combobox that retrieves the values of a mysql database table.
This is my code:
<?php
include_once 'indeling/header.php';
print 'Overzicht nota\'s <br /><br />';
$sql = "
SELECT
notas.id AS notaid
, notas.klantid AS klantid
, notas.bedrag AS bedrag
, notas.datum AS datum
, contacten.bedrijf AS bedrijf
, contacten.adres AS adres
, contacten.woonplaats AS woonplaats
FROM
notas
LEFT JOIN contacten
ON (notas.klantid = contacten.id);
";
function bedrijven($mysqli) {
$sqlbedrijven = "
SELECT
id
, bedrijf
, adres
, woonplaats
FROM
contacten
ORDER BY bedrijf ASC
";
$resultbedrijven = $mysqli->query($sqlbedrijven);
if (!$resultbedrijven) {
echo "something went wrong: (" . $mysqli->error .")";
}
echo "<select name = klantid>\n";
while ($row = $resultbedrijven->fetch_assoc()) {
echo <<<opt
<option value="{$row['id']}"> {$row['bedrijf']} - {$row['adres']} - {$row['woonplaats']} </option>
opt;
}
echo "</select>\n";
}
$result = $mysqli->query($sql);
if (!$result) {
echo "Oeps hier gaat iets fout: (" . $mysqli->error .")";
}
else {
printf("Er zijn momenteel %d nota's.<br />", $result->num_rows);
echo "
<table>
<tr>
<th>notanummer.</th>
<th>bedrijf</th>
<th>bedrag</th>
<th>datum</th>
<th>bewerken</th>
</tr>
";
while ($row = $result->fetch_assoc()) {
echo '<tr> <form action="overzicht_relaties_bewerken.php" method="post">
<td> <input type="text" class="short" name="notaid" value="' . $row['notaid'] . '"></td>
<td> ' . bedrijven($mysqli) . ' </td>
<td> <input type="text" name="bedrag" value="' . $row['bedrag'] . '"></td>
<td> <input type="date" name="datum" value="' . $row['datum'] . '"></td>
<td> <input type="submit" name="update" value="aanpassen" class="button">' . '<br />
<input type="submit" name="delete" value="verwijderen" class="button"' . '"></td>
</tr></form>
';
}
echo "</table>";
}
?>
it all works but I see the comboboxes above the table and not in the second TD bedrijven($mysqli)
here is a dump of mij html source code of the webpage:
Overzicht nota's <br /><br />Er zijn momenteel 2 nota's.<br />
<table>
<tr>
<th>notanummer.</th>
<th>bedrijf</th>
<th>bedrag</th>
<th>datum</th>
<th>bewerken</th>
</tr>
<select name = klantid>
<option value="37"> afsdf - fasdf12 - Klarenbeek - (Gelderland) </option>
<option value="36"> afsdf - fasdf12 - Klarenbeek - (Gelderland) </option>
<option value="38"> afsdf2 - fdas - Klarenbeek </option>
now we have a bunch of more option values
and then:
</select>
<tr> <form action="overzicht_relaties_bewerken.php" method="post">
<td> <input type="text" class="short" name="notaid" value="2"></td>
<td> </td>
<td> <input type="text" name="bedrag" value="125.50"></td>
<td> <input type="date" name="datum" value="2013-06-04"></td>
the table data under tabledata id is blank...?
So I call the function at the right place (2nd TD) but is shows the comboboxes somewhere else.
Any idea how this is possible?
I am not good at php but I think your select tag is not in the table! See how i do this in html:
<table>
<tr>
<th>notanummer.</th>
<th>bedrijf</th>
<th>bedrag</th>
<th>datum</th>
<th>bewerken</th>
</tr>
<tr>
<td colspan='5'>
<select name = klantid>
<option value="37"> afsdf - fasdf12 - Klarenbeek - (Gelderland) </option>
<option value="36"> afsdf - fasdf12 - Klarenbeek - (Gelderland) </option>
<option value="38"> afsdf2 - fdas - Klarenbeek </option>
</select>
</td>
</tr>
<tr> <form action="overzicht_relaties_bewerken.php" method="post">
<td> <input type="text" class="short" name="notaid" value="2"></td>
<td> </td>
<td> <input type="text" name="bedrag" value="125.50"></td>
<td> <input type="date" name="datum" value="2013-06-04"></td>
so change your php code from:
echo "<select name = klantid>\n";
while ($row = $resultbedrijven->fetch_assoc()) {
echo <<<opt
<option value="{$row['id']}"> {$row['bedrijf']} - {$row['adres']} - {$row['woonplaats']} </option>
opt;
}
echo "</select>\n";
to:
echo "<tr><td colspan='5'><select name = klantid>\n";
while ($row = $resultbedrijven->fetch_assoc()) {
echo <<<opt
<option value="{$row['id']}"> {$row['bedrijf']} - {$row['adres']} - {$row['woonplaats']} </option>
opt;
}
echo "</select></td></tr>\n";

Allow user to delete profile information

I'm trying to create a form that displays current service information for a user on their profile and then allows them to select a check box for one or more services they provide and then hit a delete button to remove the service(s) related to the check box. Each service has a unique ID and so I'm assuming I need to use this so that the query knows what to delete.
Here is relevant code and the form I am using:
<?php
if (isset($_POST['OddJobName']) && isset($_POST['Description']) && isset($_POST['DaysAvailable']) && empty($errors) === true){//if (empty($_POST) === false && empty($errors) === true) { //if (isset(empty($_POST['OddJobName'])) && isset(empty($_POST['Description'])) && isset(empty($_POST['DaysAvailable'])) === false && empty($errors) === true)
$daysavailable='';
foreach ($_POST['DaysAvailable'] as $value)
{
$daysavailable .=$value." ";
}
$Delete_Oddjob = array (
'MemberID' => $MemberID,
'OddJobID' => $_POST['OddJobID'],
'OddJobName' => $_POST['OddJobName'],
'Description' => $_POST['Description'],
'DaysAvailable' => $daysavailable,
);
Delete_Oddjob ($Delete_Oddjob);
if(success){
header('Location: member.php?username='.$username);
exit ();
}
} else if (empty($errors) === false){
//otherwise output errors
echo output_errors($errors);
}
?>
<?php
$result = mysql_query("SELECT * FROM `oddjob` WHERE `MemberID` = $MemberID");
while($row = mysql_fetch_assoc($result))
{
echo"<table width='100%' border='1' cellspacing='0' cellpadding='5'>
<td width='50%'>
<table width='100%' cellspacing='17' cellpadding='0'>
<form action='' method ='post' enctype='multipart/form-data'>
<tr>
<td>
<input type='hidden' name='MemberID' id='MemberID' value= ". $MemberID .">
</td>
</tr>
<tr>
<td>
<input type='hidden' name='OddJobID' id='OddJobID' value= ". $row['OddJobID'] .">
</td>
</tr>
<tr>
<td width='35%'>
<p>Name of OddJob*:</p>
</td>
<td>
<input type='text' name='OddJobID' style='width:180px' value= ". $row['OddJobID'].">
</td>
</tr>
<tr>
<td width='35%'>
<p>Name of OddJob*:</p>
</td>
<td>
<input type='text' name='OddJobName' style='width:180px' value= ". $row['OddJobName'].">
</td>
</tr>
<tr>
<td>
<p>Description*:</p>
</td>
<td>
<div class='expandingArea'>
<pre><span></span><br></pre>
<textarea name='Description'>". $row['Description'] ."</textarea>
</div>
</td>
</tr>
<tr>
<td>
<p>Days Available(current week)*:</p>
<p>(hold Ctrl to select multiple)</p>
</td>
<td>
<select name='DaysAvailable[]' size='5' multiple='multiple' id='DaysAvailable[]'>
<option value='Monday'>Monday</option>
<option value='Tuesday'>Tuesday</option>
<option value='Wednesday'>Wednesday</option>
<option value='Thursday'>Thursday</option>
<option value='Friday'>Friday</option>
<option value='Saturday'>Saturday</option>
<option value='Sunday'>Sunday</option>
</select>
</td>
</td>
<tr>
<td>
<input type='checkbox' name='Delete' value= ". $row['OddJobID'] .">
</td>
</tr>
</table>
</table>
</table>
<input type='submit' name='Delete' value='Delete'>
</form> ";
}
?>
Function:
function Delete_Oddjob ($Delete_Oddjob){
//global $Add_Oddjob;
array_walk($Delete_Oddjob, 'array_sanitize');
mysql_query("DELETE FROM `oddjob` WHERE `OddJobID` = '".$_POST['OddJobID']."'") or die (mysql_error());
}
I don't understand how to make this work. At the moment when I select a check box and click the delete button the page seems to refresh but nothing else happens. Also If i try to echo out the query nothing is displayed.
echo "DELETE FROM `oddjob` WHERE `OddJobID` = '".$_POST['OddJobID']."'";
Any help would be great. Thank you.
You pretty much have the solution there.
Rename your Delete checkboxes to name="delete[]" that allows multiple checkboxes to be posted under the one name, then on the PHP side of things you can access these by saying:
if (isset($_POST['delete'])) {
foreach($_POST['delete'] as $oddjob) {
if (Delete_Oddjob($oddjob)) {
// success
} else {
// failure
}
}
}
Whenever the form is submitted and the delete option has been selected this will loop through all the checked checkboxes on the form and delete them using their ID.

Categories