Php post with direct link - php

I have a players page which returns a list of players and provides you with some options. One is edit and the other is stats. The edit page predictably takes you to a form where you can edit the player info like name, while the stats page simply shows statistics to do with that player (such as games played) that come primarily from other tables. Currently this a snippet of the code used to get stats:
if (isset($_POST['action']) and $_POST['action'] == 'Stats')
{
include $_SERVER['DOCUMENT_ROOT'] . '/statsite/includes/db.inc.php';
try
{
$sql = 'SELECT id, user.usertitle as name, role, aggression, position, bowlstyle, cricket_players.username, link FROM cricket_players INNER JOIN user ON cricket_players.username = user.userid WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
}
catch (PDOExecption $e)
{
$error = 'Error retrieving player details';
include 'players.html.php';
exit();
}
$row = $s->fetch();
$pageTitle = 'View Stats';
$name = $row['name'];
$aggression = $row['aggression'];
$position = $row['position'];
$role = $row['role'];
$bowlstyle = $row['bowlstyle'];
$link = $row['link'];
$username = $row['username'];
$id = $row['id'];
include 'stats.html.php';
exit();
}
If I click on the stats button everything works fine, but the address bar only has /? on the end of the address of the players page. Is there any way that I can get it to display something such as /stats?id=1 so that it can be linked directly?

Yes, you can directly pass the value /stats?id=1
and get value of id by using $_REQUEST['id'] OR $_GET['id']
Don't use : $s->bindValue(':id', $_POST['id']);
Use : $s->bindValue(':id', $_GET['id']);
OR
$s->bindValue(':id', $_REQUEST['id']);

Related

Check if child data exists before deleting parent

I have news_Category and news table, here every news comes under one category,so before deleting new_category I want to display user a msg that child news exists in this category so u are not allowed to delete, If there are no child news than a confirm alert to user that "do u really want to delete".If he confirms the news category gets deleted.
HTML STUFF
<?php echo "<a style='color:red;''
href='delete.php?delete=$values[category_id]&
img=$values[category_image]'><i class='fas fa-trash-alt'></i></a>"; ?>
if ($_GET['msgError']) {
echo "<script>alert('First Delete The News Than Category');</script>";
}
if ($_GET['msg']) {
?>
<?php
}
?>
DELETE.PHP
if (isset($_GET['delete'])) {
$id= $_GET['delete'];
$img=$_GET['img'];
$obj=new commands();
$obj->delete_category($id,$img);
}
Delete Function
function delete_category($id,$img)
{
$stmt = $this->con->prepare("SELECT category_id FROM nm_news where category_id='$id'");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($result) {
header('Location: news_category.php?msgError=' . urlencode(base64_encode("First Delete The News Than Category")));
} else {
$sql = $this->con->prepare("DELETE FROM `nm_category` WHERE category_id=:id");
$sql->bindParam(':id', $id);
$sql->execute();
unlink("uploads/" . $img);
header('Location: news_category.php?msg="confirm"');
$this->con = null;
}
}
I am not able to make to logic here, how can I check whether the child news exists so i can display error msg and if there is no child news how to show confirm alert to allow delte
You need to check to see if the result is empty.
Something like this:
function delete_category($id,$img)
{
$stmt = $this->con->prepare("SELECT category_id FROM nm_news where category_id='$id'");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (empty($result)) {
header('Location: news_category.php?msgError=' . urlencode(base64_encode("First Delete The News Than Category")));
} else {
$sql = $this->con->prepare("DELETE FROM `nm_category` WHERE category_id=:id");
$sql->bindParam(':id', $id);
$sql->execute();
unlink("uploads/" . $img);
header('Location: news_category.php?msg="confirm"');
$this->con = null;
}
}
Edit due to extra details request
On the front end you just need to display the GET msgError like this:
<?php isset($_GET['msgError']) ? echo url_decode(base64_decode($_GET['msgError'])) : '' ?>
Where you want to show the message text.

PHP doesn't post to DB from data entered in form?

