PHP how to add user id in url? - php

I want to know how to add the logged in user's id in url (like ?id=")
I have searched a bit on Google, but I couldn't find anything that worked.
Here's the PHP code:
<?php
include("nav.php");
require("app/management/config.php");
session_start();
if(!isset($_SESSION['login_user']))
{
header("Location: index");
}
?>
<!DOCTYPE html>
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<!--<link rel="stylesheet" href="../css/providers.css">-->
<link rel="stylesheet" href="../css/main.css">
<link rel="stylesheet" href="../css/main2.css">
<meta charset="UTF-8">
<header class="header__wrapper wrapper">
<a href="/" class="header__habbo__logo">
<h1 class="header__habbo__name" id="ga-linkid-habbo-large"></h1>
</a>
</header>
<body>
<?php
include("header.php");
?>
<div class="info-block-homes">
<?php
$con = mysqli_connect($host, $username, $password , $database)
or die('Error connecting to MySQL server.');
$query = "SELECT * FROM `users` WHERE username = '{$_SESSION['login_user']}'";
$data = mysqli_query($con, $query);
$row = mysqli_fetch_array($data);
echo '<h1><font color="Red">Your Public Information:</font></h1>';
echo '<font color="green">' . $motto . '</font><font color="white">' . $row['motto'] . ' </font></br>';
echo '<font color="green">' . $credits . '</font><font color="white">' . $row['credits'] . ' </font></br>';
echo '<font color="green">' . $pixels . '</font><font color="white">' . $row['pixels'] . ' </font></br>';
echo '<font color="green">' . $points . '</font><font color="white">' . $row['points'] . ' </font></br>';
echo '<font color="green">' . $rank . '</font><font color="white">' . $row['rank'] .'</font>';
echo '<div style="margin-top:-130px; margin-left:150px;"><img src="http://www.habbo.com/habbo-imaging/avatarimage?figure='.$row['look'].'\"></div>';
?>
</div>
<div class="badges-block">
<h1><font color="Red">Your Badges:</font></h1>
<?php
$login_session=$_SESSION['login_user'];
$sql = "SELECT
so.*,
sr.*
FROM users AS so
INNER JOIN users_badges AS sr ON so.id = sr.user_id WHERE username = '{$_SESSION['login_user']}';";
$result = $dbconfig->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<img src='badges/".$row["badge_code"].".gif'>";
}
} else {
echo "0 results";
}
$dbconfig->close();
?>
</div>
<?php
include("footer.php");
?>
<div id="arrow-up-logout-homes" class="mydiv2"><ul><li><font color="white">Log Out</font></li></ul></div>
<?php
$con = mysqli_connect($host, $username, $password , $database)
or die('Error connecting to MySQL server.');
$online = "1";
$query = "SELECT count(id) as 'total' FROM `users` WHERE online = '$online'";
$data = mysqli_query($con, $query);
$row = mysqli_fetch_assoc($data);
$online=$row['total'];
echo '<div id="online-me" class="mydiv3"><center><span id="stats">'.$online.' User(s) Online!</span> </center></div>';
?>
<?php
$con = mysqli_connect($host, $username, $password , $database)
or die('Error connecting to MySQL server.');
$query = "SELECT * FROM `users` WHERE username = '{$_SESSION['login_user']}'";
$data = mysqli_query($con, $query);
$row = mysqli_fetch_array($data);
header('Location: /homes?id='.$row['id']);
exit;
?>
</body>
</head>
</html>
login page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<link href='http://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://d3hmp0045zy3cs.cloudfront.net/2.2.21/providers.css">
<?php
require("nav.php");
echo "<title>$title - $desc - $title</title>";
?>
<?php
require("app/management/config.php");
session_start();
if(isset($_SESSION['login_user']))
{
header("Location: me");
}
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password received from loginform
$username=mysqli_real_escape_string($dbconfig,$_POST['username']);
$password=mysqli_real_escape_string($dbconfig,$_POST['password']);
$securitykey=mysqli_real_escape_string($dbconfig,$_POST['securitykey']);
$sql_query="SELECT * FROM users WHERE username='$username' and password='$password' and securitykey='$securitykey'";
$result=mysqli_query($dbconfig,$sql_query);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$count=mysqli_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if($count==1)
{
$_SESSION['login_user']=$username;
header("location: me");
}
else {
$result = '<div style="position:absolute; margin-left:400px;">Invalid username or password (do not forget the security key if you got one)</div>';
echo "$result";
}
}
?>
<link rel="stylesheet" href="../css/main.css">
<link rel="stylesheet" href="../css/main2.css">
<head>
<header class="header__wrapper wrapper">
<a href="/" class="header__habbo__logo">
<h1 class="header__habbo__name" id="ga-linkid-habbo-large"></h1>
</a>
</header>
<body>
<div class="login-block">
<form method="post" action="" name="loginform">
<input type="text" value="" placeholder="Username" id="username" name="username" />
<input type="password" value="" placeholder="Password" id="password" name="password" />
<input type="securitykey" value="" placeholder="Security Key" id="securitykey" name="securitykey" />
<button type="submit">Submit</button>
</form>
</div>
<body>
<?php
include("header.php");
?>
<div id="content">
<!--<?php
// Create connection
$sql = "SELECT id, message, username FROM cms_message";
$result = $dbconfig->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<marquee behavior="scroll" direction="left">'.$row['username'].' says: '.$row['message'].'</marquee>';
}
} else {
echo "0 results";
}
$dbconfig->close();
?>-->
<?php
$con = mysqli_connect($host, $username, $password , $database)
or die('Error connecting to MySQL server.');
$online = "1";
$query = "SELECT count(id) as 'total' FROM `users` WHERE online = '$online'";
$data = mysqli_query($con, $query);
$row = mysqli_fetch_assoc($data);
$online=$row['total'];
echo '<div id="online" class="mydiv3"><center><span id="stats">'.$online.' User(s) Online!</span> </center></div>';
?>
<div id="arrow-up" class="mydiv2"><ul><li><font color="white">Register Now!</font></li></ul></div>
</br>
</br>
</br>
</br>
</br>
</br>
<?php
{
$con = mysqli_connect($host, $username, $password , $database)
or die('Error connecting to MySQL server.');
$query="SELECT * FROM cms_news WHERE highlighted = '1' AND date IN (SELECT max(date) FROM cms_news)";
$data = mysqli_query($con, $query);
while($row = mysqli_fetch_array($data))
{
echo '<main class="wrapper wrapper--content" ui-view="">
<section>
<h1 translate="NEWS_TITLE">Latest news</h1>
<div class="main main--fixed">
<habbo-compile data="NewsController.promos">
<section>
<article class="news-header news-header--column">
<a href="'.$row["link"].''.$row["room_id"].'" class="news-header__link news-header__banner">
<figure class="news-header__viewport">
<img src="'.$row["image"].'" alt="'.$row["image"].'" class="news-header__image news-header__image--featured">
<img src="'.$row["thumbnail"].'" alt="'.$row["thumbnail"].'" class="news-header__image news-header__image--thumbnail">
</figure>
</a>
<a href="/hotel?room='.$row["room_id"].'" class="news-header__link news-header__wrapper">
<h2 class="news-header__title">'.$row["title"].'</h2>
</a>
<aside class="news-header__wrapper news-header__info">
<time class="news-header__date">'.$row["date"].'</time>
<ul class="news-header__categories">
<li class="news-header__category">
'.$row["category"].'
</li>
</ul>
</aside>
<p class="news-header__wrapper news-header__summary">'.$row["description"].'</p>
</article>
</section>
</main> ';
}
mysqli_close($con);
}
?>
<?php
{
$con = mysqli_connect($host, $username, $password , $database)
or die('Error connecting to MySQL server.');
$query="SELECT * FROM cms_news WHERE highlighted = '0'";
$data = mysqli_query($con, $query);
while($row = mysqli_fetch_array($data))
{
echo '<div style="margin-top:-30px;"><main class="wrapper wrapper--content" ui-view="">
<article class="news-header">
<a href="/community/article/21340/habboxs-summer-weekend-event" class="news-header__link news-header__banner">
<figure class="news-header__viewport">
<img src="'.$row["thumbnail"].'" alt="'.$row["thumbnail"].'" class="news-header__image news-header__image--thumbnail">
</figure>
</a>
<a href="'.$row["link"].''.$row["category"].'" class="news-header__link news-header__wrapper">
<h2 class="news-header__title">'.$row["title"].'</h2>
</a>
<aside class="news-header__wrapper news-header__info">
<time class="news-header__date">'.$row["date"].'</time>
<ul class="news-header__categories">
<li class="news-header__category">
'.$row["category"].'
</li>
</ul>
</aside>
<p class="news-header__wrapper news-header__summary">'.$row["description"].'</p>
</article>
</main>
</div>';
}
mysqli_close($con);
}
?>
</div>
</div>
<?php
include("footer.php");
?>
</body>
</head>
</html>

