I am basically building an extension that gets the url and title of the current tab and sends it to the SQL database at localhost using XAMPP.
This is my code
(popup.html)
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<script src="jquery-3.3.1.min">
</script>
<script src="popup.js">
</script>
</head>
<body>
<form action="http://localhost/data.php" method="post">
<var id="lol">kk</var>
First Name: <input type="text" name="name">
<input type="Submit">
</form>
</body>
</html>
(popup.js)
chrome.tabs.getSelected(null,function(tab) {
var tablink = tab.url;
var tabtitle = tab.title;
document.getElementById("lol").textContent=tablink;
document.getElementById("card").textContent=tabtitle;
});
(data.php)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "uppercase";
// Create connection
$conn = mysqli_connect("$servername", "$username", "$password");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
mysqli_select_db($conn,$database);
$sql = "INSERT INTO urltable (name,url)
VALUES
('$_POST[lol]','$_POST[card]')";
if (mysqli_query($conn, $sql)) {
echo("success");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
I want the url and title of current tab to be saved in database(uppercase).
Even though I have specified the ID for title and url i.e(card and lol respectivesly). Nothing is getting entered in Database if I run my extension.
You're only sending one variable, named name, with this form.
You can send lol and card values with hidden fields like this :
<input type="hidden" id="lol" name="lol" value="" />
<input type="hidden" id="card" name="card" value="" />
Remove tag with id lol : <var id="lol">kk</var>
This way you'll be setting lol and card values and sending related variable to PHP.
Related
I try to make a website where people will have option to upload some files(excel, pdf etc.) and images. When they refresh the page I want them to see those files and have an option to download them.
I tried to google this for a long time and I am still not able to make it work. I read about bytea or blob option tried both. I even read and thought about using server file system.
This is as the far I've got.
<?php
$db = new PDO("pgsql:host=localhost;port=5432;dbname=name;user=user;password=pass");
if (isset($_POST["insert"])) {
$target_file = $_FILES["file"]["tmp_name"];
$img = fopen($target_file, 'r');
$data = fread($img, filesize($target_file));
//$file = pg_escape_bytea($data);
//$file = pg_escape_bytea(addslashes(file_get_contents($_FILES["image"]["tmp_name"])));
$sql = 'INSERT INTO test (data) VALUES (?)';
$ISp_Res = $db->prepare($sql);
$ISp_Res->bindParam(1, $data, PDO::PARAM_LOB);
$ISp_Res->execute();
}
?>
<html>
<head>
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br/><br/>
<div class="container" style="width:500px;">
<h3 align="center"></h3>
<br/>
<form method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info"/>
</form>
<br/>
<br/>
<?php
$query = "SELECT * FROM test ORDER BY id DESC";
$db = new PDO("pgsql:host=localhost;port=5432;dbname=name;user=user;password=pass");
$result = $db->prepare($query);
$results = $result->execute();
$results = $result->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
ob_start();
fpassthru($row['data']);
$dat = ob_get_contents();
ob_end_clean();
//echo (base$row['data']);
//$dat = stream_get_contents($row['data']);
$dat = pg_unescape_bytea($dat);
//$dat = "data:image/png;base64," . base64_encode($dat);
//echo "<img src='" . $dat . "'";
echo '<a href="'.$dat .'" download>You can download here '.$row['id'].'</a><br>';
}
?>
</div>
</body>
</html>
Now I was able to display an image on my website but it was in terrible quality. When I tried to download it there was a problem with corruption or missing parts.
Then I tried to unescape bytea from postgresql and I've got different problem that I cant download it at all.
As you can see in comment lines I tried some different things even combine some of them.
PS: I am an amateur so any comment will be helpful.
Its my first post so I am sorry If I broke any rules here.
EDIT:
Table I am trying to upload files.
CREATE TABLE public.test
(
id integer NOT NULL,
data bytea,
CONSTRAINT test_pkey PRIMARY KEY (id)
)
My assignment is to create two tables in phpMyAdmin, and then to create a simple form where the user can click a button and have the two tables displayed. I have the landing page for the assignment finished with header and search bar and button, but I'm having trouble figuring out how to bring the two tables in from the database and display them once the button is clicked.
I have had a tutor help with some of the code but I haven't been able to get it to work properly and would love any further help.
Here is the code I have now (the two separate php code chunks are two ways people tried to help me do it but I don't know which works or how to implement it):
<!DOCTYPE html>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {die("Connection Failed: " . $conn->connect_error);
}
echo "Connected Successfully";
?>
<html>
<head>
</head>
<body>
<h1>Health Club Patron and Class Information</h1>
<form name="contact-form" action="" method="post" id="contact-form">
<div class="form-group">
<label for="Search">Search</label>
<input type="text" class="form-control" search="your_name" placeholder="Search" required>
</div>
<button type="print" class="btn btn-primary" name="print" value="Print" id="submit_form">Print</button>
</form>
</body>
</html>
$connection = mysql_connect('localhost', 'root', ''); //The Blank string is the password
mysql_select_db('hrmwaitrose');
$query = "SELECT * FROM employee"; //You don't need a ; like you do in SQL
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['age'] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
mysql_close(); //Make sure to close out the database connection
Try looking at examples on this website, good example's taken from W3 schools to learn with some simple examples.
https://www.w3schools.com/php/php_mysql_select.asp
And a form handling example in PHP https://www.w3schools.com/php/php_forms.asp
You setup a php file such as post.php then your form will post to that endpoint. Or if you are posting a PHP form to itself you use <?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> for the post address in the form. When learning, try taking these simpler like the example's below than building from that, so you get the basic idea.
Here's a few examples, this one just grabs the rows from the database.
<?php
$servername = "localhost"; // Server host
$username = "username"; // Database username
$password = "password"; // Database password
$dbname = "hrmwaitrose"; // Your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Select the rows name and age from employee
$sql = "SELECT name, age FROM employee";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo " - Name: " . $row["name"]. " " . $row["age"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Simple example post a form to PHP file a different URL, not posting to itself.
Filename: index.php
<html>
<body>
<form action="results.php" method="get">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit">
</form>
</body>
</html>
Then your results.php contains
Filename: results.php
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["age"]; ?>
</body>
</html>
This is an example using a form posting to itself, instead of the example's above which post to another file. Using $_GET["name"] you are grabbing the post variable's from the URL and then you can query your database, unless you are using _POST. If your posting directly to the same file you would do something like this, which I think your question is asking.
<?php if (!empty($_POST)): ?>
Welcome, <?php echo htmlspecialchars($_POST["name"]); ?>!<br>
Your age is <?php echo htmlspecialchars($_POST["age"]); ?>.<br>
<?php else: ?>
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit">
</form>
<?php endif; ?>
I am fairly new at PHP HTML and found some help on this site but cannot get the code to work as part of my script
On clicking the SUBMIT button a record is posted to the database table (Transactions) but the FIELD (Code) is empty, it should contain a 3 letter uppercase string e.g. ABC
The ALERT shows that the value is stored in the variable $code but an empty string is posted to the table
Your help is greatly appreciated by this novice
<?php
// Include config file
require_once 'config.php';
// Define variables and initialize with empty values
$code = "";
$code_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// Validate Code
$code = strtoupper($code);
// Check input errors before inserting in database
if(empty($code_err)){
// Prepare an insert statement
$sql = "INSERT INTO Transactions (Code)
VALUES (?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_code);
// Set parameters
$param_code = $code;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records created successfully. Redirect to landing page
$url = 'http://localhost:8888/portfolio/index.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($link);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Record</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<link href="style1.css" rel="stylesheet" type="text/css"/>
<style type="text/css">
.wrapper{
width: 450px;
margin: 0 auto;
}
</style>
<script>
function getValue(obj){
alert(obj.value);
$code=(obj.value);
**alert($code);**
}
</script>
<!--Display heading at top center of screen-->
<div>
<center><h3>Peter's Portfolio - Shares</h3></center>
</div> <!-- end of Div -->
</head>
<body style="background-color:#fcf8d9">
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-6">
<div class="page-header">
<h2>Create Transaction Record</h2>
</div>
<form class="form-horizontal" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<!-- ASX CODE -->
<div class="form-group">
<label for="name" class="control-label col-xs-6">ASX Code:</label>
<div class="col-xs-6">
<?php
$conn = new mysqli('localhost', 'root', 'root', 'Portfolio') or die ('Cannot connect to db');
$result = $conn->query("SELECT Code, Coy_Nm from Companies ORDER BY Code");
echo "<html>";
echo "<body>";
echo "<select Name='Code' ID='Code'onchange='getValue(this)'>";
while ($row = $result->fetch_assoc()) {
unset($Code, $Coy_Nm);
$Code = $row['Code'];
$Coy_Nm = $row['Coy_Nm'];
echo '<option value="'.$Code.'">'.$Coy_Nm.'</option>';
}
echo "</select>";
echo "<input type='hidden' value='submit'>";
//$code=$_POST['Code'];
//echo $code;
?>
</div>
</div>
<!--Submit and Cancel Buttons-->
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Javascript and PHP cannot simply communicate to each other live.
try this
function getValue(obj){
alert(obj);// check if obj has something in it before proceeding to "value"
alert(obj.value);
}
After require_once 'config.php',
Focus on the following line :
$code = "";
When you submit form and form action is self, this means that your post data will be sent to the same file and when the code is read from your file it makes $code empty every time. of course, an empty value will be sent to DB. move this line inside if condition or change this logic.
Whenever I click the submit button of my login, I'm taken to a blank page which has the texts "403 Forbidden", I feel that this may be due to the URL of my login page as it is "mywebsite.com8:8888/login/" and is hosted on a different port (I'm using Tornado web server).
HTML
<form method="POST">
<fieldset id="inputs">
<input name="username" id="username" required>
<input name="password" id="password" type="password" name="Password" placeholder="Password" required>
</fieldset>
<fieldset id="actions">
<input type="submit" id="submit" value="Log in" name="submit">
<label><input type="checkbox" checked="checked"> Keep me signed in</label>
</fieldset>
</form> <div id="container"></div>
PHP
<?php header('Access-Control-Allow-Origin: *'); ?>
<?php
if (isset($_POST['submit'])){
session_start();
error_reporting(0);
$username = $_POST['username'];
$password = md5($_POST['password']);
$connection = mysql_connect("localhost", "moot", "lmlkmklmklmkl"); // Establishing Connection with Server
$db = mysql_select_db("snamr", $connection); // Selecting Database from Server
$sql="SELECT * FROM accs WHERE name='$username' and password='$password'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
$check = mysql_query("SELECT active FROM accs WHERE name = '$username'");
while($rows=mysql_fetch_assoc($check)){
$active = $rows['active'];
}
// If result matched $myusername and $mypassword, table row must be 1 row
if($count!=1){
echo "Wrong Username or Password";
}
elseif ($active == 0) {
echo "Your account isn't active!";
}
else {
$_SESSION['username'] = $username;
}
$time = time();
$setLogged= mysql_query("UPDATE accs SET loginstatus = '$time' WHERE name = '$username'") or die(mysql_error());
}
}
?>
JAVASCRIPT WHICH LOADS THE PHP INTO HTML (good reasons for this)
<script type="text/javascript">
$(document).ready(function(){
$("#container").load('http://mywebsite.com/sname/signing.php');
});
</script>
The login form along with the PHP works with all other files on my default port but when I take the code to my files hosted on port 8888 things go wrong. Hence why I think the main issue may be in the domain.
Any solutions?
I have a script where when a user get verified he/she is brought to Home.php. At the moment Home.php doesn't do much. But in the bottom left hand corner I have a log out button. And as you know when the user clicks on this button he expects his session to be destroyed and for him to be redirected to a log in page. Unfortunately you can't make a click listener in php. I have browsed for an hour looking for a solution but I have not been able to find the right key word or something.
This is my code
EDIT: You only really have to read some code from Home.php the est is only if someoe wants to run the code if they are not sure of their answer
Index.php(Login Page)
<?php
session_start();
mysql_connect("localhost","root","") or die ("cannot");
mysql_select_db("virtualdiary") or die ("db");
if (isset ($_POST["Username"])&& isset($_POST["Password"]))
{
$Username = $_POST["Username"];
$Password = $_POST["Password"];
$_SESSION["username"] = $Username;
$DB_Check = " SELECT * from users Where username = '".$Username."' and password = '".$Password."' " ;
$result = mysql_query($DB_Check);
if(mysql_fetch_assoc($result) === false){
$error = "invalid username or password";
}else{
header( 'Location: Home.php' ) ;
}
}
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="Index.css"/>
<title>Login</title>
</head>
<body>
<div id="main">
<div class="messages">
<?php
if(isset($error))
echo $error; ?>
</div>
<form action="Index.php" method="post">
<h5>Diary Name:</h5>
<input name="Username" type="text"/>
<h5>Password:</h5>
<input name="Password" type="password"/>
</br>
</br>
</br>
<input name="login" type="submit"/>
</form>
<p>Click HERE to register.</p>
</div>
</body>
</html>
Home.php
<?php
session_start();
echo "Username = " . $_SESSION["username"] . " !";
mysql_connect("localhost","root","") or die ("cannot");
mysql_select_db("virtualdiary") or die ("db");
if (isset($_POST["entry"])){
$entry = $_POST["entry"];
$submission = "INSERT INTO `virtualdiary`.`entries` (`entry`) VALUES ('". $entry . "')";
mysql_query($submission);
}
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="Home.css"/>
<title>Home</title>
</head>
<body>
<h1>Entry: </h1>
<form method="post" action="Home.php">
<textarea name="entry" rows="24" cols="87">
<?php
if (isset($_POST["entry"])){
echo $entry;
}
?>
</textarea>
</br>
</br>
<input name="submit" type="submit"/>
</form>
<button id="LogOut">Log Out</button>
</body>
</html>
From what I have found from searching around I will need a Home.js file with an ajax call. I don't know the first thing about Ajax so I will probably need code to paste or a very blunt tutorial.
Thanks
You could change the logout href to /Logout.php, and in Logout.php have
<?php
session_start();
session_destroy();
header('Location: /Index.php');
?>
That will simply destroy the users current session, then redirect the user back to the Index.php page.
The AJAX way would be (using jQuery, I can't remember the vanilla JS syntax for ajax calls)
$.ajax({
type: 'GET',
url: '/Logout.php',
success: function(msg) {
if (msg == 'loggedOut') {
window.location.href = 'Index.php';
}
}
});
And then you'd need to change Logout.php, instead of the header line, make it echo/die/print loggedOut (or a json string which would probably be better, but this is just an example).