$_POST['variable'] not working - php

I am having an issue getting the $userid from $_POST. I have done this lots of times before, so I am not sure what I am doing wrong all of a sudden.
Form that is submitting to user_confirm.php
<?php
//confirm user function
function confirmUsers() {
//make connection global
global $con;
//set user variables
$userquery = mysqli_query($con, "SELECT * FROM users WHERE userlevel = 0");
//echo list
echo '<center><form name="userConfirm" action="functions/user_confirm.php" method="post">';
echo '<select name="confirmUser">';
while ($row = mysqli_fetch_array($userquery)) {
echo "<option value='" . $row['userid'] ."'>" . $row['username'] ."</option>";
//in viewing element, the userid is displaying properly
}
echo '<input type="submit" value="Confirm User">';
echo '</select>';
echo '</form></center>';
}
?>
user_confirm.php
<?php
//include db connect
include ("db_con.php");
//set variable names
$userid = $_POST['userid'];
//start session
session_start();
echo $userid;
?>
As you can see, I am simply just trying to echo the variable passed from the form. It is not working and I am totally confused as to why, any ideas?
in case it was needed here is db_con.php
<?php
$con=mysqli_connect("localhost","user","pw","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

You dont have a form field called userid, perhaps you mean the confirmUser field:
$userid = $_POST['confirmUser'];

You are not passing the userid var to user_confirm.php, try renaming your select to userid

The coding looks right to me and should work.
I'm not sure if this will help but try to load the session_start(); first.
The next thing would be to do a print_r($_POST) and see what shows.
Also view the source of the finished html and see how it prints out.
Also I like to use
echo <<
END;
With this you can just type in the html plus the strings with no ' or " unless the html needs it.
I missed the confirmUser myself.. =(

Related

How to display user data after logged in?

I am trying to display information regarding the user after they have logged in. After the user has logged in the user will be redirected to success.php. I use MySQL and a form is an HTML form.
I tried writing the success page in two different ways
success.php (1)
session_start();
if (!isset($_SESSION["loggein"]) || $_SESSION["loggein"] == false) {
include ("getUser.php");
// header("Location: getUser.php");
echo "done";
}
success.php (2)
<?php
session_start();
if (!isset($_SESSION["loggein"]) || $_SESSION["loggein"] == false) {
echo "done";
}
?>
<h2>you have logged in</h2>
<p><?php include ("getUser.php");?></p>
I tried to include a file getUser.php that is suppose to retrive everything regarding the user.
getUser.php
$username = mysqli_real_escape_string($connection, $_REQUEST['username']);
$sql= "select * from userTable where username = '$username'";
if($result = mysqli_query($connection, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<table";
echo "<tr>";
echo "<th>username</th>";
echo "<th>city</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['city'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($result);
} else{
echo "No user" . mysqli_error($connection);
}
}
I keep getting the "No user" error message from the getUser.php. I do not understand why I get it
In getuser.php you didnt make connection with your database.So add the below line at top of your php document.
$connection = new mysqli("HOST_NAME","USER_NAME","PASSWORD","DATABASE_NAME") or die("Connect failed: %s\n". $connection -> error);
This more than likely will not solve your issue but I believe it could lead you closer or help us better understand what is going on. I can't comment yet so I am posting it here and will continue to help you along until we solve the problem.
Add this to the top of your php documents:
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
It will write errors to a text document stored on your server to help us debug your issue.

Pass a variable from Page1 to Page2

// Page 1 - Code below works fine, but when I click the href link the
// variable I want is not sent to page 2.
<?php
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<tr>
<td> ' . $row['recipe_name'] . ' </td>
</tr>';
$recipe_name = $row['recipe_name'];
}
$_SESSION['recipe_name'] = $recipe_name;
echo '</table>'; // Close the table
?>
// Page2 - Code below receives the variable from page 1, but only the //last one in the table and not the one I clicked.
include ('core/init.php'); // Connect to the database
$recipe_name = $_SESSION['recipe_name'];
echo "My recipes is: ".$recipe_name."<br>";
?>
Try something like this using a get request.Since the users can see/alter the data, this is not the safest way of doing this but will do the job. Sessions are not involved in this technique.
<?php
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<tr><td>
' . $row['recipe_name'] . ' </td></tr>';
}
echo '</table>';
?>
// Page2
<?php
$recipe_name = $_GET['recipe_name'];
echo "My recipes is: ".$recipe_name."<br>";
?>
You are doing wrong in your page 2
Instead of session use $_GET['']; To get value from url we use $_GET.
Like this:
$recipe_name = $_GET['recipe_name'];
I hope this would help you.