Try:
header("Location: index?id=".$id);

As php.net says you need to use exit after header
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
so use this code:
header('Location: /index?id='.$row['id']);
exit;

Use this code:
header('Location: index?id='.$row['id']);
exit;

Related

MySQL Database row in a Button

I have a database for my ToDo App which has following cloumns:
| ID | ShortDescription | Description | Date | Status |
I already can add a Task to the Datatable and can see it in phphmyadmin.
I have following code till now:
$id = mysql_real_escape_string($_GET['id']);
$out = 'SELECT * FROM ToDo1 WHERE `id` = '.$id.' LIMIT 1';
$result = mysqli_query($link, $out);
$row= mysqli_fetch_array($result);
?>
<div id= "OutShortDescription">
<?php
echo $row['ShortDescription'];
?>
</div>
<div id= "OutDescription">
<?php
echo $row['Description'];
?>
</div>
<div id= "OutDate">
<?php
echo $row['Date'];
?>
</div>
<div id= "OutStatus">
<?php
echo $row['Status'];
?>
</div>
Now I want to put every ID row on a own Site.
For that I want to make a table of Buttons (Buttonnumber=ID).
On this Button should only be shown the ShortDescription and when I click it I want to go to a the Site which matches to the Button.
Can someone help me?
EDIT
okay thanks now I have this code but it wont work:
<?php
$dbname= 'Groups';
$dsn = 'mysql:host=localhost;dbname='.$dbname;
$user = 'root';
$pass = '';
$db = new PDO($dsn, $user,$pass);
$query = "SELECT * FROM groups2 WHERE id = :id LIMIT 1";
$ps = $db->prepare($query);
$ps->bindParam(':id', $id);
$ps->execute();
$row = $ps->fetch(PDO::FETCH_ASSOC);
?>
<div class="searchwindow">
<?php
$data = $link->query('SELECT * FROM Groups2');
foreach($data as $row) {
echo '<p><input type="button" onclick="window.location = All_Groups.php?id=' . $row['ID'] . ' value='.$row['ShortDescription'].' /></p>';
}
I have now following code
<div data-role="page" id="SearchPage" data-title="SearchPage">
<div data-role="header">
<h1>Search</h1>
</div>
<div data-role="content">
<div data-role="header">
<form>
<fieldset data-role="controlgroup" data-type="horizontal" data-mini="true" align="center" id="selectMenu">
<select name="selectStatus" id="selectStatus">
<option value="0">Status</option>
<option value="1">Done</option>
<option value="2">In Progress</option>
</select>
</fieldset>
</form>
</div>
<?php
$dbname= 'Groups';
$dsn = 'mysql:host=localhost;dbname='.$dbname;
$user = 'root';
$pass = '';
$db = new PDO($dsn, $user,$pass);
$query = "SELECT * FROM groups2 WHERE id = :id LIMIT 1";
$ps = $db->prepare($query);
$ps->bindParam(':id', $id);
$ps->execute();
$row = $ps->fetch(PDO::FETCH_ASSOC);
?>
<div class="searchwindow">
<?php
$data = $link->query('SELECT * FROM Groups2');
foreach($data as $row) {
$path = $row['ID'];
$description = $row['ShortDescription'];
echo ("<form action='All_Groups.php?id=$path'><button type='submit' value='$description'/>$description</form>" );
}
?>
</div>
</div>
<div data-role="footer" data-position="fixed">
<div data-role="navbar">
<ul>
<li>Search</li>
<li>New</li>
<li>More</li>
</ul>
</div><!-- Ende navbar -->
</div><!-- Ende footer -->
</div>
And this is my All_groups.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Unbenanntes Dokument</title>
</head>
<body>
<?php
$servername ="localhost";
$username = "root";
$password = "";
$dbname = "Groups";
$link = mysqli_connect($servername, $username, $password, $dbname);
if (!$link) {
die('Verbindung nicht möglich : ' . mysqli_error($link) );
}
?>
<?php
$row="";
$Date="";
$Status="";
$ShortDescription="";
$Description="";
mysqli_select_db($link, "groups");
?>
</div>
<?php
$id = mysql_real_escape_string($_GET['id']);
$out = "SELECT * FROM groups2 WHERE ID = '$id' ";
$result = mysqli_query($link, $out);
$id = mysqli_fetch_array($result);
?>
<div id= "OutShortDescription">
<?php
echo $id['ShortDescription'];
?>
</div>
<div id= "OutDescription">
<?php
echo $id['Description'];
?>
</div>
<div id= "OutStatus">
<?php
echo $id['Status'];
?>
</div>
<div id= "OutDate">
<?php
echo $id['Date'];
?>
<div data-role="footer" data-position="fixed">
<div data-role="navbar">
<ul>
<li>Search</li>
<li>New</li>
<li>More</li>
</ul>
</div><!-- Ende navbar -->
</div>
</body>
</body>
</html>
First of all, don't use the mysql_* methods! Use PDO or mysqli_* instead.
Below, I'm pasting your example query, using PDO:
$dsn = 'mysql:host=localhost;dbname='.$dbname;//$dbName is the name of your database
$user = 'root';
$pass = '123';//use your login information here
$db = new PDO($dsn, $user,$pass);
$query = "SELECT * FROM ToDo1 WHERE id = :id LIMIT 1";
$ps = $db->prepare($query);
$ps->bindParam(':id', $id)
$ps->execute();
$row = $ps->fetch(PDO::FETCH_ASSOC);
Now, to get your button, you don't need to use jquery:
<?php
$path = $row['ID'];
$description = $row['ShortDescription'];
echo "<form action='your/site/$path'><button type='submit' value='$description'/>$description</form>"
?>
Another option is use the onclick:
<?php
$path = $row['ID'];
$description = $row['ShortDescription'];
echo "<input type=\"button\" onclick=\"location.href='your/site/$path'\" value=\"$description\" />";
?>
The \ before " is a escape, so PHP will print the character " and not interpret it as the end of your string.
Advice: Try to avoid mix HTML and PHP, in general this is a bad practice.

