Fetch data into table using PDO result in no value - php

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.

Related

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.

Multiple criteria replace mysql record with php

I am collecting data from a html form, submitting the data to mysql using a php script.
However, I can't figure out how to replace/update a record if multiple criteria match.
If a new submitted record from the html form, has the same 'type', 'volume' and 'place_name' as an existing record, it should replace the 'price'.
At this moment, it is just writing a new line with the new data.
Can anyone please help me with this? Thanks!
Please see my php code below:
<?php
require("config.php");
if(!$con)
{
echo 'Not Connected To Server';
}
if(!mysqli_select_db($con,'DB3469638'))
{
echo 'Database Not Selected';
}
$type= $_POST['type'];
$volume= $_POST['volume'];
$price= $_POST['price'];
$email = $_POST['email'];
$place_name = mysqli_real_escape_string($con, $_POST['place_name']);
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$location = mysqli_real_escape_string($con, $_POST['location']);
$sql = "INSERT INTO markers (type, volume, price, place_name,
place_Location, email, place_Lat,place_Lng)
VALUES ('$type','$volume','$price','$place_name',
'$location','$email','$lat','$lng')";
if(!mysqli_query($con,$sql))
{
echo 'Not Inserted';
}
else
{
header("refresh:4; url=addprice.php");
echo "<div align='center' style ='font:40px/60px Arial,tahoma,sans-
serif;color:#ffffff'> Submitted! <br><br> Redirecting Automatically
</div>";
}
?>
First you would want to create a multi-column index in SQL on the columns you don't want to be duplicates:
CREATE INDEX multiIndex ON markers (type, volume, place_name);
Now you can use ON DUPLICATE KEY UPDATE in your PHP:
$sql = "
INSERT INTO markers
(type, volume, price, place_name, place_Location, email, place_Lat,place_Lng)
VALUES
('$type','$volume','$price','$place_name', '$location','$email','$lat','$lng')
ON DUPLICATE KEY UPDATE
price = '$price'
";
First of all, you should find out if this is a new record, or an update of an existing one. To do this, you must either incorporate IDs (recommended) or query the database first (where type, volume and place_name matches with provided one - not recommended).
Beside this, you should avoid SQL injections by not using user input directly in your SQL queries.

INSERT INTO statement won't insert a specific value correctly?

I am trying to use the INSERT INTO SQL statement in php. It will input everything correctly up until the last value ($bands_bio). Instead of putting in the correct information, it leaves the value blank. I have looked over everything and can't seem to find any sort of syntax errors.
$page_title = "Create a new band";
require ('includes/database.php');
require_once 'includes/bandsHeader.php';
$band_name = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_name', FILTER_SANITIZE_STRING)));
$band_photo = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_photo', FILTER_SANITIZE_STRING)));
$genre = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'genre', FILTER_SANITIZE_STRING)));
$band_bio = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_bio', FILTER_SANITIZE_STRING)));
echo $band_bio;
if (($band_name === "") OR ($genre === "") OR ($band_photo === "") OR ($band_bio = "")) {
$errno = $conn->errno;
$errmsg = $conn->error;
echo "<div id='contentWrapper'>";
echo "<div class='contentBox'>";
echo "Insertion failed with: ($errno) $errmsg<br/>\n";
echo "</div></div>";
$conn->close();
include 'includes/searchFooter.php';
exit;
}
$albums = 0;
$sql = "INSERT INTO bands VALUES (NULL, '$band_name', '$genre', '$albums', '$band_bio')";
$query = #$conn->query($sql);
if (!$query) {
$errno = $conn->errno;
$errmsg = $conn->error;
echo "<div id='contentWrapper'>";
echo "<div class='contentBox'>";
echo "Insertion failed with: ($errno) $errmsg<br/>\n";
echo "</div></div>";
$conn->close();
include 'includes/footer.php';
exit;
}
As you can see, I echoed out $band_bio in order to see if it was getting the right value from my form that uses the GET method, which it is so that's not the issue. It has no problem inserting everything correctly up until the last value, which is supposed to be the last column called band_bio in my bands table in my database. It will not output any errors or anything, either. It's almost as if it's taking the string data from the variable and removing all of the text before it inserts the information.
I have been working on this website for a few weeks now and have used the INSERT INTO statement the exact same way on other pages and it works just fine. This is the first thing that has really stumped me and I can't figure it out. Any help is appreciated.
When inserting, ensure that your pk (id) field is set to auto-increment.
This way, you can exert more control over your queries. You should be more successful with:
$sql = "INSERT INTO bands "
. "(`band_name`,`genre`,`numof_albums`,`band_bio`) "
. "VALUES ('$band_name', '$genre', '$albums', '$band_bio')";
By not specifying the pk field, INNODB will automatically increment and insert it for you.
The idea is that you want to specify which columns are being inserted into. Relying on column ordering by mysql is fine, but there may be something at play in your case.
There should be no reason why band_bio would be "left off". You would get a column-mismatch error.
Totally found the answer myself! It, in fact, was a syntax error.
if (($band_name === "") OR ($genre === "") OR ($band_photo === "") OR ($band_bio = ""))
The variable $band_bio was being assigned to a blank string in the if statement since I accidentally used an assignment operator rather than a comparison operator. So the correct code would need to be $band_bio === "" rather than $band_bio = "".
I swear, the problem is always something so much simpler than you think it's going to be.

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

