Go to url based on mySQL query - php

Ok, so I'm making this website (kind of like bitly or goo.gl) where you enter a link and it shortens it, but with some extra goodies.
Right now I'm just hosting a local mysql server for testing, and the way it is setup, once a link is entered to shorten, a random 3 digit code is generated and put into the mysql table, along with its link.
When you enter the code on the site, it goes to the mysql table, finds the code, finds the corresponding link, and in theory is supposed to bring back that link, and then open it.
This is where the problem is. It simply does not work. I cannot figure out whether it is a problem with the html page, or with the scripting but I have no idea.
I'm not very experienced with PHP (language im using for query script) so I'm not sure how to go about troubleshooting.
I was hoping someone on here could offer some insight into why it may be not working.
All I know is when I click the "Go" button, it opens the php code rather than running it, and I'm not sure how to fix it.
Because of me not knowing exactly what the problem is, here is both the html and php code.
HTML:
(stripped down to just body for convenience. nothing interesting anywhere else)
<body>
<center><form action="sql_query.php" method="post">
<input class="enjoy-css" placeholder="" maxlength="3" name="var" type="text" />
<script type="text/javascript" script-name="josefin-sans" src="http://use.edgefonts.net/josefin-sans.js"></script>
<input type="submit" class="enjoy-css_1" value="Go" src="sql_query.php" />
<script type="text/javascript" script-name="josefin-sans" src="http://use.edgefonts.net/josefin-sans.js"></script>
</form></center>
PHP:
<?php
$servername = "localhost";
$username = "nimbleadmin";
$password = "admin";
$dbname = "nimble";
$var = $_POST['var'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysql_query("SELECT id, nimblecode, urlredirect, messageredirect FROM linker WHERE nimblecode = '" + $var + "'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo "id: " . $row["nimblecode"]. " //// URL: " . $row["urlredirect"]. " //// Message: " . $row["messageredirect"]. "<br>";
if ($row["messageredirect"]. == null) {
header('Location: ' . $row["urlredirect"]);
} else {
header('Location: http://nic.x10.mx/message?' . $row["nimblecode"]);
}
$conn->close();
?>
Any help is greatly appreciated! I know it's a bit of a interesting question, but I am still learning!

There is syntax error in your code, please use dot for concatentation in php and use mysqli object while querying instead of mysql.
$result = mysqli_query($conn, "SELECT id, nimblecode, urlredirect, messageredirect FROM linker WHERE nimblecode = '" . $var . "'");
Full Code changes: Store this file in the name as "tinyurl.php"
<?php
$servername = "localhost";
$username = "nimbleadmin";
$password = "admin";
$dbname = "nimble";
$var = $_GET['var'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query("SELECT id, nimblecode, urlredirect, messageredirect FROM linker WHERE nimblecode = '%s', $var);
if (!$result) {
echo 'Could not run query: ' . mysql_error(); exit;
}
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo "id: " . $row["nimblecode"]. "
//// URL: " . $row["urlredirect"]. "
//// Message: " . $row["messageredirect"]. "";
}
if ($row["messageredirect"] == "") {
header('Location: ' . $row["urlredirect"]);
} else if ($row["nimblecode"] != "") {
header('Location: http://nic.x10.mx/message?' . $row["nimblecode"]);
} else {
header('Location: http://nic.x10.mx/');
}
$conn->close();
?>
In .htaccess need to add this rule :
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/?$ http://nic.x10.mx/tinyurl.php?var=$1 [QSA,NC,L]
Sample URL entry
http://nic.x10.mx/abc
Will redirect to the target URL present in DB.

If you can't run php code then check if apache's httpd.conf file has PHP MIME type uncommented, besides there are other things to consider. Check this Apache shows php code instead of executing

Related

Getting Data values from database to save to session storage?

i want to make so my webpage takes values from a table in a database and displays them on the screen in the format that is shown below in the code, however i would then like to take the values for BikeID and ContactEmail and save them to session storage to be used on the update confirm page which your taken to when the update button is clicked. however the first issue is that the values wont save to the session storage and the second is that even if they did would the session get the correct value according to the Table/BikeID selected where the button is clicked. Image of the page layout after the code is run is below.
if anyone has any ideas i would be grateful.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$username="Username"; // change this to your database username
$password="Password"; // change this to your database password
$database="Database"; // change this to your database username
$conn = new mysqli('localhost', $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM tblBikeStolen, tblBike WHERE tblBike.BikeID=tblBikeStolen.BikeID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<div id='UpdateTable'><table><tr><td> User No: " . $row["User"] . "</td>
<td>Bike ID: " . $row["BikeID"]. "</td><td> Contact: " . $row["ContactEmail"] . "</td></tr><tr><td>
Reported Time: " . $row["ReportTime"] . "</td><td> Address: " . $row["Address"] . "</td><td> Bike
MPN: " . $row["BikeMPN"] . "</td></tr><tr><td> Bike Brand: " . $row["BikeBrand"] . "</td><td> Bike
Model: " . $row["BikeModel"] . "</td><td> Bike Type: " . $row["BikeType"] . "</td><tr><td>
Investigation Notes: " . $row["UpdateNotes"] . "</td></tr><tr><td> Status: " . $row["Status"] . "
</td></tr><tr><form><button class='btn btn-primary btnUpdateInvest' type='submit'
value='Update'formaction='ConfirmUpdate.php' onClick='UpdateFunctionDAO.php'>Update</button></form>
</tr></table></div>";
$BikeID = $row['BikeID'];
$_SESSION["BikeID"] = $BikeID;
$ContactEmail = $row['ContactEmail'];
$_SESSION["ContactEmail"] = $ContactEmail;
}
} else { echo "0 results"; }
$conn->close();
?>
I recommend starting simple and then expanding your use case:
Instead of using formaction = 'ConfirmUpdate.php', try using formaction = 'ConfirmUpdate.php?bikeid=<your-bike-id>&contactemail=<the-contact-email>'
In ConfirmUpdate.php, check if $_GET['bikeid'] and $_GET['contactemail'] are set and valid. If you didn't get either of those keys or if they were invalid, write a meaningful error message on the screening instructing the user what to do next.
If you received both those keys and their values were reasonable, you can store them in a session for future processing. Once your processing is done, clear out that information from the session.
Your PHP code will look something like this:
echo "...value='Update' formaction='ConfirmUpdate.php?bikeid=" . $row["BikeID"] . "&contactemail=" . $row["ContactEmail"] . "' onClick='UpdateFunctionDAO.php'>...";
Try this and see how it works. You might have to do more work after this to ensure that the data you are publishing on the page is sanitized and not susceptible to injection.
Example
Let's say your initial page is called test.php and it looks like this:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$username=""; // change this to your database username
$password=""; // change this to your database password
$database=""; // change this to your database username
$conn = new mysqli('localhost', $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "your sql query";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while ($row = $result->fetch_assoc())
{
$displayText = sprintf('<div>Some other info. Bike ID is %s and contact is %s.</div>',
$row['bikeid'],
$row['contactemail']
);
$form = sprintf('
<form method="post" action="ConfirmUpdate.php">
<input type="hidden" name="bikeid" value="%s">
<input type="hidden" name="contactemail" value="%s">
%s
<input type="submit" value="Submit">
</form>',
$row['bikeid'],
$row['contactemail'],
$displayText
);
echo $form;
}
}
$conn->close();
?>
Result
Your ConfirmUpdate.php will look like this:
<?php
session_start();
$_SESSION['bikeid'] = $_POST['bikeid'];
$_SESSION['contactemail'] = $_POST['contactemail'];
echo sprintf('Received bike id %s and contact email %s',
$_SESSION['bikeid'],
$_SESSION['contactemail']
);
?>
When you click on the first button, you will be taken to ConfirmUpdate page, which will look like this:
Received bike id 1 and contact email test#gmail.com
When you click the 2nd button, you will see:
Received bike id 2 and contact email test#yahoo.com
Test this out on your own systems and you should be able to replicate this code in your project.

php- How to record which user clicked on a link to download a file

I am trying to record which user has downloaded a file in an SQL database. Every file uploaded has its path displayed as a link on the site, allowing the user to download that file from a folder on the server. I am having trouble figuring out how to record which user has downloaded a file though. How can I query my database that a specific user has clicked a specific link? I have the user id stored as a session variable, so possessing the user id is not a problem. My code to display the downloadable files are as follows:
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "project_website1";
$user_id = $_SESSION[ 'user_id' ];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT task_id,file, description, title, deadline_claim FROM task";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>TITLE</th><th>DESCRIPTION</th><th>DEADLINE</th><th>TASK</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
//echo "<tr><td>" . $row["file"]. "</td><td>" . $row["title"]. "</td><td>" . $row["deadline_claim"]. "</td></tr>";
echo "<tr><td>".$row["title"]."</td><td>".$row["description"]."</td><td>".$row["deadline_claim"]."<td><a href='" .$row["file"]. "'>CLAIM</td></a>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
If you want it to be purely PHP, as suggested, just use the task_id of the row in your file table. Here is a basic example, noting I have reorganized some elements to help keep your script cleaner. Ideally you will want to keep the functions on a different page and include them when you want to use them. Keeps your script cleaner and more easily readable.:
# Better to make a function/class to do your database so you can reuse it easily.
function getConnection( $servername = "localhost", $username = "root",$password = "",$dbname = "project_website1")
{
# Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
# Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
# Make a task retrieval function/class that will deal with getting the rows only
function getTasks($con,$id=false)
{
$sql = "SELECT task_id,file, description, title, deadline_claim FROM task";
# I am assuming your task_id values are numeric, so I don't sanitize here
if ($id) {
if(is_numeric($id))
# Append sql
$sql .= " WHERE `task_id` = '{$id}'";
else
# You shouldn't get this exception unless someone is trying to
# Manually put something else here via injection attempt
throw new Exception("Id must be numeric!");
}
$result = $con->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$new[] = $row;
}
}
# Send back rows
return (!empty($new))? $new : array();
}
# This is more of a listener, but it will cut down on some redundant check-script
function getFileId()
{
if(!empty($_GET['file']) && is_numeric($_GET['file']))
return (!empty($_GET['action']) && $_GET['action'] == 'download')? $_GET['file'] : false;
return false;
}
# As noted, you would include the functions here...
session_start();
# Get session id
$user_id = $_SESSION[ 'user_id' ];
# Get the database connection
$conn = getConnection();
# If there is a download
if(!empty($_GET['action']) && $_GET['action'] == 'download') {
# Get the tasks, could be based on id or all
$tasks = getTasks($conn, getFileId());
# Save to the database, make sure that you either bind parameters, or
# check that the values are numeric (if they are supposed to be numeric)
# Also check the count here first for the task before inserting. Make an error if not.
# Usually means user is trying to manipulate the request
$conn->query("INSERT into downloads (`fileid`,`userid`) VALUES('".$tasks[0]['task_id']."','".$user_id."')");
# Download file. If you want to obfuscate the file, you would use
# download headers instead:
# http://php.net/manual/en/function.readfile.php
header('Location: '.$tasks[0]['file']);
# Stop execution
exit;
}
# Get all tasks
$tasks = getTasks($conn);
# If there are rows, output them
if (!empty($tasks)) {
echo "<table><tr><th>TITLE</th><th>DESCRIPTION</th><th>DEADLINE</th><th>TASK</th></tr>";
# output data of each row
foreach($tasks as $row) {
echo "<tr><td>".$row["title"]."</td><td>".$row["description"]."</td><td>".$row["deadline_claim"]."<td><a href='?action=download&file=" .$row["task_id"]. "'>CLAIM</td></a>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
Final note, I have not tested this, so be aware of that.
your header for calling script in html
<head>
<script laqnguage="javascript" src="myfunction.js" type="text/javascript"></script>
</head>
then in your while loop in php jump out of php
?>
<form name"myform" method="get" action="<? php echo $row["file"]; ?>">
<input type="button" name="name" Value"<? php echo $row["file"]; ?>" onClick="setinsertAction();" />
</form>
then jump into php again
<?php
now create a file called myfunction.js and put this inside
function setinsertAction() {
document.myform.action = "HERE PUT YOUR PHP FILE THAT WILL DO THE QUERY";
document.myform.submit()'
}
if all goes well it should the retrieve the file for download and executed your php script if the you replace your php file for the query in the .js file if it fails let me know

basic mysql data extraction using php

I've looked all over here. Please be patient as I am new to php and mysql.
I got WAMPP installed & seems to be working OK. I created a simple "test" database from phpMyAdmin and "firsttable" in that. I can do a simple connect using example from w3schools, but trying to select & display data I entered only throws back errors.
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Connect
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT reference, firstname, lastname, room FROM firsttable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["reference"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "room:" . $row["room"]. "<br>";
}
} else {
echo "0 results";
}
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
First off, I get a parse error on line 17. The one that reads:
if ($result->num_rows > 0) {
The error says: Trying to get property of non-object.
I tried wrapping the whole php code in tags and saving it as html, but then it appeared that no row data was ever found.
I am able to use very simple code that connects successfully. I can confirm the database is in there, so is the table, and the contents I added to it.
Please, what am I doing wrong?
You need to specify the database when you connect:
$database = 'test';
$conn = mysqli_connect($servername, $username, $password, $database);
where $database is the name of your database (test in this case). MySQL doesn't know which database your table resides in without you telling it.
In addition, you should always include error checking for your database connection (you have two of these, you don't need the last one) as well as any queries. Sans this, you can check your error logs for more information when something fails.

Make PHP run after form submitted without redirecting to another PHP page to process the data

I'm not sure if this is a duplicate question due to the fact that I'm not even sure how to properly form it (That's why the title of this question makes no real sense). I am beginning to learn PHP so I can utilize SQL databases in my webpages.
My question is, how would I be able to make it so a user types in a password into an input box, which is then used by a PHP script as the password to a MySQL login to display the contents of a table in an HTML table? Now, I have most of this figured out, the only problem is displaying the table on the same page which the password is entered and the submit button is hit. Would I need to use AJAX? Because I don't know the first thing about it. Here is what I have so far:
Index.php:
<DOCTYPE! html>
<html>
<head>
<title>Guy's Random Project</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="scripts.js"></script>
</head>
<body>
<div>
<form action="" method="POST">
<font size="4">Password: </font><input type="text" id="pass" name="pass"/><br>
<input class="buttonGreen" type="submit" value="Submit" id="1" onMouseDown="mouseDown(1)" onMouseOut="mouseUp(1)"/>
</form>
</div>
<table><thead><th>ID</th><th>Name</th><th>Type</th><th>Rating</th></thead><tbody>
<?php include 'getTableData.php'?>
</tbody></table>
</body>
</html>
getTableData.php:
<?php
$servername = "localhost";
$username = "root";
$password = $_POST['pass'];;
$dbname = "testing";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, type, rating FROM crap_food";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"] . "</td><td>" . $row["name"] . "</td><td>" . $row["type"] . "</td><td>" . $row["rating"] . "</td></tr>";
}
} else {
}
$conn->close();
?>
I understand the fact that PHP is run server side, and is only run before any HTML is read by the client, so making a function run when a button is hit wouldn't exactly be possible just using PHP and HTML, but this would be similar to what I'm looking for. I don't want to redirect the user to another page via the form action (Which is why it's blank), I want to keep this all within index.php. Thanks (And sorry for the horrible forming of this question, I'm just a bit confused).
You Use AJAX for this.
$.ajax({
url: 'xxx.php',
data:formData,
cache: false,
contentType:false,
processData:false,
type: 'post',
success: function(response)
{
//do something
}
try this :
$password =$_POST['pass'];
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username,$password);
$sql = 'SELECT firstname FROM users';
$q = $conn->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()):
echo ($r['firstname']);
echo "<tr><td>" . ($r['firstname']) . "</td></tr>";
endwhile;
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" .$pe->getMessage());
}
?>

PHP Instant messenger

I am trying to make a messenger using PHP and SQL
This is my code
<form action="send_post.php" method="post">
<h3>Name:</h3>
<input type="text" name="name">
<h3>Message:</h3>
<input type="text" name="message">
<input type="submit">
</form>
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, message FROM chat";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
while(1){
ob_start();
echo "" . $row["name"]. " - " . $row["message"]. "<br>";
sleep(10);
echo "" . $row["name"]. " - " . $row["message"]. "<br>";
ob_end_clean();
}
}
}
$conn->close();
?>
However this does not work, is there any reason for this?
The problems started once I added the infinite while loop to refresh the messages.
PHP works serversided, which means that the client(guest) requests a page that the server then "compiles" to then send to the client as a clientsided language such as HTML. If the PHP code never reaches an end/stop the client browser is going to think the server stopped responding and give an error.
To achieve what you are trying to do you might want to look into something like JQuery AJAX which allows for the client to fetch data from the server seperatly from the main request. That way you can have one file showing only the messages and request that file on a timer, while having the form as usual page load. You can however also make the form dynamic using JQuery AJAX
UPDATE You can look at this blogpost to get an idea of what I'm talking about.

Categories