how to display all data on a webpage - php

I wrote this code to comment system on my webpage. But i want to keep showing all data on web page while another people do comment and see another people's comment
include 'connection.php';
$con1= new connection();
$db=$con1-> open();
$qry= "INSERT INTO post (content) VALUES ('".$_POST["commentEntered"]."')";
$db->exec($qry);
if(isset($_POST['Submit'])) {
if ($con1->query($qry) === TRUE) {
echo "Your Comment Successfull Submited";
} else {
echo "Error: " . $qry . "<br>" . $con1->error;
}
$sql = 'SELECT * FROM post';
$q = $db->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
$con1->close();
}
if ($_POST)
echo "<h2> Your Comment Successfully Submitted</h2> <br> ".$_POST['commentEntered']."<br>";
}
?>

after your select, inside your if($_POST) write this
while ($row = $q->fetch()) {
foreach($row as $key=>$val){
if (!is_numeric($key)) echo "<p>$key=>$val</p>";
}
}
EDIT i'm not 100% sure you can close the connection and still do a ->fetch, (I think you can but i've never tried it) so you may have to move your connection close after this (but I think you'll be alright), also I am not sure if setFetchMode will return duplicate numbered keys or not so as a precaution I have filtered for them you may not need to

Related

Matching user code with database and redirecting winners / losers

I am new to...well everything. Bear with me.
I have a website that has a textbox for user input ( a code they receive). When they submit, it sends the code to a PHP file, which then checks the code against a database. If it matches the winner code, it redirects the user to a specific page. Losers, are redirected to a loser page.
That works!
However, I'm now trying to redirect users to a third page, if their code matches a different table of codes, but I can't figure out the if else statements. Can anyone help a poor doodle like myself? Thanks!
Here's what I got:
// Connect to your MySQL database
$dbhst = "localhost";
$dbnme = "blah";
$bdusr = "blaaah";
$dbpws = "blahblahblacksheep";
// Using PDO to connect
$conn = new PDO('mysql:host='.$dbhst.';dbname='.$dbnme, $bdusr, $dbpws);
// Getting variables
$answer = $_POST['answer'];
$questionID = $_POST['questionID'];
// Comparing answers
try {
$stmt = $conn->prepare("SELECT * FROM Winners WHERE Winners='" . $answer . "' LIMIT 0,1");
$stmt->execute();
$result = $stmt->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
// echo 'Congrats, you've entered a correct code';
header("Location: https://get-a-brik.myshopify.com/pages/8522");
}
} else {
// echo 'Your code did not win. Please try again.';
header("Location: https://get-a-brik.myshopify.com/pages/5551");
exit;
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
You can use an if ... else if ... else statement:
if (... user is winner ...) {
header("Location: https://get-a-brik.myshopify.com/pages/8522");
} else if (... user is looser ...) {
header("Location: https://get-a-brik.myshopify.com/pages/5551");
} else {
header("Location: winner page");
}

PHP prevent URL input to delete row in database

I’m working on a blog website where the idea is that the current user that is logged in can edit and delete their own posts. I finally got it to work, but my question is how I can prevent that a user can write the following input in the URL and do the same actions as my delete.php action.
(Example) Manual URL input with topic_id:
/delete.php?del=133
Do anyone know how I can edit my existing code or know a better solution to the problem I will be much grateful!
This is how my code looks:
Profile.php:
if (#$_GET['id']) {
$check_d = mysql_query("SELECT * FROM users WHERE id ='".$_GET['id']."'");
while ($row_d = mysql_fetch_assoc($check_d)) {
echo "<div class='spacer'></div><h2 class='headertext'>Inlägg skapade av : ".$row_d['username']."</h2>";
$check_u = mysql_query("SELECT * FROM topics WHERE topic_creator='".$row_d['username']."' ORDER BY topic_id DESC");
while ($row_u = mysql_fetch_assoc($check_u)) {
$id = $row_u['topic_id'];
echo "<tr>";
echo "<td class='postmain'><a href='topic.php?id=$id' class='links'>".$row_u['topic_name']."<br /></a></td>";
echo "<td class='postmain'><p class='text'>".$row_u['topic_creator']."</p><br /></td>";
echo "<td class='postmain'><p class='text'>".$row_u['date']."</p><br /></td>";
if($_SESSION['username'] === $row_u['topic_creator']) {
echo "<td class='postmain'><a href='edit.php?edit=$id'><button>Redigera</button></a>";
echo "<a href='delete.php?del=$id'><button>Ta bort</button></a></td>";
}
echo "</tr>";
}
}
}
The highlighted code shows that only the current session (user) who made the post can edit and delete their own posts.
Delete.php:
if (isset($_GET['del'])) {
//getting id of the data from url
$id = $_GET['del'];
//deleting the row from table
$sql = "DELETE FROM topics WHERE topic_id='$id'";
$res = mysql_query( $sql );
//redirecting to the display page
header("Location:admin.php");
}
Using isset function is solution here . The isset function will check that whether user clicked the delete/modify link or not(i.e he pasted delete.php directly in link) . So your code will only execute when user clicks the link .
if (isset($_GET['del']))
{
// your profile.php code here
}
else
{
// error message
}
You can use the same $_SESSION logic to ensure anyone accessing the delete.php has the appropriate permissions.
if (isset($_GET['del'])) {
//getting id of the data from url
$id = $_GET['del'];
// Get the author for the specified post to ensure they are permitted to do so
// TODO
// Check that the author is the same as the $_SESSION user
if($_SESSION['username'] === $postAuthor) {
//deleting the row from table - FIX THIS (see below)
$sql = "DELETE FROM topics WHERE topic_id='$id'";
$res = mysql_query( $sql );
} else {
// User is not authorized, create error handling
// TODO
}
//redirecting to the display page
header("Location:admin.php");
}
Unrelated, beware of SQL injection. Bobby Tables is a good guide and you should not be using the mysql_ functions and should be using prepared statements.

PHP Check mysqli_num_rows not working

I've searched thoroughly and nothing seems to be working; I have this code here which posts into my database but the problem is I am trying to run a conditional which checks if a row exists using the mysqli_num_rows function, but it is not actually working. I have tried many different versions and other functions as well such as mysqli_fetch_row, but nothing seems to work. Here is my code:
if (!empty($_POST)) {
$db_conx="";
$name = $_POST['name'];
$module = $_POST['module'];
$secret = $_POST['secret'];
$uid1 = $dmt->user['uid'];
$queryA = "INSERT INTO table_a (uid1,name,module,secret) VALUES ('$uid1','$name','$module','$secret')";
$resultA = mysqli_query($db_conx,$queryA);
$queryB = "SELECT 1 FROM table_a WHERE name='$name' LIMIT 1";
$resultB = mysqli_query($db_conx,$queryB);
$resultC = mysqli_query($db_conx,$queryB);
$query = mysqli_query($db_conx,"SELECT * FROM table_a WHERE name='$name'");
if (empty($name)||empty($module)||empty($secret)) {
echo "Oops! Can't leave any field blank <br />";
exit();
} elseif(mysqli_num_rows($query) > 0){
echo "name already exists.";
exit();
} elseif ($db_conx->query($queryA) === TRUE) {
echo "New record created successfully.";
exit();
} else {
echo "Error: " . $queryA . "<br>" . $db_conx->error;
exit();
}
}
As you can see the query appears to run but indeed does not do what it's told.
The first line of code inside your IF is destroying the variable you are using to hold the database connection
if (!empty($_POST)) {
$db_conx=""; // get rid of this line
So basically nothing using the mysqli API will work.
ALSO:
Add these as the first 2 lines of a script you are trying to debug
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
as you are obviously not readng your php error log

Cant track error cause in PHP page updating a MS SQL database

Simple PHP page (I'm no PHP expert, just learning) to update a MS SQL database. The following code generates an error that I dont know how to solve.
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE USERID='".$_REQUEST['user_id']."';";
if ($result = odbc_exec($dbconnect, $query)) {
echo "// Success!";
}
else {
echo "// Failure!";
}
odbc_close($dbconnect);
//End Update
This fails every time in the "if ($result ..." section
However, if I run virtually the same code
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL = '89990.jpg' WHERE USERID='80'";
if ($result = odbc_exec($dbconnect, $query)) {
// Success!
}
else {
// Failure!
}
odbc_close($dbconnect);
//End Update
It works just fine. I have echoed the $query string to the screen and the string is the same for both. I can't figure out why it fails in one and not the other?
Also weird is when I use a parameterized query such as
include '/connections/SFU.php';
$query = "UPDATE dbo.Person SET PhotoURL=? WHERE USERID=?";
if ($res = odbc_prepare($dbconnect,$query)) {
echo "Prepare Success";
} else {
echo "Prepare Failed".odbc_errormsg();
}
$uid = $_REQUEST['user_id'];
$fn = $file["name"];
echo "query=".$query." userid=".$uid." filename=".$fn;
if ($result = odbc_exec($res, array($fn, $uid))) {
echo "// Success!";
}
else {
echo odbc_errormsg();
echo "// Failure!";
}
odbc_close($dbconnect);
The query fails in the prepare section above, but fails in the odbc_exec section below:
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL=? WHERE USERID=?";
if ($res = odbc_prepare($dbconnect,$query)) {
echo "Prepare Success";
} else {
echo "Prepare Failed".odbc_errormsg();
}
$uid = "80";
$fn = "samplefile.jpg";
echo "query=".$query." userid=".$uid." filename=".$fn;
if ($result = odbc_exec($res, array($fn, $uid))) {
echo "// Success!";
}
else {
echo odbc_errormsg();
echo "// Failure!";
}
odbc_close($dbconnect);
In all cases I do not get any odbc_errormsg ().
Remove the extra ; from your query.
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE
USERID='".$_REQUEST['user_id']."';";
^
So your query should be,
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE
USERID='".$_REQUEST['user_id'];
Also have practice of using odbc_errormsg() so you can have a better idea why your query gets failed.
Warning: Your code is vulnerable to sql injection attacks!

Refresh PHP page once only when called

I have a php which would check for certain value if it exists in a mysql database. If the value does not exists, it would simply add the value and refresh the page once to load the page again and now it has a value in the database, would go ahead to add other values. How do I refresh page just once when it is called ?
<?php
$sname = "W3 schools C# tutorials";//$_POST["sitename"];
$stype = "C#";//$_POST["sitetype"];
$saddy = "www.w3schools.com";//$_POST["siteaddress"];
$scomm = "W3 schools C# tutorials";//$_POST["sitecomment"];
$conn = mysql_connect("localhost","root","password");
if(!$conn){
die("Could not connect: ".mysql_error());
} else {
mysql_select_db("bookmarks",$conn);
$rs = mysql_query("select TypeId from bookmarktypes where TypeName = '$stype'");
$row = mysql_fetch_array($rs);
if($row > 0 ){
//Data found, continue to add...
} else {
//No data... insert a valid one
$rs = mysql_query("insert into bookmarktypes (TypeName) values ('$stype')");
if (!$rs){
die('Error: ' . mysql_error());
} else {
//echo "inserted new type data...";
}
//echo "</html>";
}
}
mysql_close($conn);
//Refresh page once
?>
There's the comment to refresh page below after mysql close command.
Refresh it right after insert with
header('Location: url here');
exit;
Btw, read a little about sql injections
Also - mysql_close() is pointless there.
if(check=1)
{
echo "\"<meta http-equiv=\"refresh\" content=\"2;url=http://yourwebsite.com/\">\"\n";
}
if you need to print the data that you just have entered try this
header('Location: YourShowDataPage.php?id='.$_POST['id_dataEntered'])
mi apologizes if is wrong , im a begginer

Categories