PDO PhP - Delete query from selecting ID - php

I'm trying to make it so when i click a "x" it will delete the entire row.
I've linked each record to my jobRef however the delete isn't working.
This is what i've got so far;
<?php
$status = 'available';
$stmt = $pdo->query('SELECT * FROM jobs WHERE jobStatus = "' . $status . '"');
$results = $stmt->fetchAll();
echo "<table><tr><td>Job Reference</td><td>Description</td>";
foreach ($results as $row) {
echo "<tr><td>".$row['jobRef']."</td>","<td>".$row['jobDescription']."</td>";
echo "<td><a href='edit.php?id=".$row['jobRef']."'>Edit</a></td>";
?>
Heres my delete.php
<?php
require 'mysqlcon.php';
?>
<?php
if(isset($_GET['id']))
{
$id=$_GET['id'];
$query1= ("DELETE FROM person WHERE id='$id'");
if($query1)
{
header('location:Vacancies.php');
}
}
?>

You simply write your query , Forget to execute it.
$query1= ("DELETE FROM person WHERE id='$id'");
You need to execute it
$pdo->query("DELETE FROM person WHERE id='$id'");
Or better to use bind statement
$sth =$pdo->prepare('DELETE FROM person WHERE id=:id');
$sth->bindValue(':id', $id, PDO::PARAM_INT);
$sth->execute();
$count = $sth->rowCount();
if($count>0)
{
header('location:Vacancies.php');
}else{
echo "Error in delete";
}

Related

PHP Function only returning one row when multiple should be returned

I wrote a PHP function to display the role name of a person when they log into my website. However when a user has multiple roles it only returns one row instead of all of them. Any help would be appreciated.
getRoleName Function
function getRoleName($conn, $id)
{
$id = $_SESSION['userid'];
$sql = "SELECT
* FROM users
INNER JOIN user_roles ON users.usersId = user_roles.user_id
INNER JOIN roles ON user_roles.role_id = roles.role_id
WHERE users.usersId = ?;";
$stmt = $conn->prepare($sql);
//$stmt -> mysqli_stmt_prepare($stmt, $sql);
$stmt -> bind_param("s", $_SESSION['userid']);
$stmt -> execute();
$result = $stmt->get_result();
if($result->num_rows > 0){
while ($row = $result->fetch_assoc()){
if ($row['role_name'] == 0) {
$array = array($row['role_name']);
foreach ($array as $value) {
echo $value;
}
}else{
echo "no role!";
}//end else
}//end while
}else{
echo "JPS Says go away from me!";
}//end if numrows
}
The index.php file is where the role is being displayed for the user to see.
<?php
include_once 'header.php';
include_once 'includes/dbh.inc.php';
?>
<?php
if (isset($_SESSION["useruid"]))
{
echo "<p>Hello there " . $_SESSION["useruid"]. "</p>";
echo "Your roles are ".getRoleName($conn, $_SESSION["userid"]);
}//end isset
?>
<?php
include_once 'footer.php';
?>

What PHP function should I use to call the id of a dynamic page?

I'm creating a news website, and want to create a dynamic PHP page that will have the header and footer, and get the content itself (title and text) from the database by calling the article's id via the URL(like 'article.php?id=1'), so that there is no need for creating a new file for each article. However, I don't know what function should I use to make that work. Currently, the code is like this:
<?php
include "header.php";
$query = "SELECT title_article, subtitle_article, content_article FROM tb_article WHERE id_tb_article = 1";
$conn = mysqli_connect('127.0.0.1:3307', 'root', '', 'article') or die("error");
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<div class='titlediv'><h1 class='title'>" . $row["title_article"]. "</h1></div><div class='titlediv'><h3 class='title'>". $row["subtitle_article"]. "</h3></div><div class='textdiv'><p class='text'>" . $row["content_article"]. "</p></div><br>";
}
} else {
echo "Article not found";
}
include "footer.php";
?>
To get the id value from query string in URL, you can use the PHP's superglobal $_GET['id'].
To select a dynamic value from SQL using this value you must use prepared statements with parameter binding.
Your code with all the fixes would look more or less like this:
<?php
include "header.php";
$query = "SELECT title_article, subtitle_article, content_article FROM tb_article WHERE id_tb_article = 1";
// Enable mysqli error reporting and NEVER die()
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli('127.0.0.1:3307', 'root', '', 'article');
$conn->set_charset('utf8mb4'); // You should always specify the correct charset, which most of the time should be utf8mb4
// prepare -> bind -> execute -> get result
$stmt = $conn->prepare('SELECT title_article, subtitle_article, content_article
FROM tb_article
WHERE id_tb_article = ? ');
$stmt->bind_param('i', $_GET['id']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows) {
// output data of each row
foreach ($result as $row) {
echo "<div class='titlediv'><h1 class='title'>" . htmlspecialchars($row["title_article"]). "</h1></div>";
echo "<div class='titlediv'><h3 class='title'>". htmlspecialchars($row["subtitle_article"]). "</h3></div>";
echo "<div class='textdiv'><p class='text'>" . htmlspecialchars($row["content_article"]). "</p></div><br>";
}
} else {
echo "Article not found";
}
include "footer.php";
Whenever output values into HTML context always do it via htmlspecialchars
You can use a GET method and the url look like 'article.php?id=2'.
<?php
include "header.php";
//use GET to get the id
$id = $_GET["id"];
// use .$id to concat to the query
$query = "SELECT title_article, subtitle_article, content_article FROM tb_article WHERE id_tb_article = ".$id;
$conn = mysqli_connect('127.0.0.1:3307', 'root', '', 'article') or die("error");
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<div class='titlediv'><h1 class='title'>" . $row["title_article"]. "</h1></div><div class='titlediv'><h3 class='title'>". $row["subtitle_article"]. "</h3></div><div class='textdiv'><p class='text'>" . $row["content_article"]. "</p></div><br>";
}
} else {
echo "Article not found";
}
include "footer.php";
?>
You want to look at the global variables $_GET and $_POST. In your example ('article.php?id=1') you will find the value of 'id' in $_GET['id'].
URL: article.php?id=42
echo $_GET['id']; // Outputs 42
Remember that anyone can change that value in the URL and even injecting malicious queries into your query. Its better to at least cast your id to an integer first and use always mysqli_real_escape_string() for URL given variables in the query.
URL: article.php?id=42;DROP TABLE tb_article
echo $_GET['id']; // Outputs "42;DROP TABLE tb_article", would delete your table when used directly
// Convert to an integer value
$id = intval($_GET['id']); // Returns 42
$query = "... FROM tb_article WHERE id_tb_article = ".mysqli_real_escape_string($id);