I can't see the problem here. I enter data in my input cells and after submit it only refresh a page and do not post anything in the MySQL. I'm doing this by watching online tutorial which is old, so maybe there are some old methods, that could be a problem.
<?php
include "../db/connect.php";
if (isset($_POST['pavadinimas'])) {
$pavadinimas = mysqli_real_escape_string($con, $_POST['pavadinimas']);
$kaina = mysqli_real_escape_string($con, $_POST['kaina']);
$info = mysqli_real_escape_string($con, $_POST['info']);
$gamintojas = mysqli_real_escape_string($con, $_POST['gamintojas']);
$gamintojas = mysqli_real_escape_string($con, $_POST['atmintis']);
$tipas = mysqli_real_escape_string($con, $_POST['tipas']);
$kiekis = mysqli_real_escape_string($con, $_POST['kiekis']);
// See if that product name is an identical match to another product in the system
$sql = mysqli_query($con, "SELECT id FROM prekes WHERE pavadinimas='$pavadinimas' LIMIT 1");
$productMatch = mysqli_num_rows($sql); // count the output amount
if ($productMatch > 0) {
echo '<script type="text/javascript">alert("KLAIDA! Bandėte įkelti prekę, kurios pavadinimas jau yra įrašytas duomenų bazėje.");</script>';
exit();
}
// Add this product into the database now
$sql = mysqli_query($con, "INSERT INTO prekes (pavadinimas, kaina, info, gamintojas, atmintis, tipas, kiekis, laikas)
VALUES('$pavadinimas','$kaina','$info','$gamintojas','$atmintis','$tipas','$kiekis',now())") or die (mysqli_error($con));
$pid = mysqli_insert_id();
// Place image in the folder
$newname = "$pid.jpg";
move_uploaded_file( $_FILES['fileField']['tmp_name'], "../inventory_images/$newname");
header("location: itemList.php");
exit();
}
?>
There was just a dumb mistake. In html SUBMIT button name was set to 'button', not submit, so it didn't post it to the database.
and this
if (isset($_POST['pavadinimas']))
should have been this
if (isset($_POST['submit']))

PHP - Get the id of the table row clicked

I'm currently creating the account management system of my website and I decided to add a feature that enables me to declare weather a specific account is active or inactive. The data is retrieved from my mysql table.
$query = mysqli_query($DBConnect,"SELECT * from REG");
echo "<table class = 'table' style = 'width:90%;text-align:center'>";
while($getData = mysqli_fetch_assoc($query))
{
$username = $getData['uname'];
$fname = $getData['fname'];
$mname = $getData['mname'];
$lname = $getData['lname'];
$bday = $getData['bday'];
$email = $getData['email'];
$contact = $getData['contact'];
$gender = $getData['gender'];
if($getData['userlevel'] == 1)
{
$userlevel = "user";
}
else
{
$userlevel = "admin";
}
if($getData['status'] == 1)
{
$status = "active";
}
else
{
$status = "disabled";
}
echo "<tr>";
echo "<td>$username</td><td>$fname</td><td>$mname</td><td>$lname</td><td>$bday</td><td>$email</td><td>$contact</td><td>$gender</td><td>$userlevel</td><td>
<a href ='..\status.php' >$status </a></td></tr>";
}
echo "</table>";
This is the content of status.php
session_start();
$DBConnect = mysqli_connect("localhost", "root","","kenginakalbo")
or die ("Unable to connect".mysqli_error());
$query = mysqli_query($DBConnect,"SELECT * from REG where id = '$_SESSION[id]'");
while($getData = mysqli_fetch_assoc($query))
{
$status = $getData['status'];
echo "'$_SESSION[id]'";
}
if($status == 1)
{
$query = mysqli_query($DBConnect, "UPDATE REG SET status = 0 where id = '$_SESSION[id]'");
}
else if ($status == 0)
{
$query = mysqli_query($DBConnect, "UPDATE REG SET status = 1 where id = '$_SESSION[id]'");
}
header("Location: admin/login.php");
What I need to do is get the ID of the row clicked and declare it in my session so that it can be used in the "status.php" file. But in this code, the last id in the table is the one that is declared into the session because of the loop. How do I get the value of the id of the row that is clicked? (is there sort of like onClick function in php? Thank you.
pass id parameter,
status.php?id=$id;
in status.php
$id = $_GET['id'];
Change:
echo "<td>$username</td><td>$fname</td><td>$mname</td><td>$lname</td><td>$bday</td><td>$email</td><td>$contact</td><td>$gender</td><td>$userlevel</td><td>
<a href ='..\status.php' >$status </a></td></tr>";
to:
echo "<td>$username</td><td>$fname</td><td>$mname</td><td>$lname</td><td>$bday</td><td>$email</td><td>$contact</td><td>$gender</td><td>$userlevel</td><td>
<a href ='..\status.php{$getData['id']}' >$status </a></td></tr>";
And in your status.php change $_SESSION['id'] to $_GET['id']. But make sure to first prevent SQL injection either through mysql_real_escape_string($_GET['id']) or through PDO.
There is no onclick function in PHP but you can create a form with a button on each row that holds the value of the row that it is in. Have that form simply do a post or a get request back to the status.php. Adding it to the session might be a bad idea.
Instead of a button you can also create a link modify your loop so that there is a property called $rowid and increment it within your loop.
Perhaps, what you really want is to use a GET superglobal here. You can switch
for
Then, you use $_GET["userid"] instead of $_SESSION[id] on the status.php page.
Also, you dont need a while for the status page. You should check the number of results, if it was 1 it means the user exists, and then you just do a $getData = mysqli_fetch_assoc($query) without the while

Insert URL text into database using x-editable

I have a table with inline editing using X-editable and everything is working fine including the value being submitted to the database, but for some reason it will display my echo in the else section.
Here is my PHP code:
require("config.php");
$userid = $_SESSION['user']['id'];
$sql = "SELECT fb_url, tw_url, ggl_url FROM social_preferences WHERE user_id = :userID";
$stmt = $db->prepare($sql);
$stmt->bindParam(":userID", $userid, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch();
$pk = $_POST['pk'];
$name = $_POST['name'];
$value = $_POST['value'];
if(!empty($value)) {
try // save user selection to the database
{
$stmt = $db->prepare("UPDATE social_preferences SET tw_url = :twurl WHERE user_id = :userID");
$stmt->bindParam(":userID", $pk, PDO::PARAM_INT);
$stmt->bindParam(':twurl', $value);
$stmt->execute();
header("Location: admin-social.php");
die("Redirecting to admin-social.php");
} catch(PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); }
}else {
echo 'Something went wrong!';
var_dump($value);
}
Here is my HTML code:
<a name="tw-url" id="tw-url" data-type="text" data-pk="<?php echo ($userid);?>" title="Edit"><?php echo ($result['tw_url']);?></a>
Like I said above everything seems to be working but it redirects to a page that will display my echo Something went wrong!even though it submitted the value to the DB. I included the var_dump to see if there is a value and that returns NULL. Can someone please help me? Any ideas why it would submit the right value to the database but redirect to my error?
Also, at what point does it send it to the database? I have a table in a form with a save button, but when I open the editable text and submit the new value does it send to the database when I save from the pop-over or when I click the save button in my table form?
The else statement is executing because when your details inserted into DB, you have set a header which redirects to the same page, in that case the variable $value value set to empty and your else statement executes.
The above answer is only valid if you set your header to same page.

Get data won't insert

I've been using $_GET data to send data across pages and it has been working fine.
What i have on one page is news. Each news article has its own specific ID (and this page works perfectly fine). I can click on an add me button next to each event to add myself as a volunteer for organising the BBQ for that event. However now i'm trying to click on an add button which can add other users to the BBQ.
I've checked to see if the $_GET data is returning anything on page load and it does, however the values are lost when i click submit. So, when i check to see if it returns anything inside the isset($_POST['userselect']), the values are lost:
Here is my code:
$rosterID = $_GET["rosterid"];
$eventID = $_GET["eventid"];
//if i check to see if they gets work here, they do.
if (hasRole2($connection, "Admin") || hasRole2($connection, "Moderator") || hasRole2($connection, "BBQ Moderator")){
$usernames[] = array();
if ($stmt = $connection->prepare("SELECT id, uid from people")){
$stmt->execute();
$stmt->bind_result($id, $username);
$stmt->store_result();
$form = new jqmForm();
$form->method('post');
$sel = $form->add(new jqmSelect('userselect','userselect','<p align="center">Select User:</p>'), true);
while ($stmt->fetch()){
$usernames[] = array('uid' => $username, 'id' => $id);
$optName = $username;
$optValue = $id;
$sel->add(new jqmOption($optName, $optValue, false));
$sel->attribute('data-native-menu', 'false');
}
$stmt->close();
$form->add(new jqmInput('submit', 'submit', 'submit', 'submit', '', 'b', true));
}
if (isset($_POST["userselect"])){
//if i check to see if the gets work here, they don't.
$personID = $_POST["userselect"];
if (rostered($connection, $personID, $rosterID, $eventID)){
$personID = $_POST["userselect"];
$p->addContent("<p align=center><font color = red>You have already rostered for this event</font></p>");
$login = $p->addContent("<font color=brown size=4><a href = news.php rel=external> Go back </a></font>");
$login->attribute('align', 'center');
}
else{
$search = "INSERT INTO RosterPeopleEvent (roster_id, person_id, news_id) VALUES (?, ?, ?)";
if (!$roster = $connection->prepare($search)){
$p->addContent("Inserting into RosterPeopleEvent Prepare failed: (" . $connection->errno . ") " . $connection->error);
}
else{
$roster->bind_param("iii", $_GET["rosterid"], $personID, $_GET["eventid"]);
$roster->execute();
}
}
}
}
Just added:
$form->action("url.php?rosterid=$rosterID&eventid=$eventID");
This worked.

Categories