php updates database data only sometimes

I have to following form
$connection = mysqli_connect(SQL_HOST, SQL_USERNAME, SQL_PASSWORD, SQL_DBNAME) ;
if (mysqli_connect_errno($connection))
{
echo "Nespojeno s MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM novinky";
$result = mysqli_query($connection, $sql);
echo "<div id='newsbox'>";
while($zaznam = mysqli_fetch_row($result)):
echo "<form class='newsholder'>";
echo "<input id='displaynadpis' value='$zaznam[1]'>";
echo "<input id='displaybold' value='$zaznam[2]'>";
echo "<textarea id='displaytext'>$zaznam[3]</textarea>";
echo "<div class='buttonsholder'>";
echo "<button class='deletebutton'>Smazat</button>";
echo "<button class='updatebutton'>Upravit</button>";
echo "<input id='prime' type='hidden' attr='id' value='$zaznam[0]'>";
echo "</div>";
echo "<div class='clearfix'></div>";
echo "</form>";
endwhile;
echo "</div>";
mysqli_close($connection);
that displays data from the database in order to update them upon the .updatebutton click.
The data is passed by jquery ajax
$('.updatebutton').on('click', function(){
var idVal = $(this).closest('.newsholder').find('#prime').val();
var displaynadpisVal = $(this).closest('.newsholder').find('#displaynadpis').val();
var displayboldVal = $(this).closest('.newsholder').find('#displaybold').val();
var displaytextVal = $(this).closest('.newsholder').find('#displaytext').val();
alert(displaynadpisVal);
$.ajax({url:"updaterecord.php",
type:"POST",
cache:false,
data:{id: idVal, displaynadpis: displaynadpisVal, displaybold: displayboldVal, displaytext: displaytextVal}
}); });
to the php script
$connection = mysqli_connect(SQL_HOST, SQL_USERNAME, SQL_PASSWORD, SQL_DBNAME) ;
if (mysqli_connect_errno($connection))
{
echo "Nespojeno s MySQL: " . mysqli_connect_error();
}
$id = $_POST['id'];
$updatenadpis = $_POST['displaynadpis'];
$updatetextbold = $_POST['displaybold'];
$updatetext = $_POST['displaytext'];
echo $updatetext;
$sql = "UPDATE novinky SET nadpis='$updatenadpis',
textbold='$updatetextbold',
text='$updatetext'
WHERE id = '$id'"
;
$retval = mysqli_query($connection, $sql);
if(! $retval )
{
die('Could not enter data: ' . mysqli_connect_error());
}
echo "Entered data successfully\n";
mysqli_close($connection);
to update the database. The problem is, that it only works sometimes, but in about 70% of cases it doesn't make any change. The data is stored in js variables just fine, when tested by alert(), they exist everytime. So the problem must be in the mysqli_query() possibly? Or the AJAX method? I have tried a lot of options and recommendations from other posts but no luck. Thanks for your help...
Biggest problem here is fact that you are passing raw user input to query. Assigning it to variable doesn't change anything!
You should filter everything received from user and use prepared statements to be sure that you are safe.
Also don't use mysqli_connect_error() to check query errors. Use mysqli_error().

Trouble with a php post back solution

This may be an easy fix, but I can't get my head around it .
Basically I've remade my blog using a database and php rather than wordpress.
I want my site to show the most recent post first, then i'm using PhP postback to alter it
So far it works, but i can't figure out a way for it to automatically go to the most recent one but then change after the postback.
<?php
$inId = $data[0];
//if (!empty($inId))
//{
//}
//else
//{
//$inId = $_POST['ID'];
//}
include 'Includes.php';
$blogPosts = GetBlogPosts($inId);
foreach ($blogPosts as $post)
{
echo "<div class='post'>";
echo "<h3>" . $post->title . "</h3>";
echo "<p2>" . $post->post . "</p2>";
echo "<span class='footer'>Posted By: " . $post->Author . " Posted On: " . $post- >datePosted . "</span>";
}
echo '<form name="myForm" action="Index.php" onsubmit="return validateFormStrings()" method="post">';
echo'<select name ="ID">';
$query4 = "SELECT * FROM Blogs ORDER BY ID ";
$result = mysql_query($query4);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo '<option value="'.$row['ID'].'">'.$row['Title'].'</option>';
echo '<br>';
}
echo'</select>';
echo '<input type="submit" value="Retrieve Posts">';
echo '<a href="Index.Php" ></a>';
echo '</form>';
?>
As you see i tried to fiddle with !empty and things but that's not really what im trying to do.
If i'm unclear let me know.
I almost need something like " if ( button !pressed) then its data[0] else its the postback
Thanks in advance
I found out how to do it using the isset() function.
if (isset($_POST['submit1']))
{
$inId = $_POST['ID'];
}
else
{
$inId = $data[0];
}
This checks if the submit button has doe the postback or not. Works a treat.
Gonna have a go at trying it with Ajax so I don't need the button at all ^^

