$_POST leads to empty fields in MySQL Database - mysql

Thank you for taking the time to read this. This question may or may not have been answered before, I might have been looking in the wrong place, but I've hit a dead end wall here and I hope I could ask for some help finding a solution.
I'm using a basic form with a validation for specific fields and checkboxes before I'm sending them in a query to my database.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// validate the text inputs
$err = array();
if (empty($_POST['A'])) {
array_push($err, "A is required.");
}
if (empty($_POST['B'])) {
array_push($err, "B is required.");
}
if (empty($_POST['C'])) {
array_push($err, "C is required.");
} else {
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$";
if (!eregi($pattern, $_POST['email'])) {
array_push($err, "Incorrect email.");
}
}
if (empty($_POST['D'])) {
array_push($err, "D is required.");
if (sizeof($err) != 0) {
echo "<p style='color: red'>The following files haven't been filled yet.</p>";
echo "<ul style='list-style:circle !important;color: red !important;'>";
foreach ($err as &$value) {
echo "<li style='background: 0;list-style: disc inside none;color: red;'>" . $value . "</li>";
}
echo "</ul>";
echo "<br/>";
}
// validate the agree checkbox
if (sizeof($err) == 0 && !isset($_POST['agree'])) {
array_push($err, "Please agree with the ToS.");
foreach ($err as &$value) {
echo "<p style='color: red'>" . $value . "</p>";
}
}
}
?>
Then the inside the form we got this:
<?php echo isset($_POST['a']) ? $_POST['a'] : ''; ?>"
The other lines are the same, so I'll save you from having to read a huge block. From there on I sent the code towards:
<?php
// redirect if form is valid
if (sizeof($err) == 0 && isset($_POST['agree'])) {
// set post data in session
session_start();
$_POST = $_SESSION['POSTDATA'];
$con = mysqli_connect("localhost", "x", "y", "z");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO esselte_nl (a, b, email, c, d) VALUES
('$_POST[a]',
'$_POST[b]',
'$_POST[email]',
'$_POST[c]',
'$_POST[d]')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
// redirect to result.php
exit('<meta http-equiv="refresh" content="0; url=resullt"/>');
return;
session_destroy();
}
?>
Worst thing is, I'm fairly certain it's some very small error somewhere and I'm overlooking it, terribly frustrating. So if anyone could potentially point out whatever I'm doing wrong here, I'd appreciate it.
With friendly regards,
user2747008 (I really should pick a name though)
PS: Sorry about that, I messed up copying pasting the information.

$sql = "INSERT INTO esselte_nl (a, b, email, c, d) VALUES
('$_POST[a]',
'$_POST[b]',
'$_POST[c]',
'$_POST[email]')";
Your insert statement has 5 field names, but only 4 values, and they aren't in the correct order.

Related

odd results inside of a switch statement

