Submit variable in URL to MySQL Database - php

I would like to have a page that, when someone clicks a pre-formatted link I've sent, writes a variable in the URL to a MySQL database and just displays "Thank You" or something to the user.
Example:
The user would click a link formatted something like http://www.example.com/click.php?id=12345
When the page loads the 12345 would be written to a table in a MySQL database, it would show a Thank you, and that is it.
Seems like it should be simple enough but I can't find anything on it. I'm probably searching wrong, since this is all new to me.

Your best bet is to utilise $_GET['id'] which will take in the value from your url.
After grabbing the id from your url you will want to use PDO or mysqli prepared statements in order to protect yourself from sql injection.
I hope this helps.
Updated as per Kevin Voorn's comment.
if(isset($_GET['id']) && !empty($_GET['id'])) {
$logged_id = $_GET['id'];
$stmt = $mysqli->prepare("INSERT INTO tableName (`logged_id`) VALUES (?)");
$stmt->bind_param('i', $logged_id);
$stmt->execute();
if($stmt->affected_rows > 0){
echo "Thank You.";
}
$stmt->close();
}

User $_GET to retrive the value and put into your table.
Example:
code inside click.php
<?php
$id=$_GET['id'];
$sql="Insert into table1 VALUES ($id)";
mysqli_query($connect,$sql);
echo "<script>alert('Thank you')</script>";
?>

Thanks for the responses. I ended up finding this page: https://www.binpress.com/tutorial/using-php-with-mysql-the-right-way/17 that described the process for using mysqli to connect to my database. I used that page to create the necessary functions in ../db.php and included it in the actual PHP script that would catch the url. My script ended up looking like this:
<?php
require '../db.php';
date_default_timezone_set('UTC');
$date = date("Y-m-d H:i:s T");
$db = new Db();
$db_id = $db -> quote($_GET['id']);
$db_date = $db -> quote($date);
$result = $db -> query("INSERT INTO `table` (`id`,`GUID`,`AccessTime`) VALUES (NULL, " . $db_id . "," . $db_date . ")");
if($result === false) {
exit();
} else {
echo "<html><body><center><br><h1>Thank You!</h1></center></body></html>";
}
?>

Related

Fetch data into table using PDO result in no value