Inserting PHP in an HTML form to populate a selection

I have a HTML form that has a selection drop down. I would like to populate the drop down from my MySQL DB. The HTML form already has some java scripts to handle datepicker, and current date on one of the fields in the form.
I can code the form for the selection manually, but would like it to come from MySQL. the php I am using I put in it's own file name.php to make sure it worked correctly. I added some echo statements in the php to build the form, and the selection, and then populate the selection, and close it. this worked just fine as a standalone php.
When I append the php in the form under the selection definition, it does not populate the selection at all, it is left blank/empty. If I add some echo statments to output info in the format of a selection option, the first echo never shows up, and the subsequent echos show up, but any variable show up as the variable name.
<form id="form1" name="form1" method="post" action="/db_log.php">
Field:<select name="id">
<?php
require_once dirname(__FILE__) . '/db_connect.php';
$db = new DB_CONNECT();
$query="SELECT id, name FROM file order by name";
$result=mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$name =$row['name'];
echo "<option value=\"$id\"> $name </option>";
}
?>
</select><br />
</form>
the above yealds an empty select dropdown.
But this works great as a PHP file.
<?php
echo "<form id=\"form1\" name=\"form1\" method=\"post\" action=\"/db_log.php\">";
echo "Select:<select name=\"id\">";
require_once dirname(__FILE__) . '/db_connect.php';
$db = new DB_CONNECT();
$result=mysql_query("SELECT id, name FROM file order by name");
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$name =$row['name'];
echo "<option value=\"$id\"> $name </option>";
}
echo "</select><br />";
echo "</form>";
?>
If I add a echo to the HTML form one like a test echo before any other echo, it is ignored.
<form id="form1" name="form1" method="post" action="/db_log.php">
Field:<select name="id">
<?php
echo "<option value=\"1\"> Test-name </option>";
require_once dirname(__FILE__) . '/db_connect.php';
$db = new DB_CONNECT();
$query="SELECT id, name FROM file order by name";
$result=mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$name =$row['name'];
echo "<option value=\"$id\"> $name </option>";
}
?>
</select><br />
</form>
the only thing that shows up from this is the option to select $name
Based on this question and the previous questions and the comments you've gotten and made I'm going to guess that you're trying to run php from a .html file. You need to save your code (including the html) in a .php file for it to work.
A have a combo box that feeds from my mysql database.
I goes like this:
<tr>
<td>Emergency service</td>
<td><?php
$nombreEmergencia;
$idEmergencia;
$sql4 = "SELECT `idEmergencias`, `nombre` FROM `emergencias` WHERE 1";
$iterador = $conn->consulta($sql4);
echo '<select name="idEmergencia" id="idEmergencia" style="width:228px">
<option value="-1" selected>(please select:)</option>';
while($iterador->hayElemento()){
$nombreEmergencia = $iterador->getElemento("nombre");
$idEmergencia = $iterador->getElemento("idEmergencias");
echo '<option value="'.$idEmergencia.'">'.utf8_encode($nombreEmergencia).'</option>';
}
echo '</select>'; ?></td>
</tr>
as you can see you have to use an "iterator" variable with a function that checks the database for more elements and brings 'em.
That auxiliary function looks like this:
<?php
class Iterador{
private $ultimoDato;
private $id;
public function __construct($id){
$this->id = $id;
}
public function hayElemento(){
$dato = mysql_fetch_array($this->id);
$this->ultimoDato = $dato;
return !empty($dato);
}
public function getElemento($columnas){
return $this->ultimoDato[$columnas];
}
public function inicializar(){
$dato = mysql_fetch_array($this->id);
$this->ultimoDato = $dato;
}
public function hay(){
return !empty($this->ultimoDato);
}
public function siguiente(){
$dato=mysql_fetch_array($this->id);
$this->ultimoDato=$dato;
}
}
?>
hope this helps!!

Categories