mysql_fetch_array() error on submit form to self - php

I have a page called index.html which takes in a few variable from the user, when the user submits them, it goes to the next page (result.php) On results.php the variables from the form on the index.html are posted. The results.php connects to database runs a query etc. All of this works fine. the results.php looks something like this:
<?php
$h = "localhost";
$u = "root";
$p = "******";
$d = "********";
//connectipn to mysql
$conn = mysql_connect( $h, $u, $p );
//connection to database
mysql_select_db($d);
$code = $_POST['code'];
$usage = $_POST['usage'];
$days = $_POST['days'];
$value = $_POST['value];
$sql_runners_up = "SELECT code
from some_table
where number = $value;"
$plans['p_h10'] = array();
$rs2 = mysql_query( $sql_runners_up, $conn );
while ( $row = mysql_fetch_array( $rs2 ))
{
$plans['p_h10'][] = $row["p_h10"];
}
?>
The results.php also has a form that the user can update some fields that are used in the query. the form that I currently have looks like this...
<form action="results.php" name="filter" method="post">
usage:<input name="" type="search" value="" /><br/>
days:<input name="" type="search" value="" /><br/>
<input name="" type="checkbox" value="" />value<br />
<input type="submit" value="submit" name="submit" />
</form>
Even with a blank as soon as the user submits the form I get an error (i have tried filling out the form to use real variable but still get the same error)
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL
result resource
the error refers to the line around the while statement. my guess is that some variable/s are not being passed after the form is submitted or the entire results.php form is not being submitted / processed by the server. But to be honest I am really not sure. Any help will be greatly appreciated.

That's because mysql_query returned false.
Also, in your code, you've got a syntax error
$value = $_POST['value'];
Also, your code is vulnerable. Don't trust user's input!
so, correct code would be
$value = intval($_POST['value']);

Try:
$value = (int) $value;
$sql_runners_up = "SELECT code from some_table where number = $value";
$plans['p_h10'] = array();
$rs2 = mysql_query( $sql_runners_up);

try with this:
$sql_runners_up = "SELECT * from some_table where number = '$value';"
and also check that the $value has containing the value..
EDIT: in the above code i use * which select all the fields, cause that is see in your code you did:
$sql_runners_up = "SELECT code from some_table where number = $value;"
and in fetch query you are calling to field name p_h10:
while ( $row = mysql_fetch_array( $rs2 ))
{
// didn't selected $row["p_h10"] in your query
$plans['p_h10'][] = $row["p_h10"];
}

First of all, this row is invalid:
$value = $_POST['value];
It should be $_POST['value'];
But, this error occurs usually when there is an error in your query, or the connection is bad. Check your mysql_connect() & mysql_select_db() settings, it is probably bad.

looks like you did typos...
<?php
$h = "localhost";
$u = "root";
$p = "******";
$d = "********";
//connectipn to mysql
$conn = mysql_connect( $h, $u, $p );
//connection to database
mysql_select_db($d);
$code = $_POST['code'];
$usage = $_POST['usage'];
$days = $_POST['days'];
$value = $_POST['value']; // here
$sql_runners_up = "SELECT code
from some_table
where number = $value"; // and here
$plans['p_h10'] = array();
$rs2 = mysql_query( $sql_runners_up, $conn );
while ( $row = mysql_fetch_array( $rs2 ))
{
$plans['p_h10'][] = $row["p_h10"];
} ?>
also your form is not POSTing parameters... because name attributes are not set
<form action="results.php" name="filter" method="post">
usage:<input name="usage" type="search" value="" /><br/>
days:<input name="days" type="search" value="" /><br/>
<input name="value" type="checkbox" value="" />value<br />
<input type="submit" value="submit" name="submit" />
</form>

Related

Updating and deleting from a data table, warning undefined array key

I have been following a lesson on how to make an admin page. I got all the information out of my database to a table on the page. I have an update button and when I change the information and press the button I receive this error: Warning: undefined array key "WebID" in ..\Update.php on line 3
From my search online everyone is trying to change the code so that if array key does not exist: return null. I tried that and the error does not appear no more, but the table does not change.
Any thoughts?
This is the code:
<?php
require_once("DB/DB.php");
$SearchQueryParameter = $_GET["WebID"];
if (isset($_POST["Update"])) {
$Ename = $_POST["Ename"];
$Eid = $_POST["Eid"];
$Erank = $_POST["Erank"];
$Eemail = $_POST["Eemail"];
$Edate = $_POST["Edate"];
$Epassword = $_POST["Epassword"];
$Specialisms = $_POST["Specialisms"];
global $ConnectingDB;
$sql ="UPDATE emp_data SET Ename='$Ename', Eid='$Eid', Erank='$Erank', Eemail='$Eemail', Edate='$Edate', Epassword='$Epassword',
Specialisms='$Specialisms' WHERE WebID='$SearchQueryParameter'";
$Execute = $ConnectingDB->query($sql);
if ($Execute) {
echo '<script>window.open("adminpage.php?WebID=Recored Updated","_self")</script>';
}
}
?>
<?php
<?php
global $ConnectingDB;
$sql = "SELECT * FROM emp_data WHERE WebID='$SearchQueryParameter'";
$stmt = $ConnectingDB->query($sql);
while ($DataRows = $stmt->fetch()) {
$WebID = $DataRows["WebID"];
$Ename = $DataRows["Ename"];
$Eid = $DataRows["Eid"];
$Erank = $DataRows["Erank"];
$Eemail = $DataRows["Eemail"];
$Edate = $DataRows["Edate"];
$Epassword = $DataRows["Epassword"];
$Specialisms = $DataRows["Specialisms"];
}
?>
Html file used to update:
<form id="UpdateForm" method="post" action="Update.php?WebID<?php echo $SearchQueryParameter; ?>">
<div class="form-group">
<button type="submit" name="Update" class="form-control-submit-button">Update</button>
</div>
you have to write the form action like this.. you missed the = sign
action="Update.php?WebID=<?php echo $SearchQueryParameter; ?>"
<form id="UpdateForm" method="post" action="Update.php?WebID=<?php echo $SearchQueryParameter; ?>">
You missed the = sign, in the url

PHP UPDATE data where there are ID matches

I'm passing an id from a URL from the previous page and then try to update database values in the row of that id. I feel like I'm close. I'm able to update the value librarian_fname when I add into the update query the specific id number, but when I try and pass that value through the code, it must not be picking it up because it won't update when I use id = '$id'. Not sure what I'm doing wrong. And I am still learning so forgive me if this isn't perfect.
<?php
$id = $_GET['id'];
echo $id;
?>
<?php
// This function will run within each post array including multi-dimensional arrays
function ExtendedAddslash(&$params)
{
foreach ($params as &$var) {
// check if $var is an array. If yes, it will start another ExtendedAddslash() function to loop to each key inside.
is_array($var) ? ExtendedAddslash($var) : $var=addslashes($var);
unset($var);
}
}
// Initialize ExtendedAddslash() function for every $_POST variable
ExtendedAddslash($_POST);
$librarian_fname = $_POST['librarian_fname'];
$id = $_POST['id'];
?>
<?php
if(isset($_POST['add'])) {
$dbhost = 'localhost';
$dbuser = '';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = "UPDATE table SET librarian_fname = '$librarian_fname' WHERE id = '$id'";
mysql_select_db('Events');
$result = mysql_query( $sql, $conn );
if(! $result ) {
die('Could not enter data: ' . mysql_error());
}
mysql_close($conn);
header("Location: search.php");
}
else {
?>
<?php
// define variables and set to empty values
$librarian_fname = $id = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$librarian_fname = test_input($_POST["librarian_fname"]);
$id = test_input($_POST["id"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>">
<legend><b>Appointment Topic</b></legend>
<input type="hidden" name="id" value="<? echo $id; ?>">
<label for="librarian_fname">First Name <em>*</em></label>
<input type="text" name="librarian_fname" size="50" required="no" validateat="onsubmit" message="Please enter your first name."> input name = "add" type = "submit" id = "add" value = "Submit">
</form>
<?php
}
?>
Try this
<form method="post" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>">
<legend><b>Appointment Topic</b></legend>
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
<label for="librarian_fname">First Name <em>*</em></label>
<input type="text" name="librarian_fname" size="50" required="no" validateat="onsubmit" message="Please enter your first name."> <input name = "add" type = "submit" id = "add" value = "Submit">
<input type="reset" name="resetButton" id="resetButton" vvalue="Reset Form" style="margin-right: 20px;" />
</form>
I think one of the issues may be that TABLE is a MySQL reserved word.
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
If we want to use a reserved word as an identifier (e.g. table name) it must be escaped. The normative pattern in MySQL to escape identifiers is to enclose them in single backtick characters, e.g.
UPDATE `table` SET
That works whether the identifier is a reserved word or not. Better would be to use a different name for the table.
Be aware that the code appears to be vulnerable to SQL Injection. Potentially unsafe values incorporated into the text of a SQL statement must be properly escaped (e.g. using mysqli_real_escape_string)
https://xkcd.com/327/
The preferred pattern is to not incorporate values into the SQL text, and instead use a prepared statement with bind placeholders.

$_POST data from form being changed before entered into MySQL

So new here to stack exchange but here goes nothing. So when I send a form to my apache server my data is only showing up as ones and zeros. Using var_dump[_$POST]; shows all of my data is correct before passing to MySQL.
My html form:
<form method="POST" action="submit.php" class="subForm">
<input type="text" name = "item1" value="0">
<input type="text" name="item2" value="0">
<input type="text" name="item3" value="no">
<input type="text" name="item4" value="no">
<input type="text" name="item5" value="no">
<input type="text" name="item6" value="no">
<input type="submit" id = "form2">
</form>
my php:
$connect = mysqli_connect('*****','*****','*****','*****');
if(!$connect){
die('Could not Connect: ' . mysqli_error($connect));
}
$NoR = isset($_POST["item1"]);
$CC = isset($_POST["item2"]);
$SD = isset($_POST["item3"]);
$HD = isset($_POST["item4"]);
$pack1 = isset($_POST["item5"]);
$pack2 = isset($_POST["item6"]);
$sql = "INSERT INTO form_test (item_1,item_2,item_3,item_4,item_5,item_6) VALUES (".$NoR.",".$CC.",".$SD.",".$HD.",".$pack1.",".$pack2.")";
mysqli_query($connect, $sql);
mysqli_close($connect);
var_dump($_POST)
var_dumb shows all data input is correct but in the table itself everything shows as 1s and 0s. Any advice?
In php, isset will return a boolean value (true if it's set, false if not), and when you try to print a boolean in php, it will display as 1 or 0. I suggest using the ternary comparison in your code, it's shorter and more readable than having a ton of if statements:
$NoR = isset($_POST["item1"]) ? $_POST["item1"] : '';
$CC = isset($_POST["item2"]) ? $_POST["item2"] : '';
$SD = isset($_POST["item3"]) ? $_POST["item3"] : '';
$HD = isset($_POST["item4"]) ? $_POST["item4"] : '';
$pack1 = isset($_POST["item5"]) ? $_POST["item5"] : '';
$pack2 = isset($_POST["item6"]) ? $_POST["item6"] : '';
Add this in your HTML form
<input type="text" name="action" value="submit">
And PHP code will be
if (isset($_POST['action']) && ($_POST['action']) == 'submit') {
$NoR = mysqli_real_escape_string($_POST["item1"]);
$CC = mysqli_real_escape_string($_POST["item2"]);
$SD = mysqli_real_escape_string($_POST["item3"]);
$HD = mysqli_real_escape_string($_POST["item4"]);
$pack1 = mysqli_real_escape_string($_POST["item5"]);
$pack2 = mysqli_real_escape_string($_POST["item6"]);
$sql = "INSERT INTO form_test (item_1,item_2,item_3,item_4,item_5,item_6) VALUES (".$NoR.",".$CC.",".$SD.",".$HD.",".$pack1.",".$pack2.")";
mysqli_query($connect, $sql);
mysqli_close($connect);
//var_dump($_POST)
}
isset will only give you if value is set or not. 1 if set else 0.
Use
if(isset($_POST["item1"])){
$NoR = $_POST["item1"];`
}
Updated: I made code for you to make sude ISSET values only goto INSERT query!
$arrColumns = $arrValues = array();
foreach($_POST as $key=>$value){
$arrColumns[] = key($key);
$arrValues[] = $value;
}
if(is_array($arrValues)){
$sql = "INSERT INTO form_test (implode(',',$arrColumns))
VALUES(implode(',',$arrValues)";
mysqli_query($connect, $sql);
}
mysqli_close($connect);

filling in form fields from previous database entry - php

I am trying to create a form where everything is filled out from the user's previous entry. Its suppose to work by the user selecting the "update" link. However the form is not being filled at all.
I've been trying to figure this out for 2 days now but i cant seem to figure it out. Some help would be greatly appreciated, thanks!
up.php
<form method="POST" action="up1.php">
<?php
$connection = mysql_connect("xxxxx","xxxxx","xxxxx")
or die("Could not make connection.");
$db = mysql_select_db("xxxxx")
or die("Could not select database.");
$sql1 = "SELECT * FROM emp ORDER BY primeID DESC ";
$sql_result = mysql_query($sql1) or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($sql_result))
{
$prime = $row["primeID"];
}
?>
Update
</form>
up1.php
<form action="up2.php" method="post">
<?
$connection = mysql_connect("xxxxx","xxxxx","xxxxx")
or die("Could not make connection.");
$db = mysql_select_db("xxxxx")
or die("Could not select database.");
$sql1 = "SELECT * FROM emp WHERE primeID = '$up22'";
$sql_result = mysql_query($sql1)
or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($sql_result))
{
$prime = $row["primeID"];
$a1 = $row["country"];
$a2 = $row["job"];
$a3 = $row["pos_type"];
$a4 = $row["location"];
$a5 = $row["des"];
$a6 = $row["des_mess"];
$a7 = $row["blurb"];
$a8 = $row["restitle"];
$a9 = $row["res"];
$a10 = $row["knowtitle"];
$a11 = $row["know"];
$a12 = $row["mis"];
$a13 = $row["mis_des"];
}
?>
<input name="aa1" value="<? echo $a1; ?>" type="text" id="textfield" size="60">
<input name="a1" type="text" value="<? echo $a2; ?>" id="textfield" size="60">
<input name="a2" type="text" value="<? echo $a3; ?>" id="a2" size="60">
<input name="a4" type="text" value="<? echo $a5; ?>" id="a4" size="60">
</form>
Based upon the limited information I could get out of your post I think I found the problem:
Starting with up.php
Update
Actually sends a "GET request" (Loading the page with a query string). We need to rebuild that:
<a href="JavaScript: void(0)" onclick="this.parentElement.submit()" >Update</a>
Now this link is going to send the form. However we need to send the value $prime. Let's use a hidden input inside the form.
<input type="hidden" name="up22" value="<? echo $prime; ?>" />
Now when the user clicks the link it posts the form and loads up1.php with the post var up22.
Changes to up1.php
$sql1 = "SELECT * FROM emp WHERE primeID = '".$_POST['up22']".'";
PDO
To update your code even further: PDO is a safer way to do queries. mysql queries are deprecated. They shouldn't be used anymore.
Replace your database calls with the following code:
function openDBConnection()
{
$name = "xxxxxx";
$pw = "xxxxxx";
$server = "xxxxxxx";
$dbConn = new PDO("mysql:host=$server;dbname=xxx", $name, $pw, , array( PDO::ATTR_PERSISTENT => false));
}
catch( PDOException $Exception )
{
echo "120001 Unable to connect to database.";
}
return $dbConn;
}
function doPDOQuery($sql, $type, $var = array())
{
$db = openDBConnection();
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
if ($type == "prepare")
{
$queryArray = $var;
$sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute($queryArray);
}
else if ($type == "query")
{
$sth = $db->query($sql);
}
else
{
echo "Supplied type is not valid.";
exit;
}
if (!$sth)
{
$error = $db->errorInfo();
echo $error;
exit;
}
return $sth;
}
These functions you can use to make PDO queries to the database. The first function opens a database connection, while the second functions actually performs the query. You do not need to call the first function. It's called in the second one.
Example based upon your code:
$sql1 = "SELECT * FROM emp WHERE primeID = :id";
$sql_result = doPDOQuery($sql1, 'prepare', array(":id" => $_POST['up22']));
while ($row = $sql_result->fetchAll() )
{
//loop through the results.
}
PDO works as follows: instead of passing php variables into the SQL string (and risking SQL-injection), PDO passes the SQL string and variables to the database and let's the database's driver build the query string.
PDO variables can be declared by name or by index:
By name: use : to declare a named variable. SELECT * FROM TABLE WHERE id = :id. Each key must be unique.
By index: use ? to declare an indexed variable. SELECT * FROM TABLE WHERE id = ?
An array containing the variables needs to be passed to PDO.
named array:
array(":id" => 1);
indexed array:
array(1);
With named arrays you don't have to worry about the order of the variables.
http://php.net/manual/en/book.pdo.php

<input type = "file"> EMPTY

i have this problem regarding file upload on php.
I always get this error msg.
Warning: file_get_contents(): Filename cannot be empty in
C:\xampp\htdocs\omf2\emprecords\add8.php on line 25
this is my line 25
$data = $con->real_escape_string(file_get_contents($_FILES['uploaded_file']['tmp_name']));
But still saves the info on my database.
What i am trying to do is save the rest of the records on my database even if not selecting a file to upload. And yes the records are saved and the Attachment field (mediumblob) is [BLOB - 0 B]
Question: How can i eliminate the error/warning message? (because everything is really fine)
<meta http-equiv="refresh" content="2;URL='emphistory.php'">
<?php
{
echo "<center><font color='#AAA' size='3'><br/>Record Added!</center>";
}
?>
<?php
$con=mysqli_connect("localhost","root","","dbomf");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM valueholder");
$row = mysqli_fetch_array($result);
$count = '';
$IDNUM = $row['Val'];
$NS = addslashes($_POST ['NS']);
$ad = addslashes($_POST ['ad']);
$hr = addslashes($_POST ['HR']);
$name = $con->real_escape_string($_FILES['uploaded_file']['name']);
$data = $con->real_escape_string(file_get_contents($_FILES['uploaded_file']['tmp_name']));
include ('../dbconn.php');
$query = "INSERT INTO tblemphist1 VALUES
('".$count."', '".$IDNUM."', '".$NS."', '".$ad."', '".$hr."', '".$data."', '".$name."')";
$result = $db->query($query) or die($db->error);
$db->close();
here
<form method="post" action="add8.php" enctype="multipart/form-data">
<td><strong>Attachment</strong></td>
<td>:</td>
<td><input type="file" name="uploaded_file"></td>
</tr>
</form>
<input type = "file">
should be
<input name="uploaded_file" type = "file">
also form method should be post and use enctype='multipart/form-data
<form action="" method="post" enctype="multipart/form-data">
<input name="uploaded_file" type = "file">
</form>
also check
$name = ''; $data = '';
if ((is_uploaded_file($_FILES['uploaded_file']['tmp_name']) && !($_FILES['uploaded_file']['error'])) {
$name = $con->real_escape_string($_FILES['uploaded_file']['name']);
$data = $con->real_escape_string(#file_get_contents($_FILES['uploaded_file']['tmp_name']));
}
include ('../dbconn.php');
$query = "INSERT INTO tblemphist1 VALUES ('".$count."', '".$IDNUM."', '".$NS."', '".$ad."', '".$hr."', '".$data."', '".$name."')";
$result = $db->query($query) or die($db->error);
Use an if statement. For example:
if (!empty($_FILES)) {
$data = $con->real_escape_string(
file_get_contents($_FILES['uploaded_file'] ['tmp_name'])
);
}
Before accessing any property of $_FILES['uploaded_file'] you have to check the value $_FILES['uploaded_file']['error']. And yes, it's a good idea to check if such key exists at all - as with anything coming from the user, there is no guarantee that it exists in the request.
Simply check if the variable is not empty
$data = '';
if (!empty($_FILES['uploaded_file']['tmp_name'])) {
$data = $con->real_escape_string(file_get_contents($_FILES['uploaded_file']['tmp_name']));
}
if error doesn't affect your project just ignore it and add this code in top of your php.
<?php ERROR_REPORTING(E_ALL & ~E_NOTICE); ?>
it will ignore and hide the error. :)

Categories