So I'm currently creating a Online Game and already got the login and registering working but now I'm working on submitting Stats such as health and a player's level and retrieving that.
So in this PHP file I'm able to retrieve the info of a certain player but I don't know how to submit new stats into a certain player's row. I'm still learning PHP so please help me out.
<?php
// Database Things =========================================================
$host = "localhost";
$user = "lyth_com_Spillnk";
$password = "INTERESTED?";
$dbname = "lythumn_com_Spillnk";
mysql_connect($host, $user, $password) or die("Can't connect into database");
mysql_select_db($dbname)or die("Can't connect into database");
// =============================================================================
$Act = $_GET["Act"];// what is action, Submit or Retrieve?
$nick = $_GET["User"];
$health = $_GET["Health"];
$level = $_GET["Level"];
$xcood = $_GET["X"];
$ycood = $_GET["Y"];
if($Act == "Retrieve"){
$SQL = "SELECT * FROM Stats WHERE Username = '" . $nick . "'";
$result_id = #mysql_query($SQL) or die("DB ERROR");
$total = mysql_num_rows($result_id);
if($total) {
$datas = #mysql_fetch_array($result_id);
echo ($datas["Health"], $datas["Level"], $datas["X"], $datas["Y"]);
}
}
if($Act == "Submit"){
$SQL = "SELECT * FROM Stats WHERE Username = '" . $nick . "'";
$result_id = #mysql_query($SQL) or die("DB ERROR");
$query = "INSERT INTO Stats (Username, Health, Level, X, Y) VALUES('$nick', '$health', '$level', $'xcood', $'ycood')";
mysql_query($query) or die("ERROR");
mysql_close();
echo "Submitted";
}
// Close mySQL Connection
mysql_close();
?>
It's mostly concercing this piece of code:
if($Act == "Submit"){
$SQL = "SELECT * FROM Stats WHERE Username = '" . $nick . "'";
$result_id = #mysql_query($SQL) or die("DB ERROR");
$query = "INSERT INTO Stats (Username, Health, Level, X, Y) VALUES('$nick', '$health', '$level', $'xcood', $'ycood')";
mysql_query($query) or die("ERROR");
mysql_close();
echo "Submitted";
}
As you are able to see I already retrieve the Index of where the player's stats are located so how do I insert values there?
Thanks in advance!
Related
i'm very new to PHP so i apologize if this is a simple fix but i'm experiencing a weird issue. I've created a website that uses facebook authentication. once they login, their information gets stored in a database I've created. i then created some functions that display the users facebook image and name on the profile page of my website. problem is sometimes it shows, and other times i receive this error. "notice: undefined index: fbid in /PATH/ on line 132". Here is the code.
<div id="userInfo" class="userInfo">
<h1> <?php
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName = "facebooklogin";
$conn = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT first_name, last_name, picture FROM users WHERE
oauth_uid = '".$_SESSION['fbid']."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo " ". $row["first_name"]." ". $row["last_name"]."";
}
} else {
echo "0 results";
}
$conn->close();
?></h1>
userData.php
<?php
session_start();
include 'dbConfig.php';
$userData = json_decode($_POST['userData']);
if(!empty($userData)){
$oauth_provider = $_POST['oauth_provider'];
$_SESSION['fbid'] = $userData->id;
var_dump($_SESSION);
$prevQuery = "SELECT * FROM users WHERE oauth_provider =
'".$oauth_provider."' AND oauth_uid = '".$userData->id."'";
$prevResult = $db->query($prevQuery);
if($prevResult->num_rows > 0){
$query = "UPDATE users SET first_name = '".$userData-
>first_name."', last_name = '".$userData->last_name."', email =
'".$userData->email."', gender = '".$userData->gender."', locale =
'".$userData->locale."', picture = '".$userData->picture->data->url."',
link = '".$userData->link."', modified = '".date("Y-m-d H:i:s")."'
WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid =
'".$userData->id."'";
$update = $db->query($query);
}else{
$query = "INSERT INTO users SET oauth_provider =
'".$oauth_provider."', oauth_uid = '".$userData->id."', first_name =
'".$userData->first_name."', last_name = '".$userData->last_name."',
email = '".$userData->email."', gender = '".$userData->gender."',
locale = '".$userData->locale."', picture = '".$userData->picture-
>data->url."', link = '".$userData->link."', created = '".date("Y-m-d
H:i:s")."', modified = '".date("Y-m-d H:i:s")."'";
$insert = $db->query($query);
}
}
?>
It seems that you don't have the variable set when you use it in the query.
Check it before the query, like:
if (isset($_SESSION['fbid'])) {
$sql = "SELECT first_name, last_name, picture FROM users WHERE
oauth_uid = '".$_SESSION['fbid']."'";
$result = $conn->query($sql); } else {
// not logged in
}
To check the values of $_SESSION, just do a var_dump($_SESSION) and you can see what is set.
I want to do a query to get the last id (int) in a table to create a new row with that last id + 1 but actually this just put all rows with the same id
my code:
<?php
$servername = "localhost";
$user = "root";
$pass = "dbpass";
$dbname = "site";
$mail = $_POST['mail'];
$password = $_POST['password'];
// Create connection
$conn = mysqli_connect($servername, $user, $pass, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sqlID = "SELECT MAX(id) FROM `login`;";
if ($result = mysqli_query($conn, $sqlID)) {
$id = mysqli_fetch_row($result);
}
settype($id, "int");
$id = $id + 1;
$sql = "INSERT INTO login (`id`,`mail`,`password`)
VALUES ('".$id."','".$mail."','".$password."');";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
mysqli_fetch_row returns always an array, also if there is only 1 element. So the MAX(id) in in $row[0].
Fixing this, you also don't need to use settype.
If your id is autoincrement, change this:
$sql = "INSERT INTO login (`id`,`mail`,`password`)
VALUES ('".$id."','".$mail."','".$password."');";
to:
$sql = "INSERT INTO login (`mail`,`password`)
VALUES ('".$mail."','".$password."');";
Then get rid of all code from $sqlID to $id + 1; (for tidyness)
Kindly need assistance in my coding, I have a database named Books with table called OpenBooks I would like to add the html form which are user inputs into the table and echo confirmation.
<?php
$Title = $_POST['Title'];
$Author = $_POST['Author'];
$Series = $_POST['Series'];
$Price =$_POST['price'];
//database connection
$connection = mysqli_connect('localhost', 'root', '','books');
if(!$connection){
die("Database connection failed");
}
$query = "INSERT INTO OpenBooks(Title,Author,series,price)";
$query .= " VALUES ('$Title', '$Author', '$series', '$price')";
$result = mysqli_query($connection, $query);
}
?>
if (!$result) {
die('Invalid query: ' . mysql_error());
}
else {
echo 'yay, done';
}
And you need $Price instead of price and rest of variables starting from capital letter.
So I get this error:
Problem updating record. MySQL Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE KittenID = '2''
But then in my code:
<?php
if(isset($_POST['Modify']))
{
$connection = mysql_connect("Deleted the login info");
// Check connection
if (!$connection)
{
echo "Connection failed: " . mysql_connect_error();
}
else
{
//select a database
$dbName="Katz";
$db_selected = mysql_select_db($dbName, $connection);
//confirm connection to database
if (!$db_selected)
{
die ('Can\'t use $dbName : ' . mysql_error());
}
else
{
$KittenID = $_POST["KittenID"];
$KittenAge = $_POST['KittenAge'];
$Name = $_POST['Name'];
$Email = $_POST['Email'];
$Gender = $_POST['Gender'];
$Personality = $_POST['Personality'];
$Activity = $_POST['Activity'];
$Comments = $_POST['Comments'];
$query = "UPDATE Kittenzz
SET KittenID = '$KittenID',
KittenAge = '$KittenAge',
Name = '$Name',
Email = '$Email',
Gender = '$Gender',
Personality = '$Personality',
Activity = '$Activity',
Comments = '$Comments',
WHERE KittenID = '$KittenID'";
$res = mysql_query($query);
if ($res)
{
echo "<p>Record Updated<p>";
}
else
{
echo "Problem updating record. MySQL Error: " . mysql_error();
}
}
}
mysql_close($connection);
}
?>
It makes no sense, I've read those lines of code for an hour, I cannot see the problem. It should run. Can anyone lend me fresh eyes?
Remove the comma near '$comments'
$query = "UPDATE Kittenzz
SET KittenID = '$KittenID',
KittenAge = '$KittenAge',
Name = '$Name',
Email = '$Email',
Gender = '$Gender',
Personality = '$Personality',
Activity = '$Activity',
Comments = '$Comments'
WHERE KittenID = '$KittenID'";
it may possible that in connection username and password in required.
like this :-
$connection = mysql_connect("localhost","username","password");
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 1 year ago.
I've been creating a booking system, and creating appointments, but my SQL statement is not working. I've been trying to find a solution but to no avail.
Listed below is my php code. My first SQL statement works perfectly and returns the correct ClientID, however, the second SQL statement does not insert it all into the database. I have done var_dumps on result, returning bool(false), as well as mysqli_error on the result, returning null.
My error message at the end only displays the echo'd message, and not the mysqli_error or error number also.
(Note: some values are changed/removed to protect data)
<?php
session_start();
if(! $_SESSION['Username']) {
header("location:Index.php");
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "";
$tablename = "appointmentinformation";
$tablenamed = "clientinformation";
$connection = mysqli_connect("$servername", "$username", "$password", "$dbname") or die("Could not connect to the database");
$clientusername = $_SESSION['Username'];
$sql = "SELECT ClientID FROM $tablenamed WHERE Username = '$clientusername' LIMIT 1";
$results = mysqli_query($connection, $sql);
if (! $results) {
echo ("Could not select the data : " . mysql_error());
} else {
$datarows = mysqli_fetch_row($results);
$clientid = $datarows[0];
}
$date = $_POST["Date"];
$month = $_POST["Month"];
$year = $_POST["Year"];
$time = $_POST["Time"];
$length = $_POST["Length"];
$date = stripslashes($date);
$month = stripslashes($month);
$year = stripslashes($year);
$time = stripslashes($time);
$length = stripslashes($length);
$date = mysqli_real_escape_string($date);
$month = mysqli_real_escape_string($month);
$year = mysqli_real_escape_string($year);
$time = mysqli_real_escape_string($time);
$length = mysqli_real_escape_string($length);
$query = "INSERT INTO appointmentinformation (ClientID, Length, Date, Month, Year, Time, Price) VALUES ('$clientid', '$length', '$date', '$month', '$year', '$time', '$price')";
$result = mysqli_query($connection, $query);
if ($result) {
header("Location:UserCP.php");
} else {
echo ("Could not insert data : " . mysqli_error($result) . " " . mysqli_errno());
}
?>
$query = "INSERT INTO appointmentinformation (ClientID, Length, Date, Month, Year, Time, Price) VALUES ('$clientid', '$length', '$date', '$month', '$year', '$time', '$price')";
$result = mysqli_query($connection, $query);
if ($result) {
header("Location:UserCP.php");
} else {
echo ("Could not insert data : " . mysqli_error($result) . " " . mysqli_errno());
}
The result returned from mysqli_query is null. This sends you down the else branch of the code. Then you coded mysqli_error($result) which equals mysqli_error(null).
The documentation I have read says to initialize a variable with a "link" to the query. You did this with:
$connection = mysqli_connect("$servername", "$username", "$password", "$dbname") or die("Could not connect to the database");
You now want to code it as mysqli_error($connection) and mysqli_errno($connection).
An additional suggestion. Add this code right after your mysqli_connect statement.
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}