MySQL is not receiving information. Using MySQLi extension - php

<?php
include_once("php_includes/check_login_status.php");
if($user_ok != true){
header("location: login.php");
exit();
}
?>
<?php
$id = "SELECT id FROM users WHERE username='$log_username'";
if(isset($_POST["signupbtn"])) {
if ($log_username) {
/// getting data from submitted form into local variables
$x = preg_replace('#[^a-z 0-9]#i', '', $_POST['xbox']);
$p = preg_replace('#[^a-z 0-9]#i', '', $_POST['psn']);
$s = preg_replace('#[^a-z 0-9]#i', '', $_POST['steam']);
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR GAMER PROFILES
$sqli = "SELECT username FROM player WHERE xbox='$x' LIMIT 1";
$query = mysqli_query($db_conx, $sqli);
$x_check = mysqli_num_rows($query);
// -------------------------------------------
if ($x_check > 0){
echo "Xbox Gamer-Tag already linked to a user on this website";
exit();
} else if (is_numeric($x[0])) {
echo 'Xbox Gamer-Tag cannot begin with a number';
exit();
}
$sqli = "SELECT username FROM player WHERE psn='$p' LIMIT 1";
$query = mysqli_query($db_conx, $sqli);
$p_check = mysqli_num_rows($query);
// -------------------------------------------
if ($p_check > 0){
echo "PSN User already linked to a user on this website";
exit();
} else if (is_numeric($p[0])) {
echo 'PSN User cannot begin with a number';
exit();
}
$sqli = "SELECT username FROM player WHERE steam='$s' LIMIT 1";
$query = mysqli_query($db_conx, $sqli);
$s_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if ($s_check > 0){
echo "Steam account already linked to a user on this website";
exit();
} else if (is_numeric($s[0])) {
echo 'Steam account cannot begin with a number';
exit();
} else { $sqli = "INSERT INTO player (id, username, xbox, psn, steam, ip, created, lastupdated, notecheck)
VALUES ('$id','$log_username','$x','$p','$s','$ip',NOW(),NOW(),NOW())";
$query = mysqli_query($db_conx, $sqli);
}
echo "Gamer Profiles Updated";
exit();
if (!file_exists("p_player/$log_username")) {
mkdir("p_player/$log_username", 0755);
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="templates/default/style/style.css">
<style type="text/css">
#profiles{
margin-top:24px;
}
#profiles > div {
margin-top: 12px;
}
#profiles > input,select {
width: 200px;
padding: 3px;
background: #F3F9DD;
}
#profiles {
font-size:18px;
padding: 12px;
}
</style>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
</head>
<body>
<?php include_once("templates/default/template_pageTop.php"); ?>
<div id="pageMiddle">
<h3>Gamer Profiles</h3>
<form action="player.php" method="POST" name="profiles">
<div>Xbox Gamer-tag: <input type="text" name="xbox"></div>
<div>PSN User: <input type="text" name="psn"></div>
<div>Steam User: <input type="text" name="steam"></div>
<input type="submit" name="signupbtn">
</form>
</div>
<?php include_once("templates/default/template_pageBottom.php"); ?>
</body>
</html>
The $log_username variable comes from the top php script and every thing is fine with it as I can echo the variable and comes back with the logged user on this page.
so basicaly nothing is being written to my database on submitting the button and I am really stumped with it tbh. I am using the MySQLi extension within php 5 as I have been following a tutorial on things and have came to the end of the tutorial and now I am by myself. I was going to included a shot of my database below to prove that the names on the database is fine but with the fact that my rep is 9 I can't add one to make your lives easier as you need to b 10.
have I got a } in the wrong place or labeling something MySQL when it should be MySQLi.
When I submit the form the mkdir is made in the folder and I get sent to the page with the echo "Gamer Profiles Updated"
Thank you to anyone who tries to solve this problem out I have.
I have been trying to do this for hours tbh and from what i have done everything checks fine and it should be working in theory but it just doesn't work. Thank you once again for looking at this and I look forward to your responses.

Change:
$id = "SELECT id FROM users WHERE username='$log_username'";
to:
$result = mysqli_query($db_conx, "SELECT id FROM users WHERE username='$log_username'") or die(mysqli_error($db_conx));
$row = mysqli_fetch_assoc($result) or die ("$log_username not found");
$id = $row['id'];

Related

php Real-Time form post submit