Thanks in advance to those who will have taken time to look at my issue. I fetch results from a table that describe activities of a contractor. There are a large number of True/False fields and I seek only to display those that are true. I create a field_name => field_type array and parse my display accordingly. (apologies for the large code snippet.)
$result = $mysqli->query($visitsSQL);
if ( $result->num_rows == 0 ){ // Visit records don't exist
$_SESSION['message'] = "Cannot find any unpaid visits";
header("location: error.php");
}
else { // unpaid visits exist
$fields= array();
while ($finfo = mysqli_fetch_field($result)){
$fields [$finfo->name]= $finfo->type ; //this array holds field names -> field types
} //finish fetching keys and types
echo "<br>";
echo "<br>Begin visit records<br>";
echo "<div class='review_row'> </div>"; //this puts a thin line to separate visits
while ($visit = $result->fetch_assoc()) { //here's where each visit is compiled and sent to screen
echo "<div class='review_row'>"; //this puts a thin line on the bottom to separate visits
foreach ($fields as $k => $v) {
$field_name = $k;
$field_type = $v;
$field_data = $visit[$field_name];
switch ($field_type) {
case 1: //The field is a True / False field
if ($field_data ==1){ //show the field only if the value is set to True
echo "I am a YES/NO field called " . $field_name . " <br>"; //This line is a test
echo "<span style='color: #009999;> - " . $field_name . "</span><br>";
}
break;
case 4: //The field is a double numeric
if ($field_data != null) { //show the field only if the value is set to True
echo "<span style='color: #b38f00';>" . $field_name . "</span> " . $field_data . "<br>";
}
break;
case 253: //A text field
if ($field_data != null) {
echo "<span style='color: #b38f00';>" . $field_name . "</span> " . $field_data . "<br>";
}
break;
case 254: //a Datetime field
if ($field_data != null) {
echo "<span style='color: #b38f00';>" . $field_name . "</span> " . $field_data . "<br>";
}
break;
default: { //field type is not represented above
// do nothing so far I take care of each field type above
}
} //end of switch
} //end of foreach
} //end of while loop for the query results
echo "</div>";
} // end of if / else that determine if there are records to display
The strange results occur in the "switch" statement where "case 1". My current test record has 7 YES/NO fields whose values are all set to 1. They are
Prepared evening meal
Cleaned up evening meal dishes
Shopped for groceries
Washed and folded clothes
Washed bedding
Vacuumed carpets
Swept kitchen floor
I should get two "echo"s for each "field_type = 1": (1) my test echo and (2) what I eventually want to display, but for some reason they display alternately - see image below. I've fought with this for two days, trying if/then parsing as well, but I come up with this "every-second-one" type of result.
screenshot of output from query
Thanks for any thoughts or direction.
I have found the problem & corrected it. It had to do with the "span..." tags. I replaced the inline "style=..." with a class. I set the the color within the class then removed settings with an "class: after" section.

Getting data from database using part of the URL as a value - PHP

My url type is like "http://localhost/boardgame/profile/Duncan/" the last word is the user name...
I just try to get some data from database and I need a user name to do this. I tried to get it from page URL but it doesn't work. Where did I go wrong? What has to be done? I'll be greateful if anybody can help...
<?php
$actual_link = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
//echo $actual_link;
$rest = substr($actual_link, 35, -1);
echo $rest;
$link = mysqli_connect("localhost", "root", "", "bgt");
if (mysqli_connect_error()) {
die ("Veritabanı bağlantısında hata var");
} if (($rest) !="") {
if (get_current_user_id($link) == '0') {
echo "<p>Kullanıcının koleksiyonunu görebilmek için giriş yapmanız
gerekiyor.</p>";
} else {
$query = "SELECT TITLE FROM wp_user_collections WHERE `user_name` =
'".mysqli_real_escape_string($link, $rest)."'";
echo "<div><h1>'".mysqli_real_escape_string($link, $rest)."'in
Koleksiyonu</h1><div>";
if($result = mysqli_query($link, $query)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>Oyun Adı</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>'" . $row['TITLE'] . "'</td>";
echo "</tr>";
}
echo "</table></div>";
}
}
}
} else {
echo "Kullanıcının koleksiyonunu görebilmek için <a
href='http://localhost/boardgame/profile/'".mysqli_real_escape_string($link,
$rest)."'>tıklayınız</a>";
}
?>
Here is the solution I have thought...using array then extracting the last element (or second last since there is a trailing '/' slash which is a delimiter)
$uri="http://localhost/boardgame/profile/Duncan/";
$uriParts=explode('/', $uri); //converts the uri string into an array of words separated by forward slash
$name=$uriParts[sizeOf($uriParts)-1-1]; //the user name comes from 2nd last item as the last item is empty
echo $name;
I could suggest you use Regular Expression to extract the user name, however I'm not well versed with it yet.

Read txt file into HTML table