I have a problem. I want to fetch all the tasks related to the user into a table. However, the result is '0 results'. I did try to echo print_r($allTask), and the result is Array() 1. I don't know what is the problem because, in the incomplete database, there are several tasks, but nothing shows up when I fetch it. Can someone explain it to me? Thank you for your help
Note: I put the fetch query inside the if(isset($_POST['submit']) because I want every time the user adds the new task and click submit. The incomplete database will be updated as well to display the new task added to the table
<?php
session_start();
require 'connect.php';
if (isset($_POST['submit'])) {
$owner = $_SESSION['name'];
$title=$_POST['title'];
$description=$_POST['description'];
$due_date=$_POST['due_date'];
$time=$_POST['time'];
$state=0;
$insertQuery="INSERT INTO incomplete (owner, title, description, due_date, time, state)
VALUES (:owner, :title, :description, :due_date, :time, :state)";
$preparedInsertStatement = $conn->prepare($insertQuery);
$preparedInsertStatement->bindValue(':owner', $owner);
$preparedInsertStatement->bindValue(':title', $title);
$preparedInsertStatement->bindValue(':description', $description);
$preparedInsertStatement->bindValue(':due_date', $due_date);
$preparedInsertStatement->bindValue(':time', $time);
$preparedInsertStatement->bindValue(':state', $state);
$valueInsert=$preparedInsertStatement->execute();
if($valueInsert){
echo 'Insert is done';
}
else{
echo 'Insert is not successful';
}
$displayQuery="SELECT * FROM incomplete where owner=':owner'";
$displayTask= $conn->prepare($displayQuery);
$displayTask->bindValue(':owner', $owner);
$displayTask->execute();
$allTask=$displayTask->fetchAll();
echo print_r($allTask);
if(count($allTask) > 0)
{
echo "<table border=\"1\"><tr><th>ID</th><th>Title</th><th>Description</th><th>Due
Date</th><th>Time</th></tr>";
foreach ($allTask as $row) {
echo "<tr><td>".$row["id"]."</td><td>".$row["title"]."</td><td>".$row["description"]."</td><td>".$row["due_date"]."</td><td>".$row["time"]."</td></tr>";
}
}else{
echo '0 results';
}
}
?>
When using placeholder values be absolutely sure you haven't introduced any additional syntax. I can see owner=':owner' which is incorrect. The placeholder should not have quotes around it.
This should be:
'... owner=:owner'
PDO takes care of escaping. The quotes are just in the way.

How do i use AJAX to update my page after running a PHP function?

So i'm trying to make some text appear on my web page after a user clicks a button and runs a mysql function, but my AJAX function is only running the mysql function without doing anything else, i'm a little confused on what exactly i'm supposed to write to get it to update my page.
AJAX:
<script>$(document).ready(function(){
var game = 69;
var review = 21;
$('#fav').click(function(){
$(document).load('core/like.php', {
thegame: game,
thereview: review
});
});
});</script>"
PHP (core/like.php)
<?php
session_start();
if (isset($_SESSION['username'])) {
require 'connect.php';
$thegame = $_POST['thegame'];
$thereview = $_POST['thereview'];
$username = $_SESSION['username'];
$datentime = date("m/d/Y h:i:s a");
$stmt = $conn->prepare("UPDATE reviews SET likes=likes+1 WHERE r_id='$thereview'");
$stmt2 = $conn->prepare("INSERT INTO likes (l_id, username, r_id, date) VALUES (NULL, '$username', '$thereview', '$datentime')");
$stmt->execute();
$stmt2->execute();
$stmt->close();
$stmt2->close();
$conn->close();
echo "<div id="content"><h1>THIS IS A TEST</h1></div>";
exit();
} else {
echo "<h1>ERROR</h1>";
}
?>
Also, it only runs the mysql query when i use "document" as the jQuery selector. If i try and use a specific div like $(#abox).load('core/like.php'.. it does nothing. If i try to add a selector at the end to specify what content from the php file i want to return like $(document).load('core/like.php #content'.., it also does nothing.
It seems that there are two problems:
There are nested double quotes in the PHP:
echo "<div id="content"><h1>THIS IS A TEST</h1></div>";
Use single quotes for the outer ones:
echo '<div id="content"><h1>THIS IS A TEST</h1></div>';
Use quotes around the jQuery selector:
$(#abox).load('core/like.php'...
Like this:
$("#abox").load('core/like.php'...
Also, please take serious note of the comment about SQL injection.

SQL database not inserting data?

I am working on a program that takes HTML code made by a WYSIWYG editor and inserting it into a database, then redirecting the user to the completed page, which reads the code off the database. I can manually enter code in phpmyadmin and it works but in PHP code it will not overwrite the entry in the code column for the ID specified. I have provided the PHP code to help you help me. The PHP is not giving me any parse errors. What is incorrect with the following code?
<?php
//POST VARIABLES------------------------------------------------------------------------
//$rawcode = $_POST[ 'editor1' ];
//$code = mysqli_real_escape_string($rawcode);
$code = 'GOOD';
$id = "1";
echo "$code";
//SQL VARIABLES-------------------------------------------------------------------------
$database = mysqli_connect("localhost" , "root" , "password" , "database");
//INSERT QUERY DATA HERE----------------------------------------------------------------
$queryw = "INSERT INTO users (code) VALUES('$code') WHERE ID = '" . $id . "'";
mysqli_query($queryw, $database);
//REDIRECT TO LOGIN PAGE----------------------------------------------------------------
echo "<script type='text/javascript'>\n";
echo "window.location = 'http://url.com/users/" . $id . "/default.htm';\n";
echo "</script>";
?>
Your problem is that mysql INSERT does not support WHERE. Change the query to:
INSERT INTO users (code) VALUES ('$code')
Then to update a record, use
UPDATE users SET code = '$code' WHERE id = $id
Of course, properly prepare the statements.
Additionally, mysqli_query requires the first parameter to be the connection and second to be the string. You have it reversed. See here:
http://php.net/manual/en/mysqli.query.php
It should also be noted that this kind of procedure should be run before the output to the browser. If so, you can just use PHP's header to relocate instead of this js workaround. However, this method will still work as you want. It is just likely to be considered cleaner if queries and relocation is done at the beginning of the script.

Create a unique page for each project page

I'm building a simple bug tracking tool.
After you logged in you can create a new project, when you've created a new project you get redirected to the project page.
My question is, how can I give every project a unique page?
I know I only have to create 1 page (projectpage.php) and then create a unique page for each project. I have to get the id from each project.
After you fill in a form to create a new project, that form will post to this page:
project.class.php
$name = $_POST['name'];
$descr = $_POST['description'];
$leader = $_POST['leader'];
$email = $_POST['email'];
$sql="INSERT INTO projects (name, description, leader, email, registration_date)
VALUES ('$name', '$descr', '$leader', '$email', NOW())";
$result = mysql_query($sql);
if($result){
header('Location: ../projectpage.php');
}
else {
echo "Oops, there is something wrong. Try again later.";
}
mysql_close();
This will store the data in the MySQL database.
So, how can I make a unique page for each project?
What's the best way to do this?
Thanks in advance!
You have one PHP file, take a project id through the query string (or some other part of the URL) and query the database for the data associated with that id. Then you generate the HTML for the project page using that data.
First, mysql_* functions are obsolete, you should use PDO...
You should have a PHP script that gets a project from the database by its ID. You probably should have an ID column in your table. Here is a sample code :
if($result){
header('Location: ../project.php?id='.mysql_insert_id());
}
mysql_insert_id returns the last inserted id. See the documentation.
Then, project.php :
<?php
if (!isset($_GET['id']) || empty($_GET['id']) {
echo "error : bad url";
exit();
}
$cn = new PDO(...); // Check PDO documentation for this
$sql = "SELECT * FROM projects WHERE project_id = :id";
$stmt = $cn->prepare($sql);
$stmt->bindParam(":id", $_GET['id']);
$stmt->execute();
$project = $stmt->fetch(PDO::FETCH_OBJ);
// $project will behave like an Object, you can display for example the project name
echo $project->name;
// or the project date...
echo $project->registration_date;

Having problems going from mysqli_query to mysqli_prepare

I'm new to PHP and made a simple php site that allows me to submit a form and delete data stored in a database. I was told it was better to use prepared statements to avoid SQL Injection.
I updated my delete and it still works, not sure if it's totally right:
<?php
include("dbconnect.php");
$getid = $_GET["id"];
$delete = mysqli_prepare($database,"DELETE FROM contacts WHERE id IN ($getid)");
mysqli_stmt_execute($delete);
header("Location:http://localhost/address-book");
exit;
?>
But I can't seem to get the add to database feature to work. I tried a variety of different ways to write it, but I'm sure that I'm missing something simple. Here's the unsafe code that I originally wrote:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
include("inc/dbconnect.php");
// assigns form data to table columns
$assign = "INSERT INTO contacts(firstName,lastName,email,phone,birthday) VALUES ('$_POST[firstName]','$_POST[lastName]','$_POST[email]','$_POST[phone]','$_POST[birthday]')";
//execute query
if (mysqli_query($database,$assign)) {
header("Location:http://localhost/address-book/");
exit;
} else {
exit;
}
?>
If someone could guide me in the right direction I'd be thankful. I'm new to all of this.
UPDATED: I've updated my original code and came up with this instead for delete:
<?php
include("dbconnect.php");
$getid = $_GET["id"];
$delete = mysqli_prepare($database,"DELETE FROM contacts WHERE id IN (?)");
mysqli_stmt_bind_param($delete, 's', $getid);
mysqli_stmt_execute($delete);
header("Location:http://localhost/address-book");
exit;
?>
and the add feature:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
include("inc/dbconnect.php");
$firstName = "$_POST[firstName]";
$lastName = "$_POST[lastName]";
$email = "$_POST[email]";
$phone = "$_POST[phone]";
// assigns form data to table columns
$assign = mysqli_prepare($database,"INSERT INTO contacts(firstName,lastName,email,phone) VALUES (?,?,?,?)");
mysqli_stmt_bind_param($assign, 'ssss', $firstName, $lastName, $email, $phone);
mysqli_stmt_execute($assign);
exit;
}
?>
A simple Prepare statement is something along the lines of
$query = $this->db->prepare("Query here WHERE something = ?") - note this example is taken from my site so you'll likely have something else instead of $this->->prepare.
The key thing is that the "= something " is denoted as a question mark.
You then bind the value of that question mark to the query
$query->bindValue(1, passed in parameter)
As a fully working example:
//function to add 1 to downloads each time a file is downloaded
public function addToDownload($filename){
$query = $this->db->prepare('UPDATE trainingMaterial SET downloads = downloads + 1 WHERE filename = ?');
$query->bindValue(1, $filename);
try{
$query->execute();
}catch(PDOException $e){
die($e->getMessage());
}
}
Your query `$assign = "INSERT INTO contacts(firstName,lastName,email,phone,birthday) VALUES ('$_POST[firstName]','$_POST[lastName]','$_POST[email]','$_POST[phone]','$_POST[birthday]')";
would be
$assign = "INSERT INTO contacts(firstName,lastName,email,phone,birthday) VALUES ?,?,?,?,?)";
$assign->bindValue(1, '$_POST[firstName]')
$assign->bindValue(2, '$_POST[lastName]')
etc etc

Categories