i think im missing some post variables in this code. I'm not exactly sure how to place the post variables and link them to the controller in order to get submission forms going. I've read hours and hours and my minds still fuzzy on the concept. Now with this php controller, i can manually enter in data, but automatically uploading it via form is confusing me. I think im making it overly complicated and i know its just 1 or 2 steps from being completed. My mysql server is behind my lan, so the only thing that is publically accessable is my port 80 website. I hope i can get this resolved, its been murder on my brain lately lol
If i can't figure it out, ill just migrate it over to web2py. its more confusing but easier on the database front from what i've seen in organization of syntax. One last problem. The database isn't automatically creating new ID rows. I have it set to primary in the database and should automatically create new records, but for some reason it doesn't.
<form action="SubmissionForm.php" method="post">
<label>Name:</label><input type='text' name='user'/>
<label>Message:</label><input type='text' name='message'>
<input type='submit' value='Submit'>
</form>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = "INSERT INTO testmessage2 ". "(user, message) ". "VALUES(user, message);
mysql_select_db('politicalagenda');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
//captured the form data in variable
$user= mysql_real_escape_string($_POST['user']);
$message= mysql_real_escape_string($_POST['message']);
$sql = "INSERT INTO testmessage2 (user, message) VALUES('$user','$message')";
Related
Problem:
I want to get the MAX "SID" from my Database and add one. I handle the input via an Form that i submit through the HTTP Post Method. I get the current MAX "SID" from my database, then i put the value into an HTML input field and add one. For some reason this just works every other time. So the output i get is:
Try = 1
Try = 1
Try = 2
Try = 2
and so on. Would be nice if someone could point me in the right direction.
PHP get MAX(ID):
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "soccer";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "SELECT MAX(SID) FROM spieler";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$lastID = $row["MAX(SID)"];
}
}
mysqli_close($conn);
PHP insert in database:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "soccer";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?><br><?php
$sql = "INSERT INTO spieler VALUES ('$sid', '$name', '$verein',
'$position', '$einsaetze', '$startelf', '$tore',
'$torschuesse', '$eigentore', '$vorlagen', '$elfmeter',
'$verwandelt', '$gegentore', '$gelb',
'$rot', '$fouls', '$zweikampf', '$pass', '$note')";
if(mysqli_query($conn, $sql)){
echo "Success";
}else{
echo "Failed" . mysqli_error($conn);
}
mysqli_close($conn);
HTML & PHP Input Field:
<tr>
<td><input id="SID" name="SID" readonly value="<?php echo $lastID += 1;
?>"></td>
</tr>
Screenshot of the page:
The paragraph "Spieler ID:" is where I put the "SID" so that everytime the page loads the next free ID gets automatically loaded into the input field.
I want to get the MAX "SID" from my Database and add one
No. You don't. You really, really don't.
This is the XY Problem.
You can do it by running a system wide lock and a autonomous transaction. It would be a bit safer and a lot more efficient to maintain the last assigned value (or the next) as a state variable in a table rather than polling the assigned values. But this still ignores the fact that you going to great efforts to assign rules to what is a surrogate identifier and hence contains no meaningful data. It also massively limits the capacity and poses significant risks of both accidental and deliberate denial of service.
To further compound the error here, MySQL provides a mechanism to avoid all this pain out of the box using auto-increment ids.
While someone might argue that these are not portable, hence there may be merit in pursuing another solution, that clearly does not apply here, where your code has no other abstraction from the underlying DBMS.
//--------------------------------------------------------------------------
// php script for adding data from mysql database
//--------------------------------------------------------------------------
$ip = $_GET['ip']; //for debugging sake, will be POST from Ajax
$key = substr(md5(microtime()),rand(0,26),5); //random referral ID - will implement exist analysis
echo $ip; //debugging
$dbhost = 'localhost';
$dbuser = user;
$dbpass = 'pass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $conn);
$tbl_name = "refs";
$sql="INSERT INTO $tbl_name(ip, key)VALUES('frfr', 'grgr')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "1 record added";
I'm not sure if it's my Digital Ocean server or what, but the only syntax my PhpMyAdmin will accept as a query is as INSERT INTOrefs(ip,key) VALUES ("insert","432")
with the double quoted values. I cannot seem to get this implemented in the PHP without getting a flat out error or an Unknown column in 'field list' error.
Similar questions suggest junk non-printable characters from copy-paste, however I've retyped my code within the editor. Thanks for all the help
I'm creating a basic referral system by the way, storing requested IP's in 'refs' table with a key, or id.
key is a reserve word and thus needs to be escaped using backtique. Along with that you have spacing issue as well. Your query should looks like below
INSERT INTO refs(ip,`key`) VALUES ('insert','432')
Never use a reserve word as column or table name. if in doubt, then escape all the columns present in query.
Start referring MySQL Documentation for more inforamtion. It's way easier than posting it as question in stackoverflow.
I have this form:
<form action="contactus.php" method="post">
<select name="formTitle">
<option value="">Select...</option>
<option value="M">Mr</option>
<option value="F">Mrs</option>
</select>
<p><b>Name</b></p>
<input type="text" name="formName" maxlength="50"/>
<p><b>Enquiry</b></p>
<input type="text" name="formEnquiry" maxlength="500"/>
</select>
<p><input type="submit" name="formSubmit" value="Submit"/></p>
And I have a MySQL database (called 'contacts') with a table (called 'enquiries') with three columns; 'Title', 'Name', 'Enquiry'.
The database has no password or anything. It's just a localhost with a 'root' password.
What kind of PHP would I need to send the data from this HTML form to the MySQL database?
I can help you in this problem.
So, just add the following code to your php file contactus.php.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "contacts";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['formSubmit'])) {
$formTitle = $_POST['formTitle'];
$formName = $_POST['formName'];
$formEnquiry = $_POST['formEnquiry'];
$sql = "INSERT INTO enquiries (Title, Name, Enquiry) VALUES ('$formTitle', '$formName', '$formEnquiry')";
$conn->query($sql);
?>
I hope this will solve your problem.
SIMPLE ANSWER: MySQL
A LITTLE BIT MORE DEVELOPED ANSWER:
MySQL is in basic terms the combination of PHP and SQL to create an easy way to do various actions to a database, which include:
Create table
Query table
Update table
and much more
There are variations of MySQL, including MySQLi and MySQL (PDO).
an example of connecting to your database via MySQL (PDO) would be:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$myDB = "databasename";
try {
$conn = new PDO("mysql:host=$servername;dbname=$myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
//insert code there that you want to execute...
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
you mentioned that you don't have a password, so you might just leave the "password" slot empty ("") I suppose, though this is very insecure and I recommend you place a password.
In the code above, there is a comment that says:
//insert code there that you want to execute...
Here you would include code that would probably do actions similar to the ones mentioned above (query table, update table, etc). An example of code similar to that would be:
//htmlspecialchars takes out special characters that might
//exist in the posted information if someone were trying
//to hack your site via sql injection
$formTitle = htmlspecialchars($_POST['formTitle']);
$formName = htmlspecialchars($_POST['formName']);
$formEnquiry = htmlspecialchars($_POST['formEnquiry']);
$sql = "INSERT INTO enquiries (Title, Name, Enquiry) VALUES (formTitleBinded, formNameBinded, formEnquiryBinded)";
$sqlPrepared = $conn->prepare($sql);
$sqlPrepared->bindParam(':formTitleBinded',$formTitle);
$sqlPrepared->bindParam(':formNameBinded',$formName);
$sqlPrepared->bindParam('formEnquiryBinded',$formEnquiry);
$sqlPrepared->execute();
The previous code both sanitizes your input and inserts a row into your table with that information.
Let me know if that helped!
EDITED: My answer has been edited with parameter binding included to prevent SQL Injection.
I am using this PHP script to return search input values with corresponding URL values on a MySQL database/table. The idea is to append them to a redirect to automatically jump to that page.
<?php
$searchResults = $_POST['search'];
$dbhost = 'localhost';
$dbuser = 'admin';
$dbpass = 'pwd';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = "SELECT url
FROM Table_1
WHERE input = '" .$searchResults."'";
mysql_select_db('database_1');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$redirect = $row['url'];
header('Location:'.$redirect);
}
To catch any input that does not match a value on Table_1 added this If statement. It will take any non relevant or misspelled inputs and redirect them to xyz.html
if (mysql_num_rows($retval) < 1) {
header('Location: xyz.html');
}
Is this incorrect? It seems to be working but I assume there must be a cleaner way of doing this/ it may be bad practice.
If you are expecting only one result from the query then it would work.
But if there are multiple rows then the last row would be loaded . It would be inefficient then.
You could also directly do this:
if($retval)
{ .$row = mysql_fetch_array($retval, MYSQL_ASSOC);
header('Location:'.$row);
}
else
header('Location:xyz.html');
You wouldn't need to use the while loop if you are expecting only one row.
The way you use is wrong, it may cause lots of headache.
2 ways :
1.If result is x then redirect to page A.
2.If result is x then load view just similar like page A with same header ,footer.
So , as per 2nd way ,when the query is empty , Load specific view which you want.
For your example , suppose you visit a Shopping cart Site, you clicked on Shoes category , if there is no shoes, the page shows message Sorry stock is empty, no shoes, it does not redirect you to any page if stock if empty.
I'm quite new to PHP and Javascript. I am trying to get a variable from a google maps API marker with an option to delete the marker and its information from a MySQL database. No errors are being generated, however the row is not being deleted. I suppose that the problem is with the POST. Below is the code I have related to this matter:
var html = "<b>" + name + "</b> <br/>" + location + "<br/> <br/> <input type='button' value='Get Directions from your Current Position' onclick=getDirections()/> <br> <input type='button' name = 'remove' value='Remove Pointer' onclick=removePointer("+name+")/>";
That is the line where I am calling the removePointer function, passing 'name' as a parameter
function removePointer(name){
var nameSend = name;
$.post("index.php", {variableName: nameSend});
<?php
$mysql_host = "xxxx";
$mysql_database = "xxxx";
$mysql_user = "xxxx";
$mysql_password = "xxxx";
$link = mysql_connect($mysql_host, $mysql_user, $mysql_password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($mysql_database) or die(mysql_error());
$removeName = $_POST['variableName'];
mysql_query(("DELETE FROM markers WHERE Name='" . $removeName . "'"),$link) or die ("Markers Table Error: " . mysql_error());
?>
}
That is the removePointer function, where it should get the javascript variable, post it, and a PHP block to get the post and remove the MySQL row accordingly.
Thanks in advance for any help!
In your case, Javascript is something that will run in the user's browser while PHP is something that will run on the server (which will need to be able to talk to the database server). That is, you cannot embed PHP inside of a Javascript function and expect the PHP to be run - web browsers do not execute PHP. Further, you NEVER want to put any sensitive information into Javascript that will be running in a browser (such as MySQL credentials), because it will be visible to anyone who loads that Javascript.
You will need to create a server-side PHP script that Javascript will communicate with. Javascript could make an AJAX request to the PHP script, POSTing the data you wish the PHP to take action on. In this case, the removePointer() function could post the marker name to the PHP script, which would then remove it from the database.
To make life easier, you might consider using a Javascript library such as jQuery, which can greatly simplify making Ajax requests.
you cannot post just to your index.php page. create a new one "del.php", put your php code there, and post to that page:
index.php
function removePointer(name){
var nameSend = name;
$.post("del.php", {variableName: nameSend});
}
del.php
<?php
$mysql_host = "xxxx";
$mysql_database = "xxxx";
$mysql_user = "xxxx";
$mysql_password = "xxxx";
$link = mysql_connect($mysql_host, $mysql_user, $mysql_password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($mysql_database) or die(mysql_error());
$removeName = $_POST['variableName'];
mysql_query(("DELETE FROM markers WHERE Name='" . $removeName . "'"),$link) or die ("Markers Table Error: " . mysql_error());
?>
of course im no php-expert, and that is for sure not the optimal way to do ajax requests, but i hope you understand the concept of ajax a little bit better know...