How to get a MySQL field's content with PHP? - php

I've been working on my website's database and I had this problem recently:
I want the user to read a field of a row, when another field of the same row is submitted.
I.e:
user_id=1 user_name=Fran user_pass=Potato referedby_id=0 referedby_name=empty
When going inside www.website.com/form.php?referedby_id=1
I want the user to see "So, Fran refered you?"
I've been learning php and I decided to try this:
$referedbyid = mysqli_real_escape_string($con,$_POST["referedby_id"]); //In this case it's 1 because of the url
$sel_referedbyname = "select user_name from users where user_id='$referedbyid'"; //Then this should be the select of the user_name "Fran"
$run_referedbyname = mysqli_query($con, $sel_referedbyname); //Then a query for that select
$check_referedbyname = mysqli_fetch_field($run_referedbyname); //And this one the content of the query's result
$refername = $check_refername->user_name; //As the query result is an object I want to convert it to text
if(isset($_POST["register"]) && $check_user == 0 && $check_email == 0 && $pass == $pass2){ //If everything is right and the user/email does not already exist
mysqli_query($con,"INSERT INTO users (user_name, user_email, user_pass, refer_id, refer_name) VALUES ('$user', '$email', '$pass', '$referid', '$refername')"); //It's submitted to the database with the other values.
mysqli_close($con); //And we finish the connection with the db.
The problem is that when I try this and check the database, the referedby_name field is empty. Is it a syntax error? Or is this because it didn't convert to text properly?
In case $referedbyname is not text, how can I convert it properly? Is this because I'm using the fetch_field function wrong?
Additional info: $referedbyid is being called properly (I think) in a POST form with this html
<form action="register.php" method="post" onsubmit="validate();">
<table width="500" align="center" bgcolor="skyblue">
<tr align="center">
<td colspan="3"><h2>Registrarse</h2></td>
</tr>
<tr>
<td align="right"><b>Nombre de usuario:</b></td>
<td><input type="text" name="user" required="required"/></td>
</tr>
<tr>
<td align="right"><b>Email:</b></td>
<td><input type="email" name="email" required="required"/></td>
</tr>
<tr>
<tr>
<td align="right"><b>Contraseña:</b></td>
<td><input type="password" id="pass" name="pass" required="required"/></td>
</tr>
<tr>
<td align="right"><b>Verificar contraseña:</b></td>
<td><input type="password" id="pass2" name="pass2" required="required"/></td>
</tr>
<tr align="center">
<td colspan="3">
<input type="hidden" name="referedby_id" value="<?php echo $_GET["referedby_id"]; ?>"/>
<input type="submit" name="register" value="Registrarse"/></td>
</tr>
</table>
</form>

I don't know why the downvotes, I tried to be as clear and specific as I could...
Anyways, if someone else has any trouble finding the value of a specific field just use mysqli_fetch_assoc(mysqli_query($conect, $select))['name of the sql field']
mysqli_fetch_field($result) will only show you information about the field, like the type of input, name of the table, name of the column, etc.
Hope that's useful for someone with the same issue. Bye.

Related

How to properly send and insert a field data to a column of Time and Date data type

I'm using PostgreSQL for my tests and I've set one column start_dte as Date data type while scheduled_time and sla_time are both Time data type. I've created a form that would allow me to insert new record.
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="POST">
<table border="0" cellspacing="10">
<tr>
<td>RID:</td> <td><input type="text" name="newrid" value=""></td>
</tr>
<tr>
<td>Day:</td> <td><input type="text" name="newday" value=""></td>
</tr>
<tr>
<td>Scheduled Time:</td> <td><input type="text" name="newsched" value=""></td>
</tr>
<tr>
<td>SLA Time:</td> <td><input type="text" name="newsla" value=""></td>
</tr>
<tr>
<td>Start Date:</td> <td><input type="text" name="newsd" value=""></td>
</tr>
<tr>
<td><INPUT TYPE="submit" VALUE="Save" NAME="submit"></td>
</tr>
</table>
The PHP Code right below it is this:
<?php
if(isset($_POST['submit'])) {
$rid = $_POST['newrid'];
$day = $_POST['newday'];
$scheduled_time = $_POST['newsched'];
$sla_time = $_POST['newsla'];
$start_dte = $_POST['newsd'];
$data = $dbh->prepare("INSERT into meta_auto_reports.frequency values ($rid, '$day', $scheduled_time, $sla_time, $start_dte)");
$data->execute();
echo "<h2>Inserted Successfully</h2>";
$data = null;
}
?>
This shows an error upon submit:
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[42804]: Datatype mismatch:
So I'm wondering what's the proper way of formatting user input in a way that postgresql would accept. The Columns are Nullable as well, which means an empty field left blank by a user would have to place NULL upon insertion.
Few comments about this code:
Form values should be stored in an array:
<td>RID:</td> <td><input type="text" name="form[newrid]" value=""></td>
<td>Day:</td> <td><input type="text" name="form[newday]" value=""></td>
This way, it is easier to manipulate them:
$form_data = $_POST['form'];
I would strongly suggest you use a library to validate and clean the data submitted by end users (symfony/validator does this job but there are many other libraries).
Now, the database part. Data sent to the database need to be escaped to protect you application against SQL injection. Using a prepared statement is a way to pass data as parameters:
$stmt->prepare("INSERT into meta_auto_reports.frequency values (:id, :day, :scheduled_time …)");
$stmt->execute($form);
Using PDO directly does mix different concerns in the same layer of code (the how and the what). Using a library to handle database connectivity and queries is a good idea. (Pomm if specifically using Postgres or any DBAL or ORM if you want database abstraction).

Data entry to a particular mysql database table via php, results "undefined index error" pointing variables of another table

I'm not in a very good level in php coding. i have a php interface(code: insert.php) which has four forms that are used to enter data to four different tables in my database and data entry to the forms are independent from each other. but, when i enter data to a form, it results in "undefined index error" pointing two variables which are related to another form in the interface. and also, data is not entered to the table in the database. not all the forms cause this error.they work fine.
this is the code of 'insert.php' the form i need data to be inserted.
<form method="post" action="input.php">
<tr>
<td>ID</td>
<td><input type="text" name="cat_id" size="40">
</td>
</tr>
<tr>
<td>Description</td>
<td>
<textarea NAME="desc" COLS=31 ROWS=6></textarea>
</td>
</tr>
<tr>
<td>
</td>
<td align="right">
<input type="submit" name="submit" value="Done">
</td>
</tr>
this is the code in 'insert.php', the error variables related to.
<form method="post" action="input.php">
<tr>
<td>ItemID</td>
<td><input type="text" name="item_id" size="40">
</td>
</tr>
<tr>
<td>EPF</td>
<td><input type="text" name="epf" size="40">
</td>
</tr>
<tr>
<td>Quantity</td>
<td><input type="text" name="quan" size="40">
</td>
</tr>
<tr>
<td>Date</td>
<td><input type="date" name="date" size="40">
</td>
</tr>
<tr>
<td>
</td>
<td align="right">
<input type="submit" name="submit" value="Done">
</td>
</tr>
this is the code in 'input.php'.
<?php
$cat_id=$_POST['cat_id'];
$cat_descr=$_POST['desc'];
$query_cat = "INSERT INTO 'category' ( id, description)
VALUES ('$cat_id','$cat_descr')" or die (mysql_error());
$result_cat = mysql_query($query_cat);
?>
<?php
$item_id=$_POST['item_id'];
$epf2=$_POST['epf'];
$quan=$_POST['quan'];
$date=$_POST['date'];
$query_itemEmp = "INSERT INTO 'emp_div_item' ( epf, item ,quantity, date)
VALUES ('$epf2','$item_id','$quan','$date')" or die (mysql_error());
$result_itemEmp = mysql_query($query_itemEmp);
?>
<?php
if( $result_emp || $result_cat || $result_item || $result_itemEmp){
echo("<br>Input data is succeed");
} else{
echo("<br>Input data is fail");
}
?>
the variables which the error points out are $quan and $date.. $result_item and $result_emp are query results get from other forms which work fine.please note that users dont need to enter data to all forms at a time. they can chose whatever the number of forms to be filled at a time.
plese help me to solve this problem and thank you in advance.
I think the problem is with the HTML code, you are having two seperate forms :
<form method="post" action="input.php"> ---first one
<form method="post" action="input.php"> --- second one
So when you click on first form's submit, only that form's data will be submitted (here , only cat_id and desc will be available in input.php)
And then you try access other forms values in the same input.php ($item_id=$_POST['item_id']; which is not present with the first form's data.
Hence you get this error.
Also if you will try to submit the second form, the you will get the same error for $cat_id and $cat_descr variables.
So keep all the data in a single form.
As far as your queries concerned: don't put quotes around db identifiers. Use ticks if you need to.
That being said change
$query_cat = "INSERT INTO 'category' (id, description) VALUES ('$cat_id','$cat_descr')" or die (mysql_error());
^ ^
to
$query_cat = "INSERT INTO category (id, description) VALUES ('$cat_id','$cat_descr')" or die (mysql_error());
and
$query_itemEmp = "INSERT INTO 'emp_div_item' (epf, item ,quantity, date) VALUES ('$epf2','$item_id','$quan','$date')" or die (mysql_error());
^ ^
to
$query_itemEmp = "INSERT INTO emp_div_item (epf, item ,quantity, date) VALUES ('$epf2','$item_id','$quan','$date')" or die (mysql_error());
On a side note: your code in current state vulnerable to sql-injections. Learn and use prepared statements with either mysqli or PDO. mysql_* extension is deprecated and is no longer supported.

Displaying Data from mysql table

I have created this form using the while loop so that i dont have to make 28 text field ... but when i submit the data into my mysql database it works well but how to display the data back to my form for edit and update .. when i type a value to a text field (EX - submitted data from mysql in emp_name field) then it repeated 4 times in the text field .... i know it is happening because of loop but is there any way that i can display multiple data in each text field for updating after submitting data by the user as normal ....
my form.php
<form action="userdata.php" name="frmAdd" method="post">
<table width="80%" border="0" cellpadding="3" cellspacing="3" class="forms">
<tr>
<td width="5"> <div align="center">NO</div></td>
<td width="91"> <div align="center">Employer's NAME</div></td>
<td width="160"> <div align="center">COUNTRY</div></td>
<td width="198"> <div align="center">POSITION</div></td>
<td width="70"> <div align="center">FROM</div></td>
<td width="70"> <div align="center">TO</div></td>
<td width="70"> <div align="center">SALARY</div></td>
<td width="70"> <div align="center">REASONS FOR LEAVING</div></td>
</tr>
<?php for($i=1;$i<=4;$i++) { ?>
<tr>
<th width="5"> <div align="center"><? echo $i . "."; ?></div></th>
<td><input type="text" name="emp_name<?=$i;?>" size="25" value="submitted data from mysql"></td>
<td><input type="text" name="emp_country<?=$i;?>" size="10"></td>
<td><input type="text" name="emp_pos<?=$i;?>" size="10"></td>
<td><input type="text" name="emp_frm<?=$i;?>" size="5"></td>
<td><input type="text" name="emp_to<?=$i;?>" size="5"></td>
<td><input type="text" name="emp_sal<?=$i;?>" size="5"></td>
<td><input type="text" name="emp_lev<?=$i;?>" size="25"></td>
</tr>
<?php } ?>
</table>
</br>
<input type="submit" name="doHis" value="Save Employment History">
<input type="hidden" name="hdlfrm" value="<?=$i;?>">
</form>
and my userdata.php
if($_POST['doHis'] == 'Save Employment History')
{
try{
$conn = new PDO("mysql:host=localhost;dbname=dbname", "user", "pass");
}
catch(PDOException $pe)
{
die('Connection error, because: ' .$pe->getMessage());
}
for($i=1;$i<=$_POST["hdlfrm"];$i++){
if($_POST["emp_name$i"] != ""){
$sql = "INSERT INTO emp_table (emp_name, emp_country, emp_pos, emp_frm, emp_to, emp_sal, emp_lev)
VALUES (:emp_name, :emp_country, :emp_pos, :emp_frm, :emp_to, :emp_sal, :emp_lev)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':emp_name', $_POST["emp_name$i"]);
$stmt->bindParam(':emp_country', $_POST["emp_country$i"]);
$stmt->bindParam(':emp_pos', $_POST["emp_pos$i"]);
$stmt->bindParam(':emp_frm', $_POST["emp_frm$i"]);
$stmt->bindParam(':emp_to', $_POST["emp_to$i"]);
$stmt->bindParam(':emp_sal', $_POST["emp_sal$i"]);
$stmt->bindParam(':emp_lev', $_POST["emp_lev$i"]);
$stmt->execute();
echo "Save Done. Click <a href='phpMySQLListRecord.php'>here</a> to view.";
}
}
}
and here is the snapshot
The problem you have is your data model - you are saving employment history, but for who? It needs to have an employee_id somewhere to say who this data belongs to, and join it to a table that saves the employee_table data. Next you need to have a unique ID on the emp_table to identify each row, which you can use instead of your $i index.
TABLE
history_id INT autoincrement | employee_id INT | emp_name VARCHAR | your other fields....
SELECT
SELECT history_id, emp_name, ... FROM emp_history where employee_id = ?
You can then loop over the results and use the history_id to identify the row that the data belongs to to update it. Submitting multiple fields with the same name will be an array you can iterate over, so you don't need to use a unique field name for each.
As a side note, you probably want to use isset($_POST["key"]) instead of $_POST["key"] != "" to check if a field was submitted.

Insert same data into database

I have a web-based form that accepts student information. After I've Inserted data I want it to be still available even if I refresh the browser It would mean that 2 rows are the same but I dont want to insert the same data again. How can this be possible?
My code are here:
<form method="post" action="insert.php" >
<table>
<tr>
<td width="22%"> Name</td>
<td width="4%"></td>
<td width="74%"><input type="text" name="name" > </td>
</tr>
<tr>
<td>Information </td>
<td></td>
<td><input type="text" name="infomn" ></td>
</tr>
<tr>
<td>Email </td>
<td></td>
<td><input type="text" name="email" ></td>
</tr>
<tr>
<td>Password </td>
<td></td>
<td><input type="password" name="password" ></td>
</tr>
<tr>
<td colspan="3"> </td>
</tr>
<tr>
<td></td>
<td></td>
<td ><input type="submit" name="submit" value="Insert" >
</td>
</tr>
</table>
</form>
insert.php:
include("connect.php");
if($_POST['submit']){
$name=$_POST[name];
$info=$_POST[infomn];
$emal=$_POST[email];
$password=$_POST[password];
$query = "insert into student(name,designation,email,password) values('$name','$info','$emal','$password')";
mysql_query($query) or die("not successfully insert".mysql_error());
?>}
I would check if your values have been filled before attempting to insert your data.
if ($_POST['name']) {
//Validate, escape, insert...
} else {
//Display form...
}
Please please please make sure the data you insert into the database is escaped, especially if you're working with student data.
At the moment it looks like this:
Info is posted to insert.php
You are located in insert.php and the variables posted exist aswell.
The database execution is performed with the existing data.
You refresh.
You never really leave the page because the refresh makes you go to the same page, so the browser assumes that the posted data should not be deleted but used again.
To avoid this, you must add
header("Location: index.php");
Or some similar code, to make sure that the user won't stay on the same page after the database execution is performed.
insert.php:
include("connect.php");
if(isset($_POST['submit'])) { // put isset() for checking if it submitted or not
$name=$_POST['name'];
$info=$_POST['infomn'];
$emal=$_POST['email'];
$password=$_POST['password'];
$query = "insert into student(name,designation,email,password)
values('$name','$info','$emal','$password')";
if(mysql_query($query)) {
header('Location:your_form_page.php'); // redirect to avoid inserting data while refreshing
}else {
mysql_error() };
}
recommendation : Try use PDO How can I prevent SQL injection in PHP?
Browser refresh posts the last action (again) to the server.
Use the Post/Redirect/Get pattern (http://en.wikipedia.org/wiki/Post/Redirect/Get) i.e. redirect always after successful action (in your case database insert).

Only inserts in to database once then fails

I have a small section of code. When the table is empty this code works fine and enters in to the table fine. But then if i try again then this fails with the error?
What am i doing wrong?
Thanks
// On my Function page
function admin(){
connect();
$query = mysql_query("INSERT INTO results
(t_id, pos1, pos2, pos3)
VALUES ('$_POST[t_id]','$_POST[pos1]','$_POST[pos2]','$_POST[pos3]')")
or die ("Error.");
$b = "Updated fine</b></a>.";
return $b;
exit();
}
// Then on my main page
<?php
include ('functions.php');
if (isset($_POST['admin'])){
$admin = admin();
}
?>
<div id="content">
<div id="admin">
<form action="" method="post">
<table width="100%" border="0" align="center" cellpadding="3" cellspacing="1">
<tr>
<td width="100%"><?php echo "$admin"; ?></td>
</tr>
<tr>
<td width="100%"><label>Track <input type="text" name="track" size="25" value="<? echo $_POST[t_id]; ?>"></label></td>
</tr>
<tr>
<td width="100%"><label>Position 1<input type="text" name="pos1" size="25" value="<? echo $_POST[pos1]; ?>"></label></td>
</tr>
<tr>
<td width="100%"><label>Position 2 <input type="text" name="pos2" size="25" value="<? echo $_POST[pos2]; ?>"></label></td>
</tr>
<tr>
<td width="100%"><label>Position 3 <input type="text" name="pos3" size="25" value="<? echo $_POST[pos3]; ?>"></label></td>
</tr>
<tr>
<td width="100%"><input class="save" type="submit" value="" name="admin"></td>
</tr>
</table>
</form>
</div>
</div>
Without seeing your table schema, I can only think you have UNIQUE t_id and you want to insert the same ID into it.
Several way to debug:
Use or die ("Error: " . mysql_error()); instead of just or die ("Error.");
Check your table schema: SHOW CREATE TABLE tablename and write it down on your question, so we can see if it's causing error.
It is hard to guess. Maybe you are entering the same values twice, and they happen to violate some unique constraint?
But you make another mistake: you forget to call mysql_real_escape(). That is bad.
Can you tell us of the error? It sounds like you're hitting a primary key violation, perhaps by trying to insert the same id more than once.
That aside, your code is riddled with security holes.
You should not be inserting variables straight from the POST into your query. All I have to do is submit '; DROP DATABASE and I can completely wreck your system.
Additionally, you're injecting values directly from POST into input fields, meaning I can set up a button on my site that submits " <script type='text/javascript'>window.location='http://mysite.com'</script> or something along those lines and take over your page.
This may sound terse, but you should do some googling or pick up a book regarding textbook security issues with websites.
EDIT: Just saw your comment about learning security. My advice is to be proactive about this sort of thing, because being reactive is often too late to fix problems.

Categories