Stopping users posting more than once

Before posting my form I am checking the database to see if there are any previous posts from the user. If there are previous posts then the script will kick back a message saying you have already posted.
The problem is that what I am trying to achieve isn't working it all goes wrong after my else statement. It is also probable that there is an sql injection vulnerability too. Can you help??4
<?php
include '../login/dbc.php';
page_protect();
$customerid = $_SESSION['user_id'];
$checkid = "SELECT customerid FROM content WHERE customerid = $customerid";
if ($checkid = $customerid) {echo 'You cannot post any more entries, you have already created one';}
else
$sql="INSERT INTO content (customerid, weburl, title, description) VALUES
('$_POST[customerid]','$_POST[webaddress]','$_POST[pagetitle]','$_POST[pagedescription]')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
To answer the second part of your question: yes, you're very vulnerable to SQL injection:
$sql="INSERT INTO content (customerid, ...) VALUES ('$_POST[customerid]', ...)";
^
This article explains SQL Injection and how to avoid the vulnerability in PHP.
You are missing curly brackets {}:
<?php
if ($checkid == $customerid) {echo 'You cannot post any more entries, you have already created one';}
else
{
$sql="INSERT INTO content (customerid, weburl, title, description) VALUES
('$_POST[customerid]','$_POST[webaddress]','$_POST[pagetitle]','$_POST[pagedescription]')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
}
?>
In addition to the missing curly braces mentioned previously it looks like you're assigning in the if statement, which will cause the statement to always evaluate to true:
if ($checkid = $customerid) {echo 'You cannot post any more entries, you have already created one';}
Should be:
if ($checkid == $customerid) {echo 'You cannot post any more entries, you have already created one';}
Also, $checkid contains an SQL query string. I assume you intend to actually run the query and populate $checkid with something comparable to a $customerid before actually getting to the comparison.
In addition to the SQL injections (man, read a book/tutorial about that before you start!) and the missing braces after the else, you have two errors in there: First, you don't execute the $checkid query, secondly, you only have one = in the if (so you assign the value of $customerid to $checkid.
It is also probable that there is an sql injection vulnerability too.
Why "is possible"? Don't you see that yourself? Don't you write your code in a way that you avoid such issues in the first place?
Re: sql injection - any time you trust data from your users you're vulnerable. Take your INSERT statement and sanitize it.
$sql = sprintf("INSERT INTO content (customerid, weburl, title, description) VALUES ('%d','%s','%s','%s')",
$_POST['customerid'], //forced as digit
mysql_real_escape_string($_POST['webaddress']),
mysql_real_escape_string($_POST['pagetitle']),
mysql_real_escape_string($_POST['pagedescription']) );
Also, you should use apostrophes in your array keys. In double quotes, that'd be:
echo "Post data webpage title is {$_POST['pagetitle']}";
$_SESSION will clear when the browser is closed out. Therefore, I'd suggest using Cookies for a definite way.
I've updated your code as follows:
include '../login/dbc.php';
page_protect();
$customerid = $_COOKIE['user_id'];
$checkid = "SELECT customerid FROM content WHERE customerid = $customerid";
if ($checkid = $customerid) {echo 'You cannot post any more entries, you have already created one';}else{
$sql="INSERT INTO content (customerid, weburl, title, description) VALUES
('$_POST[customerid]','$_POST[webaddress]','$_POST[pagetitle]','$_POST[pagedescription]')";
if (!mysql_query($sql))
die('Error: ' . mysql_error());
else
echo "1 record added";
}
If you are worried about injection add this tidbit prior to your insert query:
foreach($_POST as $key=>$value){
$_POST[$key] = addslashes($value);
}

Categories