Let me explain what I want to.
I want to add a value in a list with db add without page change when I input in form, and click submit.
but in this code, I must refresh one more time to add, and also added twice a time.
How can I do that?
<?php
$conn = mysqli_connect('127.0.0.1','MYID','MYPASS','MYDB');
$sql = "SELECT * FROM MYTABLE";
$rs = mysqli_query($conn, $sql);
$list = '';
while($row = mysqli_fetch_array($rs)) {
$list = $list."<li>{$row['title']}</li>";
}
$article = array(
'title' => 'Welcome!',
'description' => 'Hello, Web!'
);
if (isset($_GET['id'])){
$filtered_id = mysqli_real_escape_string($conn, $_GET['id']);
$sql = "SELECT * FROM topic WHERE id={$filtered_id}";
$rs = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($rs);
$article['title'] = $row['title'];
$article['description'] = $row['description'];
}
if ($_POST['title'] != null){
$sql_in = "INSERT INTO topic (title, description, created) VALUES ('{$_POST['title']}', '{$_POST['description']}', NOW())";
$rs_in = mysqli_query($conn, $sql_in);
if ($rs_in === false) {
$msg = mysqli_error($conn);
} else {
$msg = 'Success.';
}
} else {
$msg = 'Fill in';
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>WEB</title>
</head>
<body>
<h1>WEB</h1>
<ol>
<?=$list?>
</ol>
<details>
<summary>Create</summary>
<form action="./index.php" method="POST">
<p><input type="txt" name="title" placeholder="title"></p>
<p><textarea name="description" placeholder="description"></textarea></p>
<p><input type="submit"></p>
<p><?=$msg?></p>
</form>
</details>
</body>
</html>
<h2><?=$article['title']?></h2>
<?=$article['description']?>
</body>
</html>
In php realtime isn't a thing but there is a workaround you can use events services like pusher https://pusher.com/docs and receive the events in client side instantly .
there other website offers this so do your search before choosing them also you can always build your event server in node.js , c# , go

PHP check if form is already submitted using num rows

I know the problem, But I cannot seem to fix it, and I was hoping someone on here could steer me in the right direction, What I want to do is check to see if a user has already submitted a correct answer to a question before checking it against the answers database and inserting it into the database, Simply to stop the same question being answered multiple times, I am a rookie with MYSQLi and not great at it, still learning it.
What I currently have so far is :
$mysqli = new mysqli($host,$username,$password,$database);
if($mysqli -> connect_error)die($mysqli->connect_error);
$questionID = $_POST['id'];
$userAnswer = $_POST['answer'];
$userAnswer = strtolower(trim($userAnswer));
$questionValue = $_POST['qValue'];
$teamName = $_SESSION['user_email'];
$user_id = "SELECT t.teamID,t.questionGroupID FROM team as t WHERE t.teamName ='$teamName'";
$result2 = $mysqli->query($user_id);
if ($result2->num_rows > 0) {
// output data of each row
while($row = $result2->fetch_assoc()) {
$userID = $row["teamID"];
}
}
$query = "SELECT answers FROM answers WHERE questionID=?";
$statement = $mysqli->prepare($query);
$statement ->bind_param('i', $questionID);
$statement->execute();
$statement->bind_result($answer);
//checking the database to see if the current question is there from the current user/teamName
if ($result = mysqli_query($mysqli, "SELECT * FROM submissions where teamID='$teamName' and questionID='$questionID'")) {
/* determine number of rows result set */
$row_cnt = mysqli_num_rows($result);
/* close result set */
mysqli_free_result($result);
}
/* close connection */
mysqli_close($mysqli);
//checking to see if it returns a result
if(($row_cnt)= 0){
while ($statement->fetch()) {
if ($answer != $userAnswer) {
echo '<br><br><div class="alert alert-danger"><h5>
<strong>Sorry!</strong> the answer is incorrect! Please Try again!.</h5>
</div>';
"<h3>Sorry the answer is incorrect! Please Try again!</h3><br>";
//return to previous Page
echo 'Return to Question ';
$statement->free_result();
$sql = "INSERT INTO `submissions`(`submissionsID`, `teamID`, `questionID`, `answer`,`qValue`,`status`,`timestamp`) VALUES (null,'$teamName','$questionID','$userAnswer','0','Wrong',NOW())";
if (mysqli_query($mysqli, $sql)) {
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
} else {
echo '<br><br><div class="alert alert-success"><h5>
<strong>Success!</strong> Correct Answer, Good Luck with the Next </h5>
</div>';
echo "<a href='questionList.php' class='btn btn-success btn-block'>Continue with other questions! </a>";
$statement->free_result();
//MySqli Insert Query
$sql = "INSERT INTO `submissions`(`submissionsID`, `teamID`, `questionID`, `answer`,`qValue`,`status`,`timestamp`) VALUES (null,'$teamName','$questionID','$userAnswer','$questionValue','Correct',NOW())";
if (mysqli_query($mysqli, $sql)) {
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
}
}
}else{
echo '<br><br><div class="alert alert-warning"><h5>
<strong>Already Answered!</strong> Good Luck with the Next </h5>
</div>';
echo "<a href='questionList.php' class='btn btn-warning btn-block'>Continue with other questions! </a>";
}
I have tested it most ways, What I need to do is run a check to see if the current logged in user has already answered the questionID correctly, I am using a num_rows to see if its greater than 0, If it is greater than 0, they have answered it.
So my question is, Am I approaching it correctly, and what approach should I take?
It's a good approach. Try using
$row_cnt = $result->num_rows;
rather than
$row_cnt = mysqli_numrows($result);
also don't forget that $row_cnt will equal -1 in the event of any form of query error so you should check for that before assuming all values that arn't 0 are valid.
I would suggest you to see natural language processing (NLP) techniques. If your answer is uni-gram (one word). This approach is ok. If you are dealing with n-grams of size more than 1,ie long sentences or paragraphs Then your approach will not work well. Answers can be written in different ways. So i would suggest some semantic methods like LSA(Latent Semantic Analysis) or simple vector representation models.
I can't think of any other methods to solve this problem.Try NLP methods. Will give you awesome results.
I took a different approach to trying to get it to work and finally got it working, Just wanted to post my solution and thank everyone for helping.
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/modern-business.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Navigation -->
<?php include_once('navigation.php');
// establishing the MySQLi connection
require_once('connection-test.php');
$mysqli = new mysqli($host,$username,$password,$database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$questionID = $_POST['id'];
$userAnswer = $_POST['answer'];
$userAnswer = strtolower(trim($userAnswer));
$questionValue = $_POST['qValue'];
$teamName = $_SESSION['user_email'];
$user_id = "SELECT t.teamID,t.questionGroupID FROM team as t WHERE t.teamName ='$teamName'";
$result2 = $mysqli->query($user_id);
if ($result2->num_rows > 0) {
// output data of each row
while($row = $result2->fetch_assoc()) {
$userID = $row["teamID"];
}
}
$query = "SELECT answers FROM answers WHERE questionID=?";
$statement = $mysqli->prepare($query);
$statement ->bind_param('i', $questionID);
$statement->execute();
$statement->bind_result($answer);
$statement->store_result();
?>
<div class="container">
<!-- Page Content -->
<hr>
<?php
if ($result4 = $mysqli->query("SELECT * FROM submissions where teamID='$teamName' and questionID='$questionID'"))
{
// display records if there are records to display
if ($result4->num_rows > 0)
{
echo '<br><br><div class="alert alert-warning"><h5>
<strong>Already Answered!</strong> Good Luck with the Next </h5>
</div>';
echo "<a href='questionList.php' class='btn btn-warning btn-block'>Continue with other questions! </a>";
}
// if there are no records in the database, display an alert message
else
{
while ($statement->fetch()) {
if ($answer != $userAnswer) {
echo '<br><br><div class="alert alert-danger"><h5>
<strong>Sorry!</strong> the answer is incorrect! Please Try again!.</h5>
</div>';
"<h3>Sorry the answer is incorrect! Please Try again!</h3><br>";
//return to previous Page
echo 'Return to Question ';
$statement->free_result();
$sql = "INSERT INTO `submissions`(`submissionsID`, `teamID`, `questionID`, `answer`,`qValue`,`status`,`timestamp`) VALUES (null,'$teamName','$questionID','$userAnswer','0','Wrong',NOW())";
if (mysqli_query($mysqli, $sql)) {
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
} else {
echo '<br><br><div class="alert alert-success"><h5>
<strong>Success!</strong> Correct Answer, Good Luck with the Next </h5>
</div>';
echo "<a href='questionList.php' class='btn btn-success btn-block'>Continue with other questions! </a>";
$statement->free_result();
//MySqli Insert Query
$sql = "INSERT INTO `submissions`(`submissionsID`, `teamID`, `questionID`, `answer`,`qValue`,`status`,`timestamp`) VALUES (null,'$teamName','$questionID','$userAnswer','$questionValue','Correct',NOW())";
if (mysqli_query($mysqli, $sql)) {
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
}
}
}
}
// show an error if there is an issue with the database query
else
{
echo "<strong>Error:</strong>" . $mysqli->error;
}
?>
<?php include_once('footer.php'); ?>
</div>
<!-- /.container -->
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>

Create Profile Information Page in PHP/MySQL/PDO

Hi I am having an issue creating a profile page using PDO- I can get the one to work that is in the old mysql but I can't figure out how to change the data over to PDO- I have been at this for weeks now and just at a loss. Please be nice I am VERY new to all of this. Here is the code that works- the old way
<?php
require_once('connection.php');
$id=$_SESSION['SESS_MEMBER_ID'];
$result3 = mysql_query("SELECT * FROM member where mem_id='$id'");
while($row3 = mysql_fetch_array($result3))
{
$fname=$row3['fname'];
$lname=$row3['lname'];
$address=$row3['address'];
$contact=$row3['contact'];
$picture=$row3['picture'];
$gender=$row3['gender'];
}
?>
And this is what I have tried to come up with but I just get a blank screen
<?php
require_once('connectpdo.php');
$id=$_SESSION['SESS_MEMBER_ID'];
$result3 = $db->prepare("SELECT * FROM member where mem_id='$id'");
$row3 = $stmt->fetch (PDO::FETCH_ASSOC);
{
$fname=$row3['fname'];
$lname=$row3['lname'];
$address=$row3['address'];
$contact=$row3['contact'];
$picture=$row3['picture'];
$gender=$row3['gender'];
}
?>
The login works fine in both old MySql and in the PDO but I can not seem to get the user profile to come up in PDO
//Create query
$result = $conn->prepare("SELECT * FROM member WHERE username= :xtxt AND password= :ztzt");
$result->bindParam(':xtxt', $username);
$result->bindParam(':ztzt', $password);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
//Check whether the query was successful or not
if($rows > 0) {
//Login Successful
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['loggedin'] = true;
$_SESSION['SESS_MEMBER_ID'] = $member['mem_id'];
$_SESSION['SESS_FIRST_NAME'] = $member['firstname'];
$_SESSION['SESS_LAST_NAME'] = $member['password'];
$_SESSION['SESS_USERNAME'] = $member['username'];
session_write_close();
header("location: home.php");
exit();
I get PHP Warning: mysql_fetch_assoc() expects parameter 1 to be resource, object given in...from this line
$member = mysql_fetch_assoc($result);
I get Undefined variable: stmt in ...& PHP Fatal error: Call to a member function fetch() on a non-object in...from this line
$row3 = $stmt->fetch (PDO::FETCH_ASSOC);
As I mentioned before I am very new at this, and I have spent many weeks researching doing multiple tutorials, and trying to figure all this out. I was just learning MySql when I was getting the depreciated errors and now I'm switching over to PDO, I know in the future I will need to pull information from multiple databases for one logged in user. I am not using functions or classes. Thanks in advance, my dogs will appreciate your help.
Okay I solved it! I am going to post the code for any one else having this issue #Fred, Thanks!
And I do know that the code is really different because I managed to get it on my test site, in my login process page I changed this code:
// query
$result = $conn->prepare("SELECT * FROM customers WHERE username=:hjhjhjh AND customers_password= :asas");
$result->bindParam(':hjhjhjh', $username);
$result->bindParam(':asas', $customers_password);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
if($rows > 0) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
$_SESSION['customers_id']=$row['customers_id'];
$_SESSION['SESS_CUSTOMERS_KENNEL'];//kwaon ang id sang may tyakto nga username kag password
header("location: http://localhost:8888/ShowMyDog/newtemplate/index.php?action=account");
}
And in the page I wanted the profile to show up I changed the code to:
<?Php
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
} else {
echo "Please log in first to see this page.";
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<?Php
error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR);
require "config.php"; // Database connection details.
$customers_id=$_SESSION['loggedin']; // Collecting one record with for user
$count=$dbo->prepare("select * from customers where customers_id=:customers_id");
$count->bindParam(":customers_id",$customers_id,PDO::PARAM_INT,1);
if($count->execute()){
echo " Success <br>";
$row = $count->fetch(PDO::FETCH_ASSOC);
print_r($row);
echo "<hr>";
echo "<br>Admin id = $row[customers_id]";
echo "<br>username = $row[username]";
echo "<br>password=$row[customers_password]";
echo "<br>kennel=$row[customers_kennel]";
echo "<br>first name=$row[customers_firstname]";
echo "<br>last name=$row[customers_lastname]";
echo "<br>email address=$row[customers_email_address]";
echo "<br> postcode=$row[customers_postcode]";
echo "<br> street address=$row[customers_street_address]";
echo "<br> gender=$row[customers_gender]";
}
?>
</body>
</html>
I know it is still a bit messy, but like I said I'm new at this

jquery mobile and append/injecting HTML

check this out.
<?php
include('configdb.php');
if(isset($_POST['submit'])) {
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$query = "SELECT * FROM user WHERE email='$email' AND password='$password' AND com_code IS NULL";
$result = mysqli_query($mysqli,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
if( $num_row == 1 ) {
$_SESSION['user_name']=$row['username'];
header("Location: member.php");
exit;
}
else {
?>
<script type="text/javascript">
$('.error').append('This will display if there was an error');
</script>
<?php
}
}
?>
<div data-role="content" data-theme="b"><p class="error"></p></div>
So as a newbie dev I'm playing around and trying to figure out why certain things work and why other's don't.
The idea here is that if the database check fails jQuery injects a message into the paragraph tag with the class of error. (You can't do that with PHP echo can you?)
Works great until I add the jQuery Mobile framework. Then all it does is refresh and nothing updates. I can't figure out why the Mobile framework is preventing this from happeneing.
Any advice would be appreciated. Thanks guys.
Why can't you use PHP to do it? It looks pretty trivial:
<?php if (isset($num_row) && $num_row == 0) { ?>
<div data-role="content" data-theme="b">
<p class="error">This will display if there was an error</p>
</div>
<?php } ?>

If MySQL Result Empty display a confirm box

I'm using some crazy mixture of PHP/JavaScript/HTML/MySQL
$query = "SELECT * FROM faculty WHERE submitted = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row != NULL) {
// Display a confirm box saying "Not everyone has entered a bid, continue?"
}
// If confirmed yes run more queries
// Else nothing
What is the best way to have this confirm box display, before completing the rest of the queries?
if($row != NULL) {
?>
<script>alert("not everyone has submitted their bid.");</script>
<?php
}
or
<?php
function jsalert($alert_message){
echo "<script type='text/javascript'>alert('".$alert_message."');</script>";
}
if($row!=null){
jsalert("Not everyone has submitted their bid.");
}
?>
You can't do this in 1 continuous block, as all of the PHP will execute before the confirm (due to server vs. client).
You will need to break these into 2 separate steps and have the client mediate between them:
part1.php:
<?php
$query = "SELECT * FROM faculty WHERE submitted = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if ($row != NULL) { ?>
<form id="confirmed" action="part2.php" method="post">
<noscript>
<label>Not everyone has entered a bid, continue?</label>
<input type="submit" value="Yes">
</noscript>
</form>
<script type="text/javascript">
if (confirm("Not everyone has entered a bid, continue?")) {
document.getElementById('confirmed').submit();
}
</script>
<?
} else {
include_once('part2.php');
}
?>
part2.php:
<?php
// assume confirmed. execute other queries.
?>
$query = "SELECT * FROM faculty WHERE submitted = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row != NULL) {
// more queries here
} else {
echo "<script>alert('Empty result');</script>";
}
Play with this code and you will get it to work eventually. I know you are not looking for just alertbox , instead you are looking for something like "yes or no" informational box. So check this out.
<?php
?>
<html>
<head>
<script type="text/javascript">
function displayBOX(){
var name=confirm("Not everyone has entered a bid, continue?")
if (name==true){
//document.write("Do your process here..")
window.location="processContinuing.php";
}else{
//document.write("Stop all process...")
window.location="stoppingProcesses.php";
}
}
</script>
</head>
<?php
$query = "SELECT * faculty SET submitted = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row != NULL) {
echo "<script>displayBox();</script>";
}
?>

Categories