Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
When submitted, a new row gets added to the 'servers' table, but every data says '0' instead of the data I inputted.. I'm using VARCHAR64 for the rows..
Form.html
<html>
<head>
</head>
<body>
<form action="db.php" method="post">
server id: <input type="text" name="post_serverid">
server ip: <input type="text" name="post_serverip">
<input type="submit>
</body>
</html>
db.php
<?php
$con=mysqli_connect("localhost","root","","toplist");
//Checking the connection
if(mysqli_connect_errno($con))
{
echo "Cold not connect to SQL Database: " + mysqli_connect_error();
}
mysqli_query($con, "INSERT INTO servers (serverid, serverip) VALUES ('$_POST['post_serverid']', '$_POST['post_serverip']')");
?>
First: NEVER just throw user data straight into your database without validating / cleansing it first.
Next, you've got some odd punctuation going on in your mysqli_query(). Try this:
$serverid = $mysqli->real_escape_string($_POST['serverid']);
$serverip = $mysqli->real_escape_string($_POST['serverip']);
$sql = "INSERT INTO servers (serverid, serverip) VALUES('$serverid', '$serverip');";
mysqli_query($con, $sql);
From OP's comment:
"Strangely enough, mysqli_query($con,"INSERT INTO form (name, dob) VALUES ('$_POST[post_name]', '$_POST[post_dob]')"); works."
"But when I replace NAME with SERVERID, and replace DOB with SERVERIP, the inputted data doesn't insert."
The problem is, you need to change your POST variables and column names accordingly.
Rename your NAME column to SERVERID and DOB column to SERVERIP.
and post_name to serverid and post_dob to serverip
The new query can now be done this way:
$serverid = mysqli_real_escape_string($con,$_POST['serverid']);
$serverip = mysqli_real_escape_string($con,$_POST['serverip']);
$sql = "INSERT INTO `servers` (`serverid`, `serverip`) VALUES ('$serverid', '$serverip');";
mysqli_query($con, $sql);
Using this method will help prevent against SQL injection.
You might want to use $_POST['key'] instead of $_POST[key]
$_POST is an associative array, you need to access the keys with single or double quotes.
Example:
change your query to
$query = "INSERT INTO servers (serverid, serverip) VALUES ('".$_POST['post_serverid']."','".$_POST['post_serverip']."')";
mysqli_query($con, $query);
Also, you are currently volunerable to SQL injection. I'd suggest to use a prepared statement or at least escape the $_POST variables before inserting it to the DB.
Hope this helps!
$serverip=$_POST['post_serverid'];
$serverid=$_POST['post_serverip'];
$query = mysqli_query($con,"INSERT INTO servers (serverid, serverip) VALUES ('$serverid','$serverid')");
Try this, it should work
Related
i want to make a form where people can add some info, and that will add up to the existing info in the table in mysql. Like lets say the "dates" column, i have info such as 05.05.2020, 01.05.2020. And i want to ADD 11.05.2020 to near of the 05.05.2020, and 01.05.2020. When i do that, it just erases this info and adds only 11.05.2020. But i want it to look like 05.05.2020, 01.05.2020,11.05.2020.
And the second thing which i dont know how to do, is how to match the users form input with the data within the mysql? Lets say in form it says Username:, Date:. Username puts 0001, and php takes that value and matches it with mysql username column. If it exists, it adds date to that specific users table.
Here is my code:
html:
<html>
<head>
<title>
</title>
</head>
<body>
<form action="process.php">
<center>
<label for="accnum">Username</label><br>
<br>
<input type="text" name="accnum" id="accnum"><br>
<br>
<label for="date">Date</label><br>
<input type="text" name="date" id="date"><br>
</body>
</html>
and my process.php
<?php
$link = mysqli_connect("localhost", "root", "123", "jbex");
if($link === false){
die("w. " . mysqli_connect_error());
}
$accnum = mysqli_real_escape_string($link, $_REQUEST['accnum']);
$date = mysqli_real_escape_string($link, $_REQUEST['date']);
$sql = "UPDATE accounts (date) VALUES ( '$date' WHERE $accnum=?)";
if(mysqli_query($link, $sql)){
echo "success.";
} else{
echo "ERROR: " . mysqli_error($link);
}
mysqli_close($link);
?>
What to put near WHERE "$accnum=" so it takes the users input with the form named accnum?
Thanks for reading and help
Your syntax for the MySQL UPDATE query also appears to be incorrect. Consult the documentation on UPDATE query syntax. Your query should probably look closer to this.
UPDATE accounts SET date = ? WHERE accnum = ?
It looks like you're overwriting the value of the date column with the value provided by the user, where you say you're wanting to instead add the value to your existing data for that user.
MySQL doesn't support list types, so you'd have to either store the dates using a different column type (e.g. varchar or text) or store the dates as rows in a separate table where each row in that table includes the primary key value for its respective user.
You should also be using a prepared statement with a bound parameter for the values of the date value you want to add and the accnum value for the record you want to add that value to.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am creating a webservice where I need to get some data from mysql and retrieve it in a mobile app.
I have been trying all day to do a query with a WHERE statement, but no success.
The normal query, without the WHERE is working perfectly though.
Also I went through all the similar questions on stack overflow and other forums, but none is the same problem as mine.
This is my current code:
<?php
$con=mysqli_connect("Hidden credentials");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($stmt = $con->prepare("SELECT
team.id as teamId,
team.team_name as teamName,
user.id as userId,
user.username as username,
team_members.role as role
FROM team_members
inner join user on team_members.user_id = user.id
inner join team on team_members.team_id = team.id
where user.id = ?
")) {
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
$stmt->close();
}
?>
If I remove the line where user.id=? it gets the data correctly.
Running the query on phpMyAdmin is everything ok, so it's not any issue on the query.
The variable $id doesn't exist (in your code). If you want to set the variable dynamically you can use $id = $_GET['id'];. This will take the value from the url and put it in the variable!
Your QUERY doesn't work because your variable id doesn't exists (in code what you showing).
Fix: create variable id and put some data to this variable.
For example:
$id = 5;
Or dynamcially:
From URL with GET method:
$id = $_GET['id'];
this allows you to get parameter from URL. But you must set this parameter by link. For example: <a href="index.php?id=5">. By clicking on this a tag you will be redirected to page index.php with parameter id which equals to 5.
From POST method:
for example you have this FORM:
<form method="post">
<input type="number" name="id">
<input type="submit" name="submit">
</form>
after submiting this FORM values will be saved in $_POST. You can access them by $_POST["name"]. In this case $_POST["id"].
$id = $_POST["id"];
From SESSION:
$id = $_SESSION["id"];
but first you have define $_SESSION["id"]. You can access this variable ($_SESSION["id"]) in other pages of your domain.
I've put certain values like a user id into the url e.g /index.php?id=1 in previous PHP files.
I have a HTML form that has an action like this:
<form name="staffResponse" method="post" action="respond_ticket.php?id=<?php echo $_GET['id']; ?>">
Which when you go to respond_ticket.php and simply echo the value for the id and look at the URL it does it successfully. Whats more the data that I am posting to that file is also done without problem. However I want to then write that information to a table but it does not seem to work.
Here is the respond_ticket.php file
<?php
include 'database/db.php';
$id = $_GET['id'];
$staffResponse = $_POST['staffResponse'];
$sql = "INSERT INTO tickets (staffResponse) VALUES ('$staffResponse') WHERE id='$id'";
$result = mysqli_query($connection, $sql);
if ($result === TRUE) {
echo '<p>Response ' . $staffResponse . ', has been added</p>';
}
else {
echo '<p class="warning">Unable to respond</p>';
}
?>
The db.php file has all the necessary information for connection to the database i.e name password etc. It also opens the question there too.
I keep just getting the warning message that I wrote.
you cant do an insert with a where modifier like this. change it to update ;)
UPDATE tickets SET staffResponse = '$staffResponse' WHERE id = '$id'
You are not supposed to use a WHERE clause with INSERT
$sql = "INSERT INTO tickets (staffResponse) VALUES ('$staffResponse')";
You may wish to set your tickets table up with auto increment so you dont need to insert an id if you haven't done that already.
use ON DUPLICATE UPDATE if it helps
INSERT INTO tickets (id,staffResponse) VALUES ('$id','$staffResponse')
ON DUPLICATE KEY UPDATE id=VALUES(id), staffResponse=VALUES(staffResponse)
I just updated this question.
I can't seem to update my database whenever I am putting variable $ecode on my WHERE condition. But when I echo this variable it always echoes its right value.
<?php
require 'sqlicon.php';
$q=$_GET['q'];
$ecode= $_GET['ecode'];
echo"".$ecode;
$result=$db->query("UPDATE offset_form SET Approved='".$q."' WHERE Employee_Code='".$ecode."'");
?>
this is the content of sqlicon.php:
<?php
$db=new mysqli('localhost','root','',dbuser'); //localhost,username,password, dbname
?>
This is where I am getting the date for $q and $ecode: Sorry if it haven't been in mysqli yet.
testingjava.php:
<html>
<title> Offset Requests </title>
<head><link rel="stylesheet" type="text/css" href="up.css"/></head>
<script>
function Approval() {
var name;
name=document.getElementById('ename').textContent;
if(document.form1.approval[0].checked true) {
alert(name);
window.location.href = "sqli.php?q=Yes" + "&ecode=" + name;
}
}
</script>
<body>
<form id="form1" name="form1" method="post" action="testingjava.php">
<?php
$conn = mysql_connect("localhost","root","");
if(!$conn)
echo ("Could not connect");
mysql_select_db("dbuser",$conn);
$query=mysql_query("Select * from offset_form where Approved=''");
while($fetch=mysql_fetch_array($query)) {
$ecode=$fetch['Employee_Code'];
//$_SESSION['ecode']=$ecode;
$ename=$fetch['Employee_Name'];
$epos=$fetch['Employee_Position'];
$edpt=$fetch['Employee_Department'];
$dleave=$fetch['Date_Leave'];
$dreturn=$fetch['Date_Return'];
$reason=$fetch['Offset_Reason'];
echo "".$ecode ."".$ename." ".$epos." ".$edpt." ".$dleave." ".$dreturn." ".$reason;
echo "<input type='radio' name='approval' onChange='Approval()'>Yes";
echo "<input type='radio' name='approval'>No";
echo "<input type='text' name='remarks' size='30'>";
echo"<hr id='br'></hr>";
echo"<input type='submit' value='Submit' name='send' onClick='Approval()'>";
}
?>
</form>
</body>
</html>
I am only testing to manipulate my database when I triggered a radio button.
1) you should be using mysql_real_escape_string($_GET[]) or someone with inject a mysql command into you system like DROP TABLE which will be the end of your database.
2)secondly I would move over to using PHP PDO it is more secure and it is faster (by a long way).
3) change your scond to last line from
mysql_query($sql,$conn);
to
mysql_query($sql,$conn) or die(mysql_error()." _____is the string correct? ".$sql);
then is should echo out any errors, if you post the echoed error we can probably fix it
having looked at it I am guessing the problem is you have missed the .. around the $q, so the $sql contains the string "$q" rather than the string assigned to the variable $q
try this
$sql="update offset_form set Approved ='".$q."' where Employee_Code='".$ecode."'");
try this way..
$sql=("update offset_form set Approved ='".$q."' where Employee_Code='".$ecode."'");
always try to echo your query and see what's going wrong with your query..
if password is set to your dbms the provide the third param passwrod
$conn = mysql_connect("localhost","root","<passwrod>");
or you can leave it blank if passwrod is not set.
and try this
$sql="update offset_form set Approved =$q where Employee_Code=$ecode";
or
$sql="update offset_form set Approved ='".$q."' where Employee_Code='".$ecode."'";
note: double quotes will parse the php variable ,
most probably there is problem in the manner of quotes you are using.
are you should your query is what you want?
One thing that is confusing is the fact that you have this commented out:
"INSERT INTO offset_form (Approved) VALUES ('".$ecode."')"
And then you have this as your update:
"UPDATE offset_form SET Approved = '$q' WHERE Employee_Code = '".$ecode."'"
The values you are using don't tally together. Surely you should have:
"UPDATE offset_form SET Approved = '$q' where Approved = '".$ecode."'"
This is because you are inserting $ecode into the column Approved, but then searching for $ecode in another column called Employee_Code. Perhaps you need to modify your insert statement instead? Either that or $ecode could be just representing two different values at different times?
quotes
The only way switching quotes will make a difference is if your embedded values contain quotes themselves. In which case using the correct escape function will sort the problem. So you are free to use either:
"UPDATE offset_form SET Approved = '$q' where Approved='$ecode'"
or:
"UPDATE offset_form SET Approved = '".$q."' where Approved = '".$ecode."'"
or:
'UPDATE offset_form SET Approved = "'.$q.'" where Approved = "'.$ecode.'"'
but not:
'UPDATE offset_form SET Approved = "$q" where Approved = "$ecode"'
either of the first three should not make a difference.
further things to do
backticks
As a rule I always write my queries escaping table and column names using backticks, just to make sure I'm not accidentally using a reserved word:
"UPDATE `offset_form` SET `Approved`='$q' WHERE `Employee_Code`='".$ecode."'"
double check your dataset
Make certain that the same query you are trying to run in PHP, works inside your dbms. This involves echoing the query out in PHP and then executing it via PHPMyAdmin, Navicat, or whatever you use to access your database outside of coding. For example, a query with hard-coded values, if this doesn't work you have a logic problem in your query or database design that has nothing to do with PHP:
"UPDATE offset_form SET Approved='13' WHERE Employee_Code='12'"
check your white space
Sometimes queries that seem they should be working are having problems because your column values contain accidental invisible white space. If so, they would only be selectable using something like:
"UPDATE offset_form SET Approved='$q' WHERE Employee_Code LIKE '%".$ecode."%'"
check user privileges
Make certain your MySQL user has the ability to perform the type of query you are attempting, this means allowing SELECT, INSERT and UPDATE queries.
disclaimer
As others have already stated, you should upgrade to non deprecated database access methods. If not, you should at least be using mysql_real_escape_string to better protect against malicious intent.
Please debug the value of $q and try to run this code:
session_start();
$q=$_GET['q'];
$ecode=$_GET['ecode'];
$conn = mysql_connect("localhost","root","");
if(!$conn)
echo ("Could not connect");
mysql_select_db("asiantech",$conn);
echo"".$ecode;
echo"<br>".$q;
$sql="update offset_form set Approved ='".mysql_real_escape_string($q)."' where Employee_Code='".$ecode."'";
//$sql = "INSERT INTO offset_form (Approved) VALUES ('".$ecode."')";
mysql_query($sql,$conn);
I have one form which need to submit data into two different tables in same DB.
at past time, i have asked how to submit form into two tables, but it impossible.
Then, I try to submit this form use two submit buttons with different destination.
Could you give some advise to submit this form after click them?
Javascript:
function button1click() {
yourForm.action = "ajax1.php";
yourForm.submit();
}
function button2click {
yourForm.action = "ajax2.php";
yourForm.submit();
}
HTML:
<form action='' method='post'>
<input type='input' id='blah' name='blee' />
<button type='button' onclick='button1click()'>Button 1</button>
<button type='button' onclick='button2click()'>Button 2</button>
</form>
why dear ?
if($_POST['submit'])
{
$sql1="insert into table 1";
mysql_query($sql1);
$sql2="insert into table 2";
mysql_query($sql2);
}
This should work..
one submit button only. OK!
You can do this many different ways. Just because the data is on one form, doesn't mean it has to go into one table. Basically you need to learn how to write some server side code that parses the incoming data and puts it where it needs to be.
So the simplest way is to just submit your form, and then on the server save the data to where it needs to go.
Having 2 buttons could be clunky, unless thats how it was designed...
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("MYDB") or die(mysql_error());
// Insert a row of information into the table "example"
$sql="INSERT INTO example
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());
// Insert a row of information into the table "example"
$sql=mysql_query("INSERT INTO example1
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());
?>
You can insert into different tables like this:
EDIT (new code):
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("double") or die(mysql_error());
// Insert a row of information into the table "example"
mysql_query("INSERT INTO example
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());
// Insert a row of information into the table "example"
mysql_query("INSERT INTO example1
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());
?>
Hope this answers you question because toy cant have double destination (i think) but this inserts into two different MySQL tables...
Good luck
To summarize what others have said above,
You could submit to two different locations, using javascript to change the action attribute of the form. You might wanna use it if the two destinations are not on the same server.
Or you could submit it to one destination only, massage your data, and then insert into two tables using php. It'll be particularly advantageous as you wouldn't need to sanitize or validate the data twice on server-side.
Very Very Simple...
You can insert in two tables by only one submit button..
Example:
<?php
if(isset($_POST['submit']))
{
$value1 = (!empty($_POST['form_name_value1']))?$_POST['form_name_value1']:null;
$value2 = (!empty($_POST['form_name_value2']))?$_POST['form_name_value2']:null;
$str = "INSERT INTO table_name1(db_value1, db_value2)VALUES('$value1','$value2')
$sql = mysql_query($str) or die(mysql_error());
$str1 = "INSERT INTO table_name2(db_value1, db_value2)VALUES('$value1','$value2')
$sql1 = mysql_query($str1) or die(mysql_error());
if($str)
{
echo "Successful";
}else{
echo "Unsuccessful";
}
if($str1)
{
echo "Successful";
}else{
echo "Unsuccessful";
}
}
This question was asked 4 years ago. Not the time to answer now I know. But
still answering to help others searching for the same problem.
Vote Up if you find this helpful. :D