I'm trying to get data from a database but cant seam to get the following working, does anyone know why?
I have tried print_r too and shows nothing, the db connection and everything is working too.
$id = $_GET['id'];
$query = $db->prepare('SELECT id, title, content FROM articles WHERE id = $id');
$query->execute();
$article = $query->fetchall();
This does however print_r the id from the URL correctly.
print_r($_GET);
Any help is appreciated!
Important note:
Variables inside single qoutes are not interpolated. They're just literal strings
Much better to bind them properly:
$id = $_GET['id'];
$query = $db->prepare('SELECT id, title, content FROM articles WHERE id = :id');
$query->bindParam(':id', $id);
$query->execute();
$article = $query->fetchAll(PDO::FETCH_ASSOC);
Related
I have a like button, which allows users to like posts on my site. If the user likes a post they have not liked before it will +1, if they press the same like button again it will -1. This is working on my virtual server on my laptop. However, the same code is not working on my live site. On my live site the user is able to like the same post multiple times, which is not what I want. I'm using a JQuery Ajax call to a PHP file that fires a some MySQL code.
Can anyone see anything obviously wrong with the PHP below?
include ("../con/config.php");
$postid = $_POST['postid'];
$userid = $_POST['userid'];
$query = $con->prepare("SELECT COUNT(*) AS CntPost FROM Likes WHERE UserID = ? AND PostID = ?");
$query->bind_param('ss',$userid,$postid);
$query->execute();
$result = $query->get_result();
$fetchdata = $result->fetch_assoc();
$count = $fetchdata['CntPost'];
if($count == 0){
$stmt = $con->prepare("INSERT INTO Likes(UserID,PostID) VALUES(?,?)");
$stmt->bind_param("ss", $userid, $postid);
$stmt->execute();
} else {
$stmt = $con->prepare("DELETE FROM Likes WHERE UserID = ? AND PostID = ?");
$stmt->bind_param("ss", $userid, $postid);
$stmt->execute();
}
// count numbers of likes in post
$query = $con->prepare("SELECT COUNT(*) AS CntLike FROM Likes WHERE PostID = ?");
$query->bind_param('s', $postid);
$query->execute();
$result = $query->get_result();
$fetchlikes = $result->fetch_assoc();
$totalLikes = $fetchlikes['CntLike'];
$return_arr = array("likes"=>$totalLikes,"type"=>$count);
echo json_encode($return_arr);
Managed to solve it. The issue was in the MySQL database column itself for the UserID. The number of chars for the column was not long enough and was truncating the UserID, which I populate using the sessionID. I amended this field in the database to allow for the length of a sessionID.
perhaps this statement
"SELECT COUNT(*) AS CntLike FROM Likes WHERE PostID = ?" need UserID in WHERE statement so you would know that specific UserID in that specific PostID
edited...
hi guys can anyone help me with my website
I just want to get a specific comment in the comment area just like in facebook
<?php
require 'db.php';
$sql = 'SELECT * FROM comment WHERE postID = postID';
$statement = $connection->prepare($sql);
$statement->execute();
$comment = $statement->fetch(PDO::FETCH_OBJ);
?>
what I mean is that if I comment in the first post it will just fetch the current comment and it will not display on the other post.
Here's what your query is currently doing:
get records from the table comment where the field postID = postId
Which of course, won't work, you're using a string (without quotes) as your value. You need to bind the parameter and pass the value in, e.g.
$sql = 'SELECT * FROM `my_table` WHERE `some_field` = :myVal;';
$res = $conn->prepare($sql);
$res->execute([':myVal' => $_GET['id']]);
$data = $res->fetchAll(PDO::FETCH_ASSOC);
Here, I pass the bind a param (:myVal) and then prepare that statement. You then pass in the value for :myVal (in this case, a $_GET of the query param id).
Then fetch, var_dump/print_r that, and you should see table data in your script.
I believe answer would look like this:
<?php
require 'db.php';
$postId = 1; // get it somewhere, probably from $_GET
$sql = 'SELECT * FROM comment WHERE postID = ?';
$statement = $connection->prepare($sql);
$statement->execute( [$postId]);
$comment = $statement->fetch(PDO::FETCH_OBJ);
?>
Explanations, copied from comment to original question:
Your SQL condition postID = postID literally says any comment. You need to pass actual post ID there.
I am very worried about sql injection. I have been reading up about it and been trying to prepare the following query:
$query_AcousticDB = "SELECT * FROM products WHERE Category = 'Acoustic ' ORDER BY RAND()";
$AcousticDB = mysqli_query($DB, $query_AcousticDB) or die(mysqli_connect_error());
$row_AcousticDB = mysqli_fetch_assoc($AcousticDB);
$totalRows_AcousticDB = mysqli_num_rows($AcousticDB);
which works great.
I thought that I only have to change to the following:
$query_AcousticDB = prepare("SELECT * FROM products WHERE Category = 'Acoustic ' ORDER BY RAND()");
However this doesn't work. I get the following error:Call to undefined function prepare()
I still would like to get my values as:<?php echo $row_AcousticDB['what ever']; ?>
Can somebody point me into the right direction?
How about this?
$category = "Acoustic";
$sql = "SELECT * FROM products WHERE Category = ? ORDER BY RAND()";
$stmt = $DB->prepare($sql);
$stmt->bind_param('s', $category);
$stmt->execute();
$row_AcousticDB = $stmt->get_result(); // altenative: $stmt->bind_result($row_AcousticDB);
$row_AcousticDB->fetch_array(MYSQLI_ASSOC)
If you let the user enter any data (in text boxes on website) or you pull anything out of database for use (risk of second order injection) make sure you sanitize it (cleanse it of any nasty tags like < or >) by using htmlspecialchars($category) or htmlentities($category).
With this method implemented into your code, you will be reasonably safe from SQL Injection :)
Try to make this variable global: Put this on the upper part of your script global $acousticDB; or else you may try this $acoustic='';
I am creating a dynamic page which changes depending on which ever post the user clicks onto. I am also wanting the views (hit-counter) the page gets to go up by one each time the page is loaded. I am currently getting the following error.
Fatal error: Call to a member function bind_param() on a non-object in C:\Users\PC\Documents\XAMPP\htdocs\post.php on line 13
<?php
session_start();
include 'php/config.php';
$post = $_GET['post'];
$stmt = $mysqli->prepare("SELECT * FROM forum WHERE ForumId = '$post'");
$stmt->execute();
$stmt->bind_result($ForumId,$ForumTitle,$ForumPostText,$PostDate,$Views);
$stmt->fetch();
$stmt->close();
$Views = 1;
$stmt = $mysqli->prepare("UPDATE 'forum' SET 'Views' = 'Views'+ 1 WHERE 'ForumId' = '?' ");
$stmt->bind_param('i',$post);
$stmt->execute();
$stmt->close();
?>
<!DOCTYPE html>
// The rest of the webpage yada yada yada
Remove (') single quotes in update query and use backtick (`) instead
So
"UPDATE `forum` SET `Views` = Views+ 1 WHERE `ForumId` = ?"
Although Krish R's response is the solution, one of the things you will want to do in cases like this, is look at $mysqli->error to actually get an error message. This will tell you that you have a syntax error near 'forum' SET 'Vi.... That in itself should indicate that that specific character (the first ' in the string) is the most likely cause of the error.
It seems you have a problem in the query.
Take note, that PDO statement dont need single quotes
Try with this:
$stmt = $mysqli->prepare("UPDATE forum SET Views = Views+ 1 WHERE ForumId = ?");
$stmt->bind_param('i', $post);
<?php
session_start();
include 'php/config.php';
$post = $_GET['post'];
$stmt = $mysqli->prepare("SELECT * FROM forum WHERE ForumId = $post");
$stmt->execute();
$stmt->bind_result($ForumId,$ForumTitle,$ForumPostText,$PostDate,$Views);
$stmt->fetch();
$stmt->close();
$Views = 1;
$stmt = $mysqli->prepare("UPDATE forum SET Views = Views + 1 WHERE ForumId = ?");
$stmt->bind_param('i', $post);
$stmt->execute();
$stmt->close();
?>
<!DOCTYPE html>
I am working on a friend list function and I can't figure out how to correctly receive the values.
My code looks like this:
$getuid = $mysqli->prepare("SELECT `uid` FROM `users` WHERE name = ? OR name = ?");
$getuid->bind_param("ss", $user, $friend);
$getuid->execute();
$getuid->bind_result($uid);
$getuid->fetch();
$getuid->close();
$resetpass = $mysqli->prepare("INSERT INTO `friendlist` SET `friend1`=?, `friend2`=?, `accept`=0");
$resetpass->bind_param("ss", $uid[0], $uid[1]);
With the first query I get exactly two uid values back. I want to use them in the second query. It seems like bind_result is not working, neither as array nor when using two values in bind_result. How can I do this using mysqli. I can't use get_result because I'm on PHP 5.2 .
Anyone able to help me?
I think you need something like this. I have not tested it and there are probably even better ways to do this. I just tried the quickest change i could make to your original code to get it to work.
$query = "SELECT uid FROM users WHERE name = '".$user."' OR name = '".$friend."'";
$getuid = $mysqli->query($query);
if($uid = $getuid->fetch_assoc())
{
$query = "INSERT INTO friendlist SET friend1= '".$uid['uid'][0]."', friend2='".$uid['uid'][1]."', accept=0";
$mysqli->query($query)
}
$getuid->close();
Okay I finally understood the concept of fetch.
In order to receive all the values I have to retrieve them in a while-loop.
Here is the solution:
$getuid = $mysqli->prepare("SELECT `uid` FROM `users` WHERE name = ? OR name = ?");
$getuid->bind_param("ss", $user, $friend);
$arra = array();
$getuid->execute();
$getuid->bind_result($uid);
while ($getuid->fetch()) {
$arra[] = $uid;
}
Now I can call the array values using $arra[0] and $arra[1]