Facing issue while running PHP script - php

I have a form in HTML which posts two values hostname and ip_address.
<form action="demo-select.php" method="post" />
<p>HOSTNAME/IPADDRESS: <input type="text" name="HOSTNAME" name="IP_ADDRESS" /></p>
<input type="submit" value="Submit" />
</form>
If I enter the hostname/ip_address and submit it, it will take me to demo-select.php script.
In demo-select.php script I'm able to get the output for hostname from my MySQL db. How should I get the output based on ip_address?
$value = $_POST['HOSTNAME'];
$query = "SELECT * FROM <tablename> WHERE HOSTNAME='$value'";
$result = mysql_query($query);
This script connects to a MySQL db and gets the output based on the hostname. What modifications should I make to get the output based on ip_address as well?
Table columns:
HOSTNAME
IP_ADDRESS
cpus
MEMORY

HTML:
You can't assign two names to an HTML element. I'd suggest that you either use two fields or use a dropdown / radio button along with the form field for the user to specify whether they're entering a hostname or an ip_address:
<form action="demo-select.php" method="post" />
<select name="address_type">
<option value="ip"> IP Address </option>
<option value="host"> Host Name </option>
</select>
<input type="text" name="host_name_or_address" />
<input type="submit" value="Submit" />
</form>
An assumption here is that you'd want the user to enter as input only one of hostname or ip_address in a single submit. If you want both to be relayed to the PHP at once, then please get rid of the select dropdown and use two input fields instead.
PHP:
Check what's been received in address_type and determine what query to use accordingly:
$address_type = $_POST['address_type'];
$value = $_POST['host_name_or_address'];
if($address_type == "host"){
// If looking for partial matches, use... WHERE HOSTNAME LIKE '%$value'
$sql = "SELECT * FROM <tablename> WHERE HOSTNAME = '$value' ";
}
else{
$sql = "SELECT * FROM <tablename> WHERE IP_ADDRESS = '$value' ";
}
Again, if you want both fields to be searched for at once, then along with the HTML edits indicated in the narration above, you'll have to receive in a PHP variable the value of the second input field too. Also then please get rid of the if-else construct here above and write a single, combined query as:
$sql = "SELECT * FROM <tablename> WHERE HOSTNAME = '$value1' AND IP_ADDRESS = '$value2' ";
Finally, please don't use mysql_*() functions in any PHP code. They're long deprecated and are very vulnerable to SQL Injection Attacks as Daniel has already suggested in his answer. Please have a look at MySQLi and PDO Prepared Statements instead. These utilities provide a cleaner way to write your queries and also a much safer mechanism to shield them against potential risks.

Related

Eror in SQL syntax: Update query