Select multiple rows from database

I want to be able to select all rows where a value matches with the one I'm calling for in php
This is what I have for now and the only thing I get is the first row. Not the other rows.
<?php>
session_start();
require "db.inc.php";
$id = $_SESSION['userId'];
$sql = "SELECT followingId FROM following WHERE followerId=$id";
$sth = $conn->query($sql);
if(!$sth) {
echo("Error description: " . mysqli_error($conn));
die();
}
$result = mysqli_fetch_array($sth);
echo var_dump($result);
$followedId = $result['followingId'];
echo $followedId;
And $conn is the connection variable in db.inc.php
You must iterate through the results array you are fetching
while ($row = mysqli_fetch_array($result)) {
foreach($row as $field => $value) {
//do something with $field and $val
}
}

Undefined property: PDOStatement::,$id_login,$nama_depan

Index.php
require_once '../../konfig/conn.php';
echo $id = $_SESSION['id'];
$sql = "SELECT * FROM i_user WHERE id_login = $id";
$stmt = $conn->prepare($sql);
$stmt->execute() . "<br/>";
I'm Try to count data from database and it's working
echo "<br>".$stmt->rowCount()." Total Rows";
and the result is "1 Total Rows", Please help me to fixed this...
while ($stmt->fetch(PDO::FETCH_LAZY)) {
echo $stmt->id_login;
echo $stmt->nama_depan;
}
return $stmt;
and this picture
from my database php code
You need to assign the result of the fetch to a variable:
while($row = $stmt->fetch(PDO::FETCH_LAZY)){
echo $row->id_login;
echo $row->nama_depan;
}
Perhaps like this?
while($rs = $stmt->fetch(PDO::FETCH_LAZY)){
echo $rs->id_login;
echo $rs->nama_depan;
}
Or, using prepared statement with a bound variable
include '../../konfig/conn.php';
$id=$_SESSION['id'];
$sql="SELECT * FROM i_user WHERE id_login=:id";
$stmt=$conn->prepare( $sql );
if( $stmt ){
$stmt->bindParam(':id',$id);
$res = $stmt->execute();
if( $res ){
while( $rs=$stmt->fetch( PDO::FETCH_LAZY ) ){
echo $rs->id_login, $rs->nama_depan;
}
}
}

Returning an array with PDO - using FetchAll doesn't work

I use the following code to retrieve data from my database. The problem is that it only displays the first row. In this particular case, it means that only the first picture is shown on the webpage but I want to show all of them.
<?php
$sql = "SELECT `image-id`, `article-id`, `image-path`, `image-title` FROM `table-images` WHERE `article-id` = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":id", $id);
$stmt->execute();
if($result = $stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<a class="swipebox" href="<?php echo $result['image-path'];?>" title="<?php echo $result['image-title'];?>">
<img alt="image" src="<?php echo $result['image-path'];?>"></a>
<?php
}// end if
else {
echo '0 results';
}// end else
?>
I read this article so I tried to use the code:
if($result = $stmt->fetchAll(PDO::FETCH_ASSOC));?
... but that doesn't work. It doesn't even echo the first picture anymore. What am I missing here?
Here is how it works:
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":id", $id);
$success = $stmt->execute();
if($success){
//fetch here
}
Now you have 2 options for fetching the data:
fetch()
fetch() will get rows one by one so you need a while loop.
while($rows = $stmt->fetch(PDO::FETCH_ASSOC)){
// get data
}
fetchAll()
fetchAll() get all the rows at once so no need for loops to retrieve the data, but if you need to loop then you will need a for loop.
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
//do something
}
<?php
$sql = "Your SQL query";
$id = 1;
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":id", $id);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC)
if($stmt->rowCount()){
foreach($result as $row){
echo $row['row_name'].'<br/>';
}
}else{
echo 'No results found';
}

Categories