Refresh PHP page once only when called - php

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

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");
}

how to display all data on a webpage

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

headers not working PHP

Page 1 abc.html.. on submit it will jump to this PHP page .
This is page PHP1.php here i am trying to validate user input if name and id in in data he will be forwarded to fill out second part of registration if not it will just give error.
<?php
session_start();
$_SESSION["acb"] = "good";
$_SESSION['team'] = $_POST['team_name'];
$con = mysql_connect("localhost", "user", "password");
if (!$con)
{die('Could not connect: ' . mysql_error());}
mysql_select_db("mydbName");
if(isset($_POST['team_name'],$_POST['id'])){
$team_name = mysql_real_escape_string($_POST['team_name']);
$id = mysql_real_escape_string($_POST['id']);
if (!empty($team_name)) {
$result= mysql_query("SELECT COUNT(`teamname`) FROM `table` WHERE `teamname`='$team_name' AND `id`='$id'");
$team_result = mysql_fetch_row($result);
if ($team_result[0] == '0') { //if does not exist print failed.
echo 'Varification failed';
} else {
header('Location: http://www.abc.com/REGISTERpart2.php');
}} } ?>
RegisterPART2.php is where i am checking my session exist or not (the one i started in last file). if not i want to redirect back to form one and fill that first then come to registration part 2
`<?php
session_start();
$name = $_SESSION['team']; //a value stored in session which i used on this page
if (($_SESSION["abc"] !== 'good')) {
header('Location: http://www.abc.com/page1.html'); //take back to stage 1 coz user did not fill first part.
}
else{
echo $name. 'you have completed register process part one you may continue!';
}
?>
If you're using the new MySQL version (MySQLi), so the first page will become:
<?php
session_start();
$_SESSION["acb"] = "good";
$_SESSION['team'] = $_POST['team_name'];
$con = new mysqli("localhost", "user", "password", "mydbName");
if (!$con) {
die('Could not connect: ' . $con->error());
};
if (isset($_POST['team_name'],$_POST['id'])) {
$team_name = $con->real_escape_string($_POST['team_name']);
$id = $con->real_escape_string($_POST['id']);
if (!empty($team_name)) {
$result = $con->prepare("SELECT COUNT(`teamname`) FROM `table` WHERE `teamname`='$team_name' AND `id`='$id'");
$result->execute();
$result->bind_result($one,$two,$three,$etc);
$result->fetch();
if (empty($one) and empty($two) and empty($three) and empty(etc)) { // may be and/or (pick one)
echo 'Varification failed';
} else {
header('Location: http://www.abc.com/REGISTERpart2.php');
}
}
}
?>
You may use the following alternative to header.
prinf('<script>window.location = "URL HERE"</script>');
It should do the same thing as header does.

If else statement that redirects to another page

I'm terrible with PHP/SQL, so any help would be appreciated.
Basically I have a form that posts the values 'firstname' & 'surname' to another page. What I want that page to do, is check to see if the user's name is already on the table 'Members'. If it is I want it to continue loading this page, but if they aren't on the database, I want the viewer to be re-directed to an existing sign up page.
Here is the code I've been working on, I'm not sure if I'm heading in the right direction or not.
<?php
$con = mysql_connect("localhost","site","xxxxxxxx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("site", $con);
$query = "SELECT * FROM Members WHERE firstname='$_POST[firstname]' and surname='$_POST[surname]'";
$result = mysql_query($query);
if ($result==$something)
{
echo "great success"; //user continues loading page
}
else
{
echo "fail"; //user is redirected to sign up page
}
?>
This will do the trick:
<?php
$con = mysql_connect( "localhost", "site", "xxxxxxxx" );
if ( !$con ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("site", $con);
1st, remove the sql injection part at least like this:
$firstname = strip_tags( $_POST[ 'firstname' ] );
$surname = strip_tags( $_POST[ 'surname' ] );
2nd, I didn't change it, but you need to remove the * and enter only specific values you want to load. Even if those are all the values, still write them manually.
$query = "SELECT * FROM Members WHERE firstname='" . $firstname . "' and surname=' " . $surname. "'";
$result = mysql_query( $query );
3rd, you can check for row count, if you got some value, there is an entry with those variables
if ( mysql_num_rows($result) >= 1 ) {
// the page you want
} else {
// redirect user to another page
header( "Location: signup.php" ); die;
}
?>
Edit:
Think adding some unique requests to your query. What will happen if two users have identical names and surnames or if a new one wants to join, but the name and lastname is already in the db ...
if (mysql_num_rows($result) == 1)
{
echo "great success"; //user continues loading page
}
else
{
echo "fail"; //user is redirected to sign up page
}
Also, you're query is prone to SQL injection big time
$rows = mysql_num_rows($results);
if ($rows == 1)
{
echo "login successful"; //user continues loading page
}
else
{
header ('location: signup.php'); //user is redirected to sign up page
}
You can simply put a header( "Location: host/site.php" ) function call in your else branch followed by a die()
if(mysql_num_rows($result) > 0){
echo "great success"; //user continues loading page
}
else
{
echo "fail"; //user is redirected to sign up page
}
use this

Check To See A Match In MySql

I have a form which has a textbox with an attribute called ref. once this is submitted, it updates on of my fields in the database. I have this code working and fine but what i need now is for it to check if the data entered into the textbox exists in the database and if it does, then it should notify the user to choose another reference. here is my code for the php end:
$ref = mysql_real_escape_string($_REQUEST['ref']);
$id = $_GET['public'];
$con = mysql_connect("localhost", "*****", "******");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('*****', $con);
$sql = "UPDATE public SET ref = '$ref' WHERE public_id = '$id'";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo '<hr><h2>Reference Number Has Been Assigned Successfully</h2><hr>';
}
any ideas guys?
thanks
You can get the number of rows affected:
$rowsAffected = mysql_affected_rows($con);
if($rowsAffected) {
//something WAS changed!
}
else {
//NOTHING was changed ... :-(
}
Also I would watch out for Bobby Tables
You might want to use mysqli or PDO's prepared queries for what you want to do.
Based on OP's comment below:
...
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
$rowsAffected = mysql_affected_rows($con);
if($rowsAffected) {
echo '<hr><h2>Reference Number Has Been Assigned Successfully</h2><hr>';
}
else {
//show some error message?
}
}
In this case First you run a select command to search for the record with particular reference number. If the result is eof , then run insert command. If not EOF then send a warning to the user saying reference number exist and choose another one.

Categories