I am a beginner to PHP and I am working on a profile page. The current problem is to change the name (This is a trial page that's why i am changing the name).For some reason i am getting the error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'lastName ='Lname' WHERE email ='qwerty#example.com'' at line 1.
<?php
include('server.php');
$db = mysqli_connect('localhost','root','','userdata');
$query = "SELECT * FROM data WHERE email = '".$_SESSION['username']."'";
$result = mysqli_query($db,$query);
$data = mysqli_fetch_assoc($result);
?>
<html>
<head>
<title>Profile</title>
</head>
<body>
<form method="POST" action="">
<p>First name: <input type="text" name="fname" value="<?php echo htmlspecialchars($data['firstName']); ?>" > </p>
<p>Last name: <input type="text" name="lname" value="<?php echo htmlspecialchars($data['lastName']); ?>"> </p>
<p><input type="Submit" name="confirm" value="Confirm"></p>
</form>
<?php
if(isset($_POST['confirm']))
{
$db = mysqli_connect('localhost','root','','userdata');
$query = "UPDATE data SET firstName ='".$_POST['fname']."' lastName ='".$_POST['lname']."' WHERE email ='".$_SESSION['username']."'";
mysqli_query($db,$query);
echo mysqli_error($db); //For checking error.Remove afterwords.
}
?>
<p>HOMEPAGE</p>
</body>
</html>
The server.php is a page where I manage the backend of the entire operation so it's not involved in this operation.The first PHP block takes data from the table. The HTML block creates a form where the user can edit the data. The PHP block should update data into the table.
I would appreciate any tips to further improve my page as i am still new to this.Thanks in advance
UPDATE:- Adding , to the query still does not change the situation.
you have an error in your sql statement (as the error message suggests). in mysql the error message usually points out the exact position where the error occurs, and it usually quotes the first character/word that causes the problem.
in your case, that's lastname. Your update query so far is:
UPDATE data SET firstName ='fname' lastName ='Lname' WHERE email ='qwerty#example.com'
-- ^ error occured here
when you look-up how UPDATE queries are supposed to look like (mysql docs) you'd find, that the different updated fields must be separated by comma:
UPDATE data SET firstName ='fname', lastName ='Lname' WHERE email ='qwerty#example.com'
-- ^ add this here
also, you're vulnerable to sql injections (please read up on them, and how to prevent them - this is done by prepared statements)
Please try with that(there was a missing comma on your SQL query).
$query = "UPDATE data SET firstName ='".$_POST['fname']."', lastName ='".$_POST['lname']."' WHERE email ='".$_SESSION['username']."'";
The other problem of using code that is open to sql injection is you can easily change the syntax of an sql statement from the input side. For example if for last name you input "O'connor", you change the syntax. Try to use echo $query and then analyse the output or better still,copy it and run it directly without using php
As mentioned in the comment. When updating multiple fields you need to comma separate them:
UPDATE data
set
field1="meh", /* <-- comma */
field2="foo"
where otherField="something"

Update command of MySQL not working in PHP

This is my first very simple learning php program I have connected my PHP with MySQL Server and the Insert, Delete is working great but Update has some issue. When I press the update button nothing happens.
My database name is ddb3, the table name is student1.
The Apache server I am using is hosted via Xampp.
mysql_error(); shows no error and also no error in apache logfile
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("ddb3");
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$age = $_POST['age'];
mysql_query("INSERT INTO student1(name, age) VALUES ('$name', '$age');");
}
if(isset($_POST['delete'])) {
$name = $_POST['name'];
mysql_query("DELETE FROM student1 WHERE name = '$name';");
}
if(isset($_POST['update'])) {
$name = $_POST['name'];
$age = $_POST['age'];
mysql_query("UPDATE student1 SET name = '$name' WHERE age = '$age';");
}
?>
<html>
<body>
<center>
<form name='f1' action='prog3.php' method='post'>
<b>Name:<b><input type="text" name="name" size="20"><br>
<b>Age:<b><input type="text" name="age" size="5"><br>
<input type="submit" name="submit" value="Insert to Table"/>
<input type="submit" name="delete" value="Delete from Table"/>
<input type="submit" name="update" value="Update Row"/>
</form>
</center>
<?php
echo "<table align='center' name='t1' border='1' width=500px>
<tr><th>NAME</th><th>AGE</th></tr>";
$select = mysql_query("SELECT * FROM student1");
while($colmn = mysql_fetch_array($select)) {
echo "<tr><td>$colmn[0]</td><td>$colmn[1]</td></tr>";
}
echo "<table>";
?>
</body>
</html>
Describing the observed behavior as "not working" or "nothing happens" gives very little useful information, in determining what the actual problem is.
(How are you making the determination that "nothing happens", or that it's "not working"?)
I suggest adding some debugging output (for example, an echo or var_dump) at particular points in the code, to determine which path in the code is being taken. (Is $_POST['update'] set? Is the if condition evaluating to TRUE?)
https://ericlippert.com/2014/03/05/how-to-debug-small-programs/
I will note that it's very strange that we would change the name of a student based on age. For example, this statement will attempt to assign the same name to every student that is a particular age ...
UPDATE student1
SET name = 'Ted'
WHERE age = '19'
It would be very odd to do this. The SQL is valid. What is strange is which rows are being changed (all rows that have age=19), and the change that is being applied (changing the name of all the rows to the same value.)
It doesn't matter if the student's name is Jack, or Jill, or whatever. Every row in the table that has an age value of 19 is going to changed.
We typically don't store "age" as a column, but instead store a date of birth (dob). The DOB won't change. But age is going to change; age is the difference between DOB and the current (or some specified "as of") date. Age in years? Age in months, or days?
If we insist on storing age, then its much more likely that the age column is going to changed that the name column.
To identify which row should be updated... is name unique? Can there be two or more rows with the same name?
We probably want some unique identifier for the student, and use that in an UPDATE statment.
UPDATE student1 s
SET s.some_col = 'new_value'
WHERE s.id = 'unique_identifier'
Do not use the deprecated mysql_ interface for new development. Use PDO. (Or use mysqli_).
Also use prepared statements with bind placeholders to mitigate SQL Injection vulnerabilities. If for some unfathomable reason we can't do that, then at the very minimum, any potentially unsafe values incorporated into SQL text must be properly escaped.
Little Bobby Tables https://xkcd.com/327/
OWASP Project SQL Injection https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet

Form session not working when multiple users use it

i need an help from you all.
i had created an form using PHP. it's a school application registration form. it has one page only.
i need to generate registration number(session id used as registration number here) for everyone who opens the form.
instead of creating a session i have used ID for all. that is when some one submits the form, it checks the DB and if the registration number is there, it will increment one value and add the current form to DB.
my code here
<td>Application No : <input type="hidden" name="disablusr_dummyid" autocomplete="off" style="background:#f0efed;" value="00<?php
include('config.php');
$q="select MAX(auto_gen_id) from application_form";
$result=mysql_query($q);
$data=mysql_fetch_array($result);
$max_val=$data[0];
echo $max_val+1;
?>"/>
<input type="hidden" name="applicant_id" autocomplete="off" value="00<?php
include('config.php');
$wer = "select MAX(auto_gen_id) from application_form";
$resultgh = mysql_query($wer);
$dates = mysql_fetch_array($resultgh);
$erfdqwe = $dates[0];
echo $erfdqwe+1;
?>" />
<input type="hidden" name="txt_applicant_id" style="display:none;" autocomplete="off" value="<?php
include('config.php');
$werqw = "select MAX(auto_gen_id) from application_form";
$resultghasw = mysql_query($werqw);
$dataqsax = mysql_fetch_array($resultghasw);
$erfdqweqti = $dataqsax[0];
echo $erfdqweqti+1;
?>" /></td>
but what is happening is when multiple users are using the form same session ID is generated and only one user is able to save the form and it reflects in DB. other forms are being not submitted and not added to DB.
help me in this error.. thanks in advance.
The solution here is not the use the hidden fields for the IDs :
At this moment u have something like this :
"INSERT INTO (id, ..., ...) VALUES('".addslashes($_POST['applicant_id']."', ...)
You should refactor your logic to calculate the id afterwards meaning that u drop the hidden fields and do this :
<?php
if (!empty($_POST)) {
$wer = "select MAX(auto_gen_id) from application_form";
$resultgh = mysql_query($wer);
$dates = mysql_fetch_array($resultgh);
$erfdqwe = $dates[0];
$new_applicant_id = $erfdqwe+1;
}
And then use the $new_applicant_id into the INSERT sql.
On a sidenote your code is vulnerable for SQL injection and is using outdated functions.
You should try to move to mysqli or PDO and preferable use prepared statements

SQL text boxes with dynamic information / auto fill text boxes

I am trying to make a webpage that connects to my SQL database and fetches information from a table and place it into a text box. The information it fetches is dependent on what is entered into another text box. Essentially its an "autofill" of information. I was curious whether this was possible.
To create a better understanding here is a layout of text boxes:
<html>
<head>
<?php
$con = mssql_connect("abc", "123", "password");
if (!$con)
{
die('Could not connect: ' . mssql_get_last_message());
}
mssql_select_db("db1", $con);
$result = mssql_query("SELECT * FROM FormData");
<head>
<title>test</title>
</head>
<body>
<h1>test</h1>
<form action="#">
<p>Enter ID</p>
<input type="text" name="ID"/>
<input type="text" name="NAME"/>
<input type="text" name="LASTNAME"/>
<input type ="button" value="submit" onclick="check(ID)" />
</form>
</body>
Here an ID would be entered into a text box and then once the submit button was pressed, it would fetch the rest of the information from my sql database into the next boxes. I don't even know whether this is possible, whether I can use Javascript in conjunction with this or something. I searched but couldn't find much help on the subject.
I'm not even sure if its possible to do "if" statements within SQL - whenever I try I end up with a 500 error due to improper syntax.
If I understand you correctly, all you need to do is on the submission of the form capture the ID they entered.
If the ID has not been submitted yet (either their first time hitting the page, or they failed to enter an ID) you should not perform any query and create a blank $row array like so:
$row = array("ID" => "", "NAME" => "", "LASTNAME" => "");
You should then fill your form fields using this array <input type="text" name="NAME" value="<?php echo $row['NAME']; ?>"/>.
If the ID has been submited you then use this ID in your SQL query "SELECT * FROM FormData WHERE ID = $_POST['ID']" (Note: This is an example. You will need to escape the POST data to prevent SQL injection).
You need to then pull this result into your $row array $row = mysql_fetch_row($result) which in turn is used by your fields to populate the value.
This entire procedure could be done with AJAX so that you don't have to perform a full page submit however based on your example the solution I have provided should be good enough.

how to perform sql command on html page with user input field, and show result on the same page

i write a command, or i fill up parameter value from user input field. click the button, send this command to php and send resultant value back to html to display.
for example. on html page :
select ___ from ____,
two available input field i fill up with "tablenameone" and "valueone". then, result will be printed on html text field on the same page.
what i do know is those value can be sent(perhaps) as in such format
$('input[name="talbename"]')
$('input[name="value"]')
example.com?tablename=tablenameone&value=valueone
and from php side i use
$sql="SELECT '$_GET['value']' FROM '$_GET['tablename']';
what i dont know is that....how exactly should i perform this in a click function? its for sure using ajax. but how can i produce example.com?tablename=tablenameone&value=valueone
and where should i put $('input[name="value"]')
thanks in advance :D
You must not use direct input in your queries as you will be open to SQL injection attacks.
$sql="SELECT '$_GET['value']' FROM '$_GET['tablename']';
Instead, use the following:
$column = $_GET['value'];
$table = $_GET['tablename'];
$sql = sprintf("SELECT %s FROM %s;",
mysql_real_escape_string($column),
mysql_real_escape_string($table));
Although you are still exposing too much "inside information" by giving people a page that tells them all of your table and column names!
Anyway, here is a complete example;
<form method="post" action="">
<fieldset>
<legend>Select Data</legend>
<p><label>Table<br>
<select name="table">
<option value="tblStudents">Students</option>
</select></label></p>
<p><label>Table<br>
<select name="column">
<option value="firstname">First Name</option>
<option value="lastname">Last Name</option>
</select></label></p>
<p><input type="submit" name="submit" value="submit">
</fieldset>
</form>
<?php
$connection = mysql_connect("servername:3306", "user", "password") or die ('Error connecting to mysql');
mysql_select_db("databasename");
$column = mysql_real_escape_string($_POST['column']);
$table = mysql_real_escape_string($_POST['table']);
$sql = sprintf("SELECT %s FROM %s;",
$column,
$table);
$result = mysql_query($sql) or die(mysql_error());
echo '<ul>';
while($row = mysql_fetch_array($result)) {
echo '<li>' . $row[$column] . '</li>';
}
echo '</ul>';
mysql_close($connection);
?>
Seeming as though noone has actually answered the question (although they are all good points, I will assume there is a reason for you doing this), I will answer:
$('form[name=formname]').submit(function(e){
e.preventDefault;
var tablename = $('input[name="tablename"]').val();
var value = $('input[name="value"]').val();
$.get("example.php?tablename="+tablename+"&value="+value, function(data){
$('body div').text(data);
})
});
PHP:
$sql=mysql_query("SELECT '$_GET['value']' FROM '$_GET['tablename']'")or die(mysql_error());
$sqlOutput = mysql_fetch_array($sql);
echo "<pre>";
print_r($sqlOutput);
echo "</pre>";
Obviously replace formname with your form name, body div with the name of the element you want the output to go in and all other identifiers replaced where seen fit. Then change the output in the PHP to suit your needs.
Again, do bear in mind the posts regarding SQLi, because you have yourself a very serious problem there.
You really want to make sure you are not open to SQL injection.
You could use mysql prepared statements
or
use the php function mysql_real_escape_string($_GET['value'])
Read this thread:
How can I prevent SQL injection in PHP?
I'm not sure what you mean by the click function.

Categories