I have to read a txt file into a HTML table.
There are many fields in it but I only want to read the field that says "value".
Here is my txt file:
one=availability:, timestamp=90754, value=no
two=description:, timestamp=074693, value=not sure
three=Name, timestamp=90761, value=yes
The one, two, three values are my row headers and I want it to display the values underneath.
Is there anyway of doing this using iframe?? PHP is not working for me.
Supposing the value is always the last field and you are reading the file line by line I would use a dirty approach:
$value = explode('value=', $line)[1];
longwinded approach
$headers=[];
$values=[];
$lines = file('./homework.txt', FILE_IGNORE_NEW_LINES);
foreach($lines as $line){
$chunks = explode(',',$line);
foreach($chunks as $index => $chunk){
list($key, $value) = explode('=', trim($chunk));
if(!$index){
$headers[] = $value;
}
if('value' === $key){
$values[] = $value;
}
}
}
echo "<table><thead><tr>";
foreach($headers as $h){
echo "<th>{$h}</th>";
}
echo "</tr></thead><tbody><tr>";
foreach($values as $v){
echo "<td>{$v}</td>";
}
echo "</tr></tbody></table>";
If all rows follow the same pattern you can probably use:
//$textfilestring = "one=availability:, timestamp=90754, value=no
//two=description:, timestamp=074693, value=not sure
//three=Name, timestamp=90761, value=yes";
$textfilestring = file_get_contents("PATH_TO_FILE");
$arraylines = explode("\n", $textfilestring);
for ($i=0;$i<count($arraylines);$i++) {
$arraylines[$i] = explode("value=", $arraylines[$i]);
}
echo "<pre>";
var_dump($arraylines);
echo "</pre>";
echo $arraylines[0][1] . "<br>";
echo $arraylines[1][1] . "<br>";
echo $arraylines[2][1] . "<br>";
$arraylines should be twodimensional with one part beeing
one=availability:, timestamp=90754,
and one beeing
no
Not tested though.

How to use IF NULL, do this in MySQL?

I'm trying to build a members-system in which you can view certain values from a database.
It worked, so that was great, but I'm having a problem now because I'm using a NULL value on 'age'.
When viewing a profile page, it looks like this:
$id = $_GET["id"];
$result = mysql_query("SELECT * FROM membersfromsite WHERE `idofmember`=$_GET[id]");
$row = mysql_fetch_array($result);
echo "<b>" . $row['userusername'] . "</b>: </p>"; ?>
<?php
$id = $_GET["id"];
$result = mysql_query("SELECT * FROM membersfromsite WHERE `idofmember`=$_GET[id]");
$noage = mysql_query("SELECT ISNULL([age]) FROM membersfromsite WHERE `idofmember`=$_GET[id]");
while ($row = mysql_fetch_array($result))
{
echo "<p class='middle'>id-number: " . $row['idofmember'] . "<br>";
echo "Username: " . $row['userusername'] . "<br>";
if ($noage)
{
echo "Age not specified";
}
else
{
echo "Age: " .$row['age'] ;
}
}
I have tried all kinds of other things, but the problem which I 'm having is that it either returns 'Age not specified' on every userpage or the age on every userpage, including the pages with a NULL value, which makes it look like:
Age:
The code which you can see above returns the age on every page, including the pages with an age which is set to NULL. What I don't understand is if I change the code to this:
$noage = mysql_query("SELECT * FROM membersfromsite WHERE `idofmember`=$_GET[id] AND age IS NULL");
it simply doesn't work. Since I'm using IS NULL instead of = NULL I don't really see why this shouldn't work, but I guess it has to do with the IF which is inside the 'while' thing, I don't really see in what other way I could fix this though...
I'm having an idea what the problem is, because I think that there is already a MyQS, Query done with Results and $noage is maybe ignored because of this, but I don't know how to solve this.
You don't need to do a whole separate $noage query.
Just do:
if(!$row['age'])
{
echo "Age not specified";
}
else
{
echo "Age: " .$row['age'] ;
}
Instead of if($noage) use if(!$row['age']) and skip the second query.
The other reason your code does not work is that the second query returns an array with something like array('expr1' => 0) which is not false. You only get a false result if nothing is found.
The reason why = NULL does not work? There are books written about it, it is just as it is.
Rather than relying on MySQL to tell us if no age was found or not, we can programatically determine whether the age value is Null right in PHP.
Here is an example:
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM membersfromsite WHERE `idofmember` = '" . mysql_real_escape_string($id) . "'");
while($row = mysql_fetch_array($result)) {
echo '<p class='middle'>id-number: ' . $row['idofmember'] . '<br>';
echo 'Username: ' . $row['userusername'] . '<br>';
if($row['age'] === Null) {
echo "Age not specified";
} else {
echo "Age: " .$row['age'] ;
}
}