How do i use $_GET to check whether the value of the sub category is in a category?

I am making a forum system to strengthen my php and make a website for a community that i have. I do not know how to check if the sub category i have selected is inside the specified category for example we have localhost/forum/sub_category.php?cat=1&sub_cat=1 what i want to know is to figure out if a user tries to set the category id to 3 and the sub_category to 4 and the sub_category id does not exist. How do i use $_GET to check for that, then show the user a message saying that the specified sub category does not exist. Here's My Code:
<?php
include '../inc/dbc.php';
include '../inc/functions.php'
?>
<?php
if(isset($_GET['user']) && !empty($_GET['user'])) {
$username = $_GET['user'];
} else {
$username = $_SESSION['username'];
}
$my_name = $_SESSION['username'];
$firstname = getuser($username, 'firstname');
$lastname = getuser($username, 'lastname');
?>
<!DOCTYPE html>
<html>
<head>
<title>EWC Forums</title>
<link rel="stylesheet" type="text/css" href="css/index.css">
</head>
<body>
<?php include 'header.php';?>
<div class='main'>
<div class='body'>
<div class='left'>
<?php
if (isset($_GET['cat']) && isset($_GET['sub_cat'])) {
$cat_query = mysqli_query($mysqli, "SELECT * FROM categories Where");// this is not done yet
} else if ($_GET['sub_cat'] == 0) {
$msg = 'That Sub Category Was Not Found In Our Database';
} else {
?>
<div class='message'><?php echo $msg;?></div>
<?php
}
?>
</div>
<div class='right'>
</div>
<div class='clear'></div>
</div>
</div>
</body>
</html>
This is the main page that shows the categories and the sub_categories:
<?php
include '../inc/dbc.php';
include '../inc/functions.php'
?>
<?php
if(isset($_GET['user']) && !empty($_GET['user'])) {
$username = $_GET['user'];
} else {
$username = $_SESSION['username'];
}
$my_name = $_SESSION['username'];
$firstname = getuser($username, 'firstname');
$lastname = getuser($username, 'lastname');
?>
<!DOCTYPE html>
<html>
<head>
<title>EWC Forums</title>
<link rel="stylesheet" type="text/css" href="css/index.css">
</head>
<body>
<?php include 'header.php';?>
<div class='main'>
<div class='body'>
<?php
if(loggedIn() == false) {
?>
<div class='mbli'>You Are Not Logged In Right Now. Click Here To Login</div><br>
<?php
}
?>
<div class='forum'>
<div class='tools'>
<?php
$sql = mysqli_query($mysqli, "SELECT * FROM users WHERE rank = 'Administrator' ");
$res = mysqli_num_rows($sql);
if ($sql == 1) {
?>
<div class='forummenu'>
<i class=''></i> New Category
<i class=''></i> New Sub Category
</div>
<?php
}
?>
</div>
<?php
$check_forum = mysqli_query($mysqli, "SELECT * FROM categories");
while ($run = mysqli_fetch_array($check_forum)) {
$cat_id = $run['cat_id'];
$creator = $run['creator'];
$cat_name = $run['name'];
$create_date = $run['create_date'];
$activated = $run['activated'];
?>
<div class='cat'>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;border-style:solid;border-width:1px;overflow:hidden;}
.tg .tg-7ht0{background-color:#f07075;color:#ffffff}
</style>
<table>
<tr class="cat_head">
<th class="tg-7ht0"><b><?php echo $cat_name;?></b><i><?php echo $create_date;?></i></th>
<th class="tg-7ht0">Threads</th>
<th class="tg-7ht0">Posts</th>
<th class="tg-7ht0">Latest Posts</th>
</tr>
<?php
$check_subcat = mysqli_query($mysqli, "SELECT * FROM subcategories WHERE cat_id= '$cat_id' ");
while ($run_sub = mysqli_fetch_array($check_subcat)) {
$sub_cat_id = $run_sub['sub_cat_id'];
$creator_subcat = $run_sub['creator'];
$name_sub = $run_sub['name'];
$sub_desc = $run_sub['sub_desc'];
$create_date_sub = $run_sub['create_date'];
?>
<tr class='sub_cat'>
<td class="tg-7ht0"><div class='sub_img'><img src="http://minotar.net/helm/<?php echo $creator_subcat;?>/32"></div><div class='sub_body'><a href='sub_category.php?cat=<?php echo $cat_id;?>&sub_cat=<?php echo $name_sub;?>'><div class='sub_tit'><b><?php echo $name_sub; ?></b><div class='desc'><?php echo $sub_desc;?></div></div></a><i class='date'><?php echo $create_date_sub; ?></i></div></td>
<td class="tg-7ht0">0</td>
<td class="tg-7ht0">0</td>
<td class="tg-7ht0">Nub picture</td>
</tr>
<?php
}
?>
<div class='clear'></div>
</table>
</div>
<?php
}
?>
</div>
</div>
</div>
</body>
</html>
Also if there's another way to do this please suggest it, but i do prefer this one. And if you need more code just ask.
Try use this :
EDIT: with the sub categories screenshot on comments :
<?php
if (isset($_GET['cat']) && isset($_GET['sub_cat'])) {
$cat_query = mysqli_query($mysqli, "SELECT * FROM SubCategoryTableName WHERE sub_cat_id='".$_GET['sub_cat']."' AND cat_id ='".$_GET['cat']."'");// this is not done yet
// Check if number of ROWS are zero/sub category notfound! .
if(mysqli_num_rows($cat_query)) == 0)
{
// show error and die
die('The requested sub/category not found.');
}
} else if ($_GET['sub_cat'] == 0) {
$msg = 'That Sub Category Was Not Found In Our Database';
} else {
?>
Please note this code are work , but always must secure the inputs that requested from users.
I don't know if your id's will go further up automatically otherwise you just put a check statement to see if the cat and sub cat are the correct number and not too high or low.
If you do depend on your database then you could ask a query to see if it exists or not or ask it to give the latest id in the database and use this then to check if your id is lower than that.
I hope that I understood your question correctly here. Don't forget to validate your GET request btw ;)
Thanks for all the help, because of you guys i figured how to fix the problem, it may not be the correct way but it's close. Here's my code:
<?php
include '../inc/dbc.php';
include '../inc/functions.php'
?>
<?php
if(isset($_GET['user']) && !empty($_GET['user'])) {
$username = $_GET['user'];
} else {
$username = $_SESSION['username'];
}
$my_name = $_SESSION['username'];
$firstname = getuser($username, 'firstname');
$lastname = getuser($username, 'lastname');
?>
<!DOCTYPE html>
<html>
<head>
<title>EWC Forums</title>
<link rel="stylesheet" type="text/css" href="css/index.css">
</head>
<body>
<?php include 'header.php';?>
<div class='main'>
<div class='body'>
<?php
if(isset($_GET['cat']) && isset($_GET['sub_cat'])) {
$sub = $_GET['sub_cat'];
$cat = $_GET['cat'];
$sql = mysqli_query($mysqli, "SELECT * FROM subcategories WHERE sub_cat_id = '$sub' AND cat_id = '$cat' ");
if (!$sql) {
$msg = 'Sorry We Kept Looking, But We Found Nothing ;-;';
} else {
if (mysqli_num_rows($sql) == 0) {
$msg = 'Ask An Admin';
} else {
?>
<?php
while ($row = mysqli_fetch_array($sql)) {
?>
<div class='cat'>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;border-style:solid;border-width:1px;overflow:hidden;}
.tg .tg-7ht0{background-color:#f07075;color:#ffffff}
</style>
<table>
<tr class="cat_head">
<th class="tg-7ht0"><b><?php echo $row['name'];?></b><i><?php echo $row['create_date'];?></i></th>
<th class="tg-7ht0">Views</th>
<th class="tg-7ht0">Replies</th>
<th class="tg-7ht0">Latest Posts</th>
</tr>
<?php
$thread_query = mysqli_query($mysqli, "SELECT * FROM threads WHERE sub_cat_id = $sub ");
while ($run = mysqli_fetch_array($thread_query)) {
$thread_id = $run['thread'];
$thread_author = $run['creator'];
$thread_title = $run['name'];
$thread_date = $run['create_date'];
?>
<tr class='sub_cat'>
<td class="tg-7ht0"><div class='sub_img'><img src="http://minotar.net/helm/<?php echo $thread_author; ?>/32"></div><div class='sub_body'><a href=''><b><?php echo $thread_title; ?></b></a > created by <a href='profile.php?user=<?php echo $thread_author;?>'><?php echo $thread_author;?></a> at <?php echo $thread_date; ?></div></td>
<td class="tg-7ht0">0</td>
<td class="tg-7ht0">0</td>
<td class="tg-7ht0">Nub picture</td>
</tr>
<?php
}
}
?>
<div class='clear'></div>
</table>
</div>
<?php
}
}
} else {
?>
<div class='message'><?php echo $msg; ?></div>
<?php
}
?>
<div class='clear'></div>
</div>
</div>
</body>
</html>

Trying to edit records with sql queries but only allows me to edit one record

I am trying to edit records with sql queries but it only lets me edit one record. I try to update projectname and projectnr. When I try to update both records none of them gets updated.Whenever I try to update projectname it allows me to change it. Projectnr won't update when I try that one alone.
include("dbconfig.php");
// $connection = mysql_connect('localhost', 'root', '');
// mysql_select_db('projectsync');
if( isset($_GET['edit']))
{
$id = $_GET['edit'];
/*$result = mysql_query("SELECT * FROM projecten WHERE projectnr='$id'");
while($rows = mysql_fetch_array($result)){
$projectnr= $rows['projectnr'];
$projectnaam= $rows['projectnaam'];
} */
$query = "SELECT * FROM projecten WHERE projectnr='$id'";
$projecten = $conn->prepare($query);
try {
$projecten->execute(array());
$projecten->setFetchMode(PDO::FETCH_ASSOC);
foreach($projecten as $project){
$projectnr = $project['projectnr'];
// $email = $consultant['email'];
// $admin = $consultant['admin'];
$projectnaam = $project['projectnaam'];
}
}
catch(PDOException $e){
echo "<script>$('Er iets is misgegaan, wilt u opnieuw proberen alstublieft!');</script>";
}
//$rows = mysql_fetch_array($result);
//$res = $conn->prepare("SELECT * FROM klant WHERE klantnr='$id'");
//$row = $res->fetch(PDO::FETCH_ASSOC);
}
if( isset($_POST['newProject']))
{
$newProject = $_POST['newProject'];
$id = $_POST['projectnr'];
/*$sql = "UPDATE klant SET naam='$newUsername', admin= '$newAdmin', password= '$newPass', username= '$newName'
WHERE klantnr='$id'";
$row= mysql_fetch_array($res);
$res = mysql_query($sql)
or die("Could not update".mysql_error());
*/
try {
$query = "UPDATE projecten SET projectnaam='$newProject' WHERE projectnr='$id'";
$data = $conn->prepare($query);
$data->execute();
$row = $data->fetch(PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
if(isset($_GET['delete']))
{
$id = $_GET['delete'];
//$res= mysql_query("SELECT * FROM klant WHERE klantnr='$id'");
//$row= mysql_fetch_array($res);
$res = $conn->prepare("SELECT * FROM klant WHERE klantnr='$id'");
$row = $res->fetch(PDO::FETCH_ASSOC);
try {
include("dbconfig.php");
$sql = "DELETE FROM klant WHERE klantnr='$id'";
$conn->exec($sql);
echo "<script>alert('User successfully deleted.');</script>";
header("refresh: 0.4; url=manage.php");
}
catch(PDOException $e) {
echo $sql . "<br />" . $e->getMessage();
}
}
?>
<!DOCTYPE html>
<html lang="nl">
<head>
<meta http-equiv="Content-Type"
content="text/html";
charset="UTF-8">
<title>Beheer gebruikers</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<header>
<center>
<img src="images/project-sync.png" /><br />
<nav>
<ul>
<li>
Admin
</li>
<li>
Mijn Declaraties
</li>
<li>
Declareren
</li>
<li>
Projecten
</li>
<li>
Declaraties
</li>
<li>
Manage Users
</li>
<li>
Logout
</li>
</ul>
</nav>
</center>
</header>
<div class="main">
<center>
<div class="loginRegisterBox">
<form action="editp.php" method="POST" name="loginform" class="form-4" style="width: 300px">
<p>Projectnr: <input type="text" name="projectnr" value="<?php echo $projectnr; ?>"></p>
<p>Projectnaam <input type="text" name="newProject" value="<?php echo $projectnaam; ?>"></p>
<p><input type="submit" name="submitProject" value=" Update "/></p>
</form>
</div>
</center>
</div>
</body>
</html>

Why the query runs again when i reload the page and can not click on the post button to insert any data

I am making a medical related site in php. When a patient logged in and he did not post any thing but he refreshes the page the query retrieve the old records again which is already inserted kindly help
This is my code for
Patient_dashboard.php
<?php
session_start();
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$ufn = "";
$uln = "";
$q2 = "";
$post="";
$query;
$query2="";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $connection )
{
die('Could not connect: ' . mysql_error());
}
$database = mysqli_select_db($connection,"medical_network");
if (!$database) {
die("Database selection failed: " . mysql_error());
}
if(!isset($_SESSION['username'])) {
header('Location: index.php');
}
require_once("Functions/functions.php");
$posts = get_user_posts($_SESSION['id']);
$uploadDir = 'Reports Images/'; //Image Upload Folder
if(isset($_POST['submit'])&& !empty($_POST['submit'])){
$fileName = $_FILES['image']['name'];
$tmpName = $_FILES['image']['tmp_name'];
$fileSize = $_FILES['image']['size'];
$fileType = $_FILES['image']['type'];
$filePath = $uploadDir . $fileName;
$filename = $fileName;
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$date = date_create();
$fileName= date_timestamp_get($date).".".$ext;
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$post = mysqli_real_escape_string($connection,($_POST['np_text']));
//$date = date("Y/m/d");
date_default_timezone_set('Asia/Karachi');
$date = date('Y-m-d H:i:s');
//echo $date;
$query = "INSERT INTO post ";
$query .= "(p_pic,p_content,p_date,u_id) VALUES (";
$query .= "'{$filePath}','{$post}','{$date}','{$_SESSION['id']}');";
//echo $query . " " .$date;
$result_set = mysqli_query($connection,$query);
if (!$result_set) {
die("Database query failed: " . mysqli_error($connection));
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Medical Network</title>
<link href="css/custom.css" rel="stylesheet" />
<script>
function performClick(node) {
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, false);
node.dispatchEvent(evt);
}
</script>
</head>
<body>
<div class="topmenu">
<div class="search">
<form>
<input type="text" placeholder="Search" value="">
</form>
</div>
<div id='cssmenu'>
<ul>
<li><a href='#'><span>Home</span></a></li>
<li><a href='#'><span>Profile</span></a></li>
<li><a href='logout.php'><span>Logout</span></a></li>
</ul>
</div>
</div>
<div class="main">
<div class="left-colum">
<div class="profileinfo">
<div class="profilepic">
<?php echo "<img class='getPic' src='{$_SESSION['pic']}' />" ?>
</div>
<div class="personal-info">
<ul>
<li><a href='#'><span><?php echo $_SESSION['fname']." ".$_SESSION['lname']; ?></span></a></li>
<li><a href='#'><span>Edit Profile</span></a></li>
</ul>
</div>
</div>
<div class="importantlinks">
<h4>Important Links</h4>
<ul>
<li><a href='#'><span>Make Appointment</span></a></li>
<li><a href='#'><span>Search Doctor</span></a></li>
<li><a href='logout.php'><span>Logout</span></a></li>
</ul>
</div>
<div class="pages">
<h4>Pages</h4>
</div>
</div>
<div class="middle-colum">
<div id="feeds">
<div class="new-post">
<ul>
<form method="post" action="patient-dashboard.php" enctype="multipart/form-data">
<li><label for="newpostfield"><img src="images/status.png" width="14" height="14"> Update Status</label></li>
<li> <img src="images/photo.png" width="14" height="14"> Add Photo
</li>
<input type="file" id="myFile" name="image" size="4
000000" accept="image/gif, image/jpeg, image/x-ms-bmp, image/x-png" />
</ul>
<br />
<textarea rows="1" cols="40" id="newpostfield" name="np_text" placeholder="Whats on your mind ?" required="required" ></textarea>
<input type="submit" value="Post" name="submit" id="postbtn"/>
</form>
</div><!--End of feed-item -->
<br />
<div class="posts-feed">
<h3 id="postsheading" class="post-heading">Posts</h3>
<?php while($post = mysqli_fetch_array($posts)){
$counter = 0;
?>
<div class="post">
<div class="poster-pic">
<?php echo "<img src='{$_SESSION['pic']}' height='60' width='60' />" ?>
</div><!--End of poster-pic -->
<div class="post-content">
<div id="poster-name"><?php echo $_SESSION['fname']." ".$_SESSION['lname']; ?><span></span></div>
<div id="content">
<p id="post-text">
<?php
echo $post['p_content']."<br/>";
$img = $post['p_pic'];
echo "<a href='#'> <img src='{$post['p_pic']}' height='300' width='300' >"
?>
</p>
</div><br />
<div id="post-responses" class="top-border">
Comment
</div>
</div><!--End of post-content -->
</div><!--End of post -->
<?php $counter++;
} ?>
</div><!--End of feeds -->
</div>
<div class="right-colum">
<div class="heading">
<h4>Recommended Pages</h4>
</div>
</div>
</body>
</html>
This is function.php where i am retrieving the records.
<?php
function get_user_posts($id) {
global $connection;
$query2 = "SELECT p_pic, p_content,u_id ";
$query2 .= "FROM post ";
$query2 .= "WHERE u_id= " . $id ." ";
$query2 .= "ORDER BY p_id DESC ";
$query2 .= "LIMIT 5";
$result_set1 = mysqli_query( $connection,$query2);
if (!$result_set1) {
die("Database query failed: " . mysqli_error($connection));
}
// REMEMBER:
// if no rows are returned, fetch_array will return false
if ($result_set1) {
return $result_set1;
} else {
return NULL;
die("query faild..... in get post");
}
}
?>
You are calling $posts = get_user_posts($_SESSION['id']); outside the if statement so it is showing the records as on every reload it is fetching the data. if you want to display the records only if it is posted then put it inside the if statement
if(isset($_POST['submit'])&& !empty($_POST['submit'])){
//your code
$posts = get_user_posts($_SESSION['id']);
}
and please do check the if the variables are available or not.
Please change input name attribute
it should be:
use any name Except submit
also change
if(isset($_POST['submit'])&& !empty($_POST['submit'])){

mysqli - Commands out of sync; you can't run this command now

I am continuosly getting this error:
Commands out of sync; you can't run this command now
I don't know why is this happening and none of the preivous questions are helping.
This is my code:
User.php
public static function GetUserFullName($username){
if(Utilities::IsValid($username)){
$username = Utilities::SafeString($username);
Database::OpenConnection();
$query = Database::$databaseConnection->prepare("SELECT Name FROM user WHERE Username = ?") or die(Database::$databaseConnection->error);
$query->bind_param("s", $username);
$result = $query->execute();
Database::CloseConnection();
if($result){
$query->bind_result($name);
$query->fetch();
$query->close();
return $name;
}
}else return -1;
}
Skill.php
public static function UpdateSkills($id, $skill, $action){
if(Utilities::IsValid($id) && Utilities::IsValid($skill) && Utilities::IsValid($action)){
$id = Utilities::SafeString($id);
$skill = Utilities::SafeString($skill);
$action = Utilities::SafeString($action);
Database::OpenConnection();
if($action == 'i'){
$skill = str_replace(" ", "", $skill);
$db = Database::$databaseConnection;
$skills = explode(",", $skill);
$query = "";
foreach ($skills as $s){
$query .= "INSERT INTO skill (User_ID,Skill) VALUES({$id},'{$s}');";
}
$result = $db->multi_query($query);
echo $db->error;
Database::CloseConnection();
if($result) return 1;
else return -1;
}else if($action == 'd'){
$query = Database::$databaseConnection->prepare("DELETE FROM Skill WHERE Skill = ? AND User_ID = ?");
$query->bind_param("si", $skill,$id);
$result = $query->execute();
Database::CloseConnection();
if($result && $query->num_rows >0) return 1;
else return -1;
}
}
return -1;
}
header.php
<?php
require_once 'Classes/UserLogin.php';
require_once 'Classes/User.php';
$user_fullname = User::GetUserFullName($_SESSION["username"]);
?>
<header>
<div class="welcome_area">
<p>
Welcome, <b><?php echo $user_fullname; ?> </b>
</p>
</div>
<div class="menu">
<nav>
<ul>
<li>My Profile
<ul>
<li><div>My Questions</div>
</li>
<li><div>Settings</div>
</li>
<li style="margin-bottom: 5px;"><div>Logout</div>
</li>
</ul>
</li>
<li>Inbox
</li>
<li>Notifications
</li>
</ul>
</nav>
</div>
</header>
<section id="container">
<br />
<div id="logo"></div>
<div id="content">
profile.php
<?php
require_once "Classes/User.php";
require_once "Classes/Skill.php";
require_once "Classes/UserLogin.php";
if(!UserLogin::IsLoggedIn("username")) header("location: login.php");
$user_details = User::GetUserDetails($_SESSION["username"]);
echo Skill::UpdateSkills(11, "programmer,designer", "i");
?>
<!DOCTYPE html>
<html>
<head>
<title>Help Exchange</title>
<link rel="stylesheet" href="css/base.css" />
<link rel="stylesheet" href="css/profile.css" />
<link rel="stylesheet" href="css/user.css" />
<link rel="stylesheet" href="css/widgets.css" />
<script src="js/jquery.min.js"></script>
<script src="js/profile.js"></script>
</head>
<body>
<script>
var user_details = eval(<?php echo $user_details; ?>);
var about = user_details.About;
</script>
<?php require_once 'admin/header.php';?>
Please help me :'(

Categories