prepare($sql) function not working on one script - php

I'm working on a school project involving a website with database integration. Currently working on adding new content (text, titles, images) to the website through it. I can already add new users to the database through the website, but for some reason the same code and logic doesn't apply for the content.
I noticed that printing $stmt with echo does not print anything.
<?php
include "../conn.php";
$sql = "INSERT INTO `contenido` (`id_contenido`, `tipo_contenido`, `id_seccion`, `orden_contenido`, `largo_contenido`, 'corto_contenido', 'extra_contenido') VALUES (NULL, '".$_POST["tipo"]."', '".$_GET['id']."','".$_POST["orden"]."','".$_POST["largo"]."','".$_POST["corto"]."','".$_POST["extra"]."')";
$stmt = $conn->prepare($sql);
if ($stmt = $conn->prepare($sql))
{
//echo "It worked";
$stmt->execute();
$last_id = $conn->insert_id;
header("Location: editarContenidos.php?id=".$_GET['id']);
}
?>
Expected Results: The content information is uploaded to the database and the user is redirected to the Edit Contents page (editarContenidos.php)
Actual Results: White screen, no errors. Since the if condition is false, you are never redirected and the content is not uploaded to the database.
NOTE: The Insert User .php is working with the same logic and syntax, I'm not experienced enough with php to understand what I'm doing wrong.

I am assuming id_contenido is an auto_increment field and I'm not sure houw the backticks work in various languages. I would recommend adding some error handling PDO::errorInfo
and changing the SQL code to:
$sql = "INSERT INTO contenido (tipo_contenido, id_seccion, orden_contenido, largo_contenido, corto_contenido, extra_contenido) VALUES ('".$_POST["tipo"]."', '".$_GET['id']."','".$_POST["orden"]."','".$_POST["largo"]."','".$_POST["corto"]."','".$_POST["extra"]."')";
There is a $_GET['id'] in the SQL code and I cant tell if that is intentional.
I would recommend using parameters and some debugging using print_r($_POST);.
Try the following code:
<?php
include "../conn.php";
$sql = "INSERT INTO contenido (id_contenido, tipo_contenido, id_seccion, orden_contenido, largo_contenido, corto_contenido, extra_contenido) VALUES (?,?,?,?,?,?)";
$stmt = $conn->prepare($sql);
if ($stmt))
{
//echo "It worked";
$stmt->execute(array($_POST["tipo"], $_GET['id'],$_POST["orden"],$_POST["largo"],$_POST["corto"],$_POST["extra"]));
$last_id = $conn->lastInsertId();
header("Location: editarContenidos.php?id=".$_GET['id']);
}
?>

I found out what the problem was. The quotation marks were not properly used.
The following code worked:
<?php
include "../conn.php";
$sectionid = $_GET['id'];
$sql = "INSERT INTO contenido (id_contenido, tipo_contenido, id_seccion, orden_contenido, largo_contenido, corto_contenido, extra_contenido) VALUES (NULL, '".$_POST["tipo"]."', '".$sectionid."','".$_POST["orden"]."','".$_POST["largo"]."','".$_POST["corto"]."','".$_POST["extra"]."')";
$stmt = $conn->prepare($sql);
//echo $sql;
if ($stmt = $conn->prepare($sql))
{
$stmt->execute();
$last_id = $conn->insert_id;
header("Location: editarContenidos.php?id=".$sectionid);
}
?>

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.

PHP insert blank values instead of GET values

I have this script on my site:
<?php
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if($db_found) {
$SQL = "INSERT INTO users (user, address)
VALUES('".$_GET['username']."','".$_GET['password']."')";
$result = mysql_query($SQL);
mysql_close($db_handle);
print "Records added to the database";
}
else {
print "Database NOT found";
mysql_close($db_handle);
}
?>
I then open this url in my browser:
http://ringkapps.altervista.org/addToDatabase.php?user=ringk&address=test
But instead of inserting "ringk" and "test" in the table, it inserts this:
Can't understand why, any help would be greatly appreciated.
This code is wrong!
$SQL = "INSERT INTO users (user, address)
VALUES('".$_GET['username']."','".$_GET['password']."')";
Replace this.
$SQL = "INSERT INTO users (user, address)
VALUES('".$_GET['user']."','".$_GET['address']."')";
It's not working because you're calling
http://ringkapps.altervista.org/addToDatabase.php?user=ringk&address=test
Which creates $_GET["user"] and $_GET["address"] but you are trying to put in the db $_GET['username'] and $_GET['password'] which don't exist.
You should call:
http://ringkapps.altervista.org/addToDatabase.php?username=ringk&password=test
Plus, read something on security for PHP apps, your code is prone to a lot of vulnerabilities!!!
In the url : http://ringkapps.altervista.org/addToDatabase.php?user=ringk&address=test
We can see user = ringk and address = test.
Where user is the key and ringk it's value.
Where address is the key and test it's value.
You can print all the $_GET value by using var_dump($_GET) and see by yourself what's in it.
My guess is that what you want is to access
$_GET['user'] and $_GET['address']
then just replace the line :
VALUES('".$_GET['username']."','".$_GET['password']."')";
with
VALUES('".$_GET['user']."','".$_GET['address']."')";
or you could update the url to match the code.

Submit variable in URL to MySQL Database

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>";
}
?>

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