mysql query insert error

The INSERT into staffprofiles mysql query (near the bottom of the code) is getting the "or die" statement triggered. Can anyone see why? The first one into staffusers is fine. Am I breaking a rule by having 2 insert commands or something? If so, is there another way to code what I am trying to do? Thank you in advance for any help.
Also, I will be address SQL injection and other items shortly. I just want to get this figured out first. Thanks.
<html>
<head>
<title>XXXXXXX</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="back">
</div>
<div id="wrapper">
<div id="header">
<div id="logout">
<?php
include 'header.php';
?>
</div>
<span><b>XXXXXXX</b>XXXXXX</span>
</div>
<?php
include 'menu.php';
if (isset ($_POST['submit']))
{
}
else
{
echo "not set";
}
$user=$_POST['username'];
$pass1=$_POST['pass1'];
$pass2=$_POST['pass2'];
$email=$_POST['email'];
$user=strip_tags($user);
$email=strip_tags($email);
$pass1=strip_tags($pass1);
$isemail = "SELECT * from staffusers where email ='$email'";
$isemail2 = mysql_query($isemail) or die ("could not query email in table");
$isemail3 = mysql_fetch_array($isemail2);
if ($isemail3)
{
echo "That email address is already registered.<br>";
echo "<a href='forgotpassword.php'>Forgot passsword.</a><br>";
echo "<a href='staffregisterform.php'>Go back to register under a different email address.</a>";
exit;
}
if ($email == "" || $user == "" || $pass1 == "" || $pass2 == "")
{
echo "please complete all fields before submitting<br>";
echo "<a href='staffregisterform.php'>Go Back</a>";
exit;
}
if (strlen($pass1)<6)
{
echo "Your password must be at least 6 characters in length.<br>";
echo "<a href='staffregisterform.php'>Go Back</a>";
exit;
}
if ($pass1 == $pass2)
{
$isplayer = "SELECT * from staffusers where username ='$user'";
$isplayer2 = mysql_query($isplayer) or die ("could not query user in table");
$isplayer3 = mysql_fetch_array($isplayer2);
if ($isplayer3)
{
echo "The username ''$user'' is already taken. Please try another username.<br>";
echo "<a href='staffregisterform.php'>Go Back</a>";
exit;
}
if (strlen($user)>16 || strlen($user)<2)
{
echo "Your username must be be at 2 two characters and at most, 16 characters.<br>";
echo "<a href='staffregisterform.php'>Go Back</a>";
exit;
}
}
else
{
echo "The passwords do not match.<br>";
echo "<a href='staffregisterform.php'>Go Back</a>";
exit;
}
$pass1=MD5($pass1);
$register = "INSERT INTO staffusers (username, password, email) VALUES ('$user', '$pass1', '$email')";
mysql_query($register) or die ("staffusers.");
$profile = "INSERT INTO staffprofiles (username, email) VALUES ('$user', '$email')";
mysql_query($profile) or die ("staffprofiles.");
echo "Thank you for registering, $user.<br>";
echo "<a href='index.php'>Login</a>";
?>
If you have valid fieldnames and table names then try;
$profile = mysql_query("INSERT INTO staffprofiles (username, email) VALUES ('$user', '$email')");
// use some value directly to check as:
$user = "Tester";
$email= "something#test.com";
$profile = mysql_query("INSERT INTO staffprofiles (username, email) VALUES ('$user', '$email')");
//if this value gets inserted then you have problem in $user variables value
Hope it helps