Stuck with trying to show tictactoe values out of mysql db - php

I am making a tictactoe game with php and mysql. It should be played by 2 players from different systems. So I have a table in mysql with a column id which goes from 1-9 and a column tictac which has a value X or O or NULL. Put a x or o in the database is working but retrieving a X or O out of the table and show it on the screen is not working. I have a config file, a class.tictactoe.php, class.game.php and an index.php. The DB connection should be in the class.tictactoe.php but I don't know how.
I am having the most trouble with this part:
function displayGame()
{
if (!$this->isOver())
{
echo "<div id=\"board\">";
$i=1;
for ($x = 0; $x < 3; $x++)
{
for ($y = 0; $y < 3; $y++)
{
require('config.inc.php');
$db = new PDO("mysql:dbname=$db_name;host=$db_host",
$db_user, $db_pass,
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
echo "<div id=\"$i\" class=\"board_cell\">";
$i++;
$query = $db->prepare('SELECT * FROM tictactoe WHERE value IS NOT NULL and id = ?');
if ($this->board[$x][$y])
$query->execute([$lookup[$key]]);
echo "<p>\"{$this->board[$x][$y]}\"</p>";
else
{
echo "<select name=\"{$x}_{$y}\">
<option value=\"\"></option>
<option value=\"{$this->player}\">{$this->player}</option>
</select>";
}
echo "</div>";
}
echo "<div class=\"break\"></div>";
}
echo "
<p align=\"center\">
<input type=\"submit\" name=\"move\" value=\"Take Turn\" /><br/>
<b>It's player {$this->player}'s turn.</b></p>
</div>";
}
else
{
if ($this->isOver() != "Tie")
echo successMsg("Congratulations player " . $this->isOver() . ", you've won the game!");
else if ($this->isOver() == "Tie")
echo errorMsg("Whoops! Looks like you've had a tie game. Want to try again?");
session_destroy();
echo "<p align=\"center\"><input type=\"submit\" name=\"newgame\" value=\"New Game\" /></p>";
}
}
function move($postdata)
{
if ($this->isOver())
return;
require('config.inc.php');
$db = new PDO("mysql:dbname=$db_name;host=$db_host",
$db_user, $db_pass,
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$postdata = array_unique($postdata);
$lookup = ['0_0'=>1, '0_1'=>2, '0_2'=>3, '1_0'=>4, '1_1'=>5, '1_2'=>6,
'2_0'=>7, '2_1'=>8, '2_2'=>9];
$query = $db->prepare('UPDATE tictactoe SET tictac = ? WHERE id = ?');
foreach ($postdata as $key => $value)
{
if ($value!=$this->player) continue;
$query->execute([$this->player, $lookup[$key]]);
if ($value == $this->player)
{
$coords = explode("_", $key);
$this->board[$coords[0]][$coords[1]] = $this->player;
if ($this->player == "X")
$this->player = "O";
else
$this->player = "X";
$this->totalMoves++;
}
}
if ($this->isOver())
return;
}
The indentation might be wrong.

Related

PHP only display last id number in last row

I'm trying to display 6 items in one page with 3 items in each row. And when the user clicks on the image link it will redirect to another page and display the id. However when the user clicks on the image it does redirect to another page but it shows the id of the last product in the last row of the page, and this is not correct. I'm not sure where I made the mistake. I hope you can look at my code and give me a hint where the mistake lies.
<?PHP
session_start();
function connect()
{
$servername = xxxxxxxx;
$username = xxxxxxxx;
$password = xxxxxxxx;
$dbname = xxxxxxxx;
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
echo 'connection is invalid';
} else {
mysqli_select_db($conn, "mytest");
}
return $conn;
}
function getData()
{
$conn = connect();
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
$startrow = 0;
} else {
$startrow = (int) $_GET['startrow'];
}
$sql = "SELECT * FROM tbl_products LIMIT $startrow, 6";
$getdata = mysqli_query($conn, $sql) or die(mysqli_error());
$cell_img = mysqli_num_rows($getdata);
$i = 0;
$per_row = 3;
echo "<table id='productTumb'><tr id='proRow'>";
$data = '';
while ($row = mysqli_fetch_assoc($getdata)) {
//echo "<a href='ProDet.html'></a>";
echo "<td><a href='test.php'><img style='vertical-align: bottom;' width='218px' height='332px' src='" . $row['products_image'] . "'/ ></a></td>";
$data .= "<td style='background-color:#FF0004'>" . $row['product_name'] . "</td>";
$product_id = $row['products_id'];
$_SESSION['id'] = $product_id;
if (++$i % $per_row == 0 && $i > 0 && $i <= $cell_img) {
echo "</tr><tr>$data</tr><tr>";
$data = '';
}
}
for ($x = 0; $x < $per_row - $i % $per_row; $x++) {
echo "<td></td>";
}
echo "</tr>";
echo "</table>";
echo 'Next >>>';
$prev = $startrow - 5;
if ($prev >= 0)
echo ' <<<< Previous';
}
?>
This line of code $_SESSION['id'] = $product_id; will set last product id to SESSION.(overwrites previous ids)
Try to add product id to the anchor href tag
while ($row = mysqli_fetch_assoc($getdata)) {
echo "<td><a href='test.php?id=".$row['products_id']."'><img style='vertical-align: bottom;' width='218px' height='332px' src='" . $row['products_image'] . "'/ ></a></td>";
......
}
In test.php file get id by below code
if(isset($_GET)){
$pid = $_GET['id'];
echo $pid;
}
hope this will helps you.

Dropdown of tables to show content

This script allows the user to choose a table from the dropdown and then displays the contents of the chosen table.
At the moment the DB connection is working.
A list of tables is shown in the dropdown.
Problem: No content from the database table is shown.
I have checked through the code and everything looks OK, but it still only seems to partially work.
<?php
//update this to your DB connection details.
$dbh = "localhost";
$dbn = "dbname";
$dbu = "dbuser";
$dbp = "dbpass";
$conn = mysql_connect($dbh,$dbu,$dbp) or die("Unable to connect do database.");
mysql_select_db($dbn, $conn) or die("Unable to select database.");
//Some vars for Order by and Limit.
if (!isset($ordBy)){
$ordBy = 1;
}
if (!isset($ps)){
$ps = 0;
}
if (!isset($ord)){
$ord = 1;
}
if ($ord == 1){
$tOrder = "ASC";
} else {
$tOrder = "DESC";
}
//Tables drop-down
$result = mysql_query("SHOW TABLES FROM $dbn") or die("Cannot list table names.");
echo "
<form name=\"table_browser\" action=\"".$PHP_SELF."\" method=\"GET\" >
<select name=\"t\" onChange=\"javascript:submit();\">
<option>Select a table</option>
";
while ($row = mysql_fetch_row($result)){
echo " <option value=".$row[0].">".$row[0]."</option>\n";
}
echo " </select>
</form>\n";
if (!isset($t)){
die("Please select a table");
}
//Get number of rows in $t and then select
$result = mysql_query("SELECT COUNT(*) FROM $t") or die("The requested table doesn't exist.");
$total = mysql_result($result,0);
$qry = "SELECT * FROM $t ORDER BY ".$ordBy." ".$tOrder." LIMIT ".($ps*20).",20 ";
if (isset($qry)) {
$result = mysql_query($qry) or die("The requested table doesn't exist.");
$i = 0;
while ($i < mysql_num_fields($result)) {
$meta = mysql_fetch_field($result);
if (!$meta) {
echo "No information available on the table<br />\n";
}
$name[$i] = $meta->name;
$i++;
}
//Display table details
echo "Rows ".($ps*20+1)." to ".((($ps+1)*20 < $total) ? (($ps+1)*20) : ($total))." of $total from table:
<b>$meta->table</b>\n<br /><br />\n";
//Count results
if ($ps > 0) {
echo "20 Previous - ";
} else {
echo "20 Previous - ";
}
if ((($ps+1)*20) < $total ){
echo "Next 20\n";
} else {
echo "Next 20\n";
}
//Column names
echo "<br /><br />\n<table>\n <tr>\n";
for ($j = 0; $j < $i; $j++){
echo " <td><b>$name[$j]</b>";
if ($ordBy == $name[$j]) {
echo "<img src=\"images/arrow$ord.gif\">";
}
echo "</td>\n";
}
echo " </tr>\n";
//Data
while ($row = mysql_fetch_array($result)){
echo " <tr onmouseover=\"this.style.background='#DDDDDD'\" onmouseout=\"this.style.background=''\">";
for ($j = 0; $j < $i; $j++){
echo "<td>".$row[$name[$j]]."</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
}
mysql_close();
?>
#gentlebreeze - my eyes hurt from trying to read that - but I can't see where you are actually setting the variable called $t - which is used to determine the table. You should have
$t = $_GET['t'];
somewhere before the line:
....if (!isset($t)){....
because you need to use it in the line:
....$result = mysql_query("SELECT COUNT(*) FROM $t"....
and you should not be using mysql_query either - old and now deprecated. You should switch to PDO and bound variables.

Query to return connecting flights given source and destination

So I have a table called "Flights" that stores the source and destination of a flight. Say you have A -> B and B -> C in a table, and you give the source as 'A' and destination as 'C', the query should return the path between these two A - > B, B -> C. I have tried this query:
$result = $mysqli -> query(
"SELECT *
FROM Flights a
JOIN Flights b
ON a.Destination = b.Source
AND '{$source}' = a.Source
AND '{$destination}' = b.Destination");
As a side note: I'm using mysqli in PHP. I have done this query in the mysql console and it returns everything I need. But if I ran this query in PHP on the example table I gave it would return B -> C only. Any ideas where I went wrong? I think it could have to do with the PHP string formatting.
<?php
if(isset($_POST['source'])){
$source = $_POST['source'];
}
if(isset($_POST['destination'])){
$destination = $_POST['destination'];
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Airport Tracking";
$table ="Flights";
$flag = 0;
// Create connection
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['source']) && isset($_POST['destination'])){
$columns= $mysqli -> query("SHOW COLUMNS FROM $table");
$sql = "SELECT *
FROM Flights a
JOIN Flights b
ON a.Destination = b.Source
AND {$source} = a.Source
AND {$destination} = b.Destination";
echo "$sql";
$result = $mysqli -> query($sql);
if($result == FALSE){
echo "<br><b>Incorrect input</b>";
$flag = 1;
}
else if($result->num_rows == 0){
echo "<br><b>Returned no results</b>";
$flag = 1;
}
}
$array = array();
$i = 0;
if(isset($_POST['source']) && $flag == 0){
// Display results
echo "<table>";
echo "<thead><tr>";
while ($row = $columns -> fetch_array(MYSQLI_BOTH)) {
echo "<th>" .$row['Field']. "</th>";
$array[] = $row['Field'];
}
echo "</tr></thead>";
while ($row = $result -> fetch_array(MYSQLI_BOTH)) {
echo "<tr>";
while ($i < sizeof($array)) {
echo "<td>" .utf8_encode($row[$array[$i]]). "</td>";
$i++;
}
echo "</tr>";
$i = 0;
}
echo "</table>";
}
$mysqli->close();
?>
That is my PHP code. I apologize because I know indenting is incorrect.

Why can't I echo all variables correctly?

Edited, please scroll down
I am trying to display 3 variables which consist of data stored in a SQL database. However, only the first gets echoed successfully (topLeftUrl). It is worth noting that the same PHP file also receives data from an input (also in the same PHP file) and stores it in the same SQL database. This code was written for testing purposes and may not be entirely safe.
//Connect
$con = mysqli_connect ("localhost","noneedtoknow","noneedtoknow","noneedtoknow");
if (mysqli_connect_errno())
{
echo "Error: ", mysql_connect_error(), "<br>";
die ();
}
//Store input in SQL database
$result = mysqli_query ($con, "SELECT * FROM edit");
$message = stripslashes ($_POST ['message']);
if ($message !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$message' WHERE id='message'"); }
$topLeftNew = ($_POST ['topLeftUrl']);
if ($topLeftNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topLeftNew' WHERE id='topLeft'"); }
$topRightNew = ($_POST ['topRightUrl']);
if ($topRightNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topRightNew' WHERE id='topRight'"); }
//First echo
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "topLeft" && $done2 == 0)
{
$topLeftUrl = $row["cont"];
}
}
echo "<input type=\"text\" name=\"topLeftUrl\" value=\"" . $topLeftUrl . "\">";
//Second echo
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "topRight" && $done3 == 0)
{
$topRightUrl = $row["cont"];
}
}
echo "<input type=\"text\" name=\"topRightUrl\" value=\"" . $topRightUrl . "\">";
//Third echo
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "message" && $done == 0)
{
echo $row["cont"];
}
}
Edit:
I updated the code, and the problem seems to have changed. For some reason, echo $messageCont; displays an old value of cont WHERE id='message'. The database itself is updated successfully, though, and I see the new value of cont once I refresh the page/re-submit the form. Why do I not see the current value of cont immediately after form submission, though? Here is the new code:
/* Before <!DOCTYPE html> */
//Connect
$con = mysqli_connect ("localhost","noneedtoknow","noneedtoknow","noneedtoknow");
if (mysqli_connect_errno())
{
echo "Error: ", mysql_connect_error(), "<br>";
die ();
}
//Query and update
$result = mysqli_query ($con, "SELECT * FROM edit");
$message = stripslashes ($_POST ['message']);
if ($message !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$message' WHERE id='message'"); }
$topLeftNew = ($_POST ['topLeftUrl']);
if ($topLeftNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topLeftNew' WHERE id='topLeft'"); }
$topRightNew = ($_POST ['topRightUrl']);
if ($topRightNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topRightNew' WHERE id='topRight'"); }
//Query again and read
$done0 = 0;
$done1 = 0;
$done2 = 0;
mysqli_data_seek ($result, 0);
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "topLeft" && $done0 == 0)
{
$topLeftUrl = $row["cont"];
$done0 = 1;
}
else if ($row["id"] == "topRight" && $done1 == 0)
{
$topRightUrl = $row["cont"];
$done1 = 1;
}
else if ($row["id"] == "message" && $done2 == 0)
{
$messageCont = $row["cont"];
$done2 = 1;
}
else null;
}
/* After <!DOCTYPE html> */
/* Form code was omitted as it works perfectly. It is in this same file, though. */
echo "<input type=\"text\" name=\"topLeftUrl\" value=\"" . $topLeftUrl . "\">";
echo "<input type=\"text\" name=\"topRightUrl\" value=\"" . $topRightUrl . "\">";
echo $messageCont;
Any help is appreciated.
Edit: I only had to replace mysqli_data_seek () with the line beginning by $result (cut/paste). Thank you.
I ran into this same problem on my site....you run multiple mysql_fetch_array() on the same query ($result)...I thought this would work on my site but this failed for all but the first of 6 while loops which all referenced the same query on my site (I'm sorry but I don't remember the exact error message in my error_log). Try condensing your 3 while loops into 1 loop, something like this:
while ($row = mysqli_fetch_array ($result)) {
if ($row["id"] == "topLeft" && $done2 == 0) {
$topLeftUrl = $row["cont"];
} else if ($row["id"] == "topRight" && $done3 == 0) {
$topRightUrl = $row["cont"];
} else if ($row["id"] == "message" && $done == 0) {
echo $row["cont"];
} else null;
}
echo "<input type=\"text\" name=\"topRightUrl\" value=\"" . $topRightUrl . "\">";
echo "<input type=\"text\" name=\"topLeftUrl\" value=\"" . $topLeftUrl . "\">";

PHP: Undefined shown on blank page

I'm trying to print/echo values from previous file however instead of showing error, all that is shown is 'Undefined' on a blank page. I've researched and tried several method but nothing works. Please help.
<?PHP
$user_name = "root";
$password = "";
$database = "leadership_program";
$server = "localhost";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
if (isset($_POST['survey_id'])) {
$survey_id = $_POST['survey_id'];
echo $survey_id;
}
if (isset($_POST['marks'])) {
foreach ($_POST['marks'] as $value) {
echo"$value";
}
}
if (isset($_POST['id'])) {
$id = $_POST['id'];
echo $id;
}
// $SQL2 = "UPDATE answer_table SET marks='$value' WHERE survey_id= '$survey_id' AND student_id= '$id'";
//$result2 = mysql_query($SQL2);
//mysql_close($db_handle);
} else {
print "Database NOT Found ";
mysql_close($db_handle);
// header("Location: surveyView.php");
}
?>
Here is displayresult.php
<form action="student_mark_save.php" method="POST"> //<?php...more codes here
if ($strucrow["qns$i"] === 'radio' || $strucrow["qns$i"] === 'checkbox') {
foreach ($arr as $b) {
echo "<br/>";
if (strpos($b, '%#%') !== false) {
$c = substr($b, 3, -2);
//echo $c;
$d = str_replace("$arr[0] :-", ':', $c);
echo $d, "<br/>";
echo "<br/>";
echo "<tr> Marks : <input type=\"text\" name=\"marks[]\"></tr><br />";
//echo $b;
} else {
echo $b;
// echo "is not with comment qns";
}
}
} else if ($strucrow["qns$i"] === 'comment') {
foreach ($arr as $b) {
echo $b;
echo "<tr> Marks : <input type=\"text\" name=\"marks[]\"></tr><br />";
// echo "is not with comment qns";
}
} else {
}
echo "<p/>";
}
$marksquery = sprintf(
"SELECT marks FROM answer_table WHERE survey_id = '%d' AND student_id = '$studentid' ", mysql_real_escape_string($survey_id)
);
$marksQuer = mysql_query($marksquery) or die(mysql_error());
$marksrow = mysql_fetch_assoc($marksQuer);
echo "<td><input type=\"hidden\" value= \"$survey_id\" name=\"survey_id\"></td><br />" ;
echo "<td><input type=\"hidden\" value= \"$studentid\" name=\"id\"></td><br />" ;
echo "<p><input type=\"submit\" value=\"Update\"></p>";
?>
</form>
for undefined mean, there is something which is not existing in global $_POST[]
check try to print $_POST in your first if statement as:
if ($db_found) {
print_r($_POST);
exit();
if (isset($_POST['survey_id'])) {
$survey_id = $_POST['survey_id'];
echo $survey_id;
}
now just see what do you have in $_POST, It might help you...Thanks
Most likely some Post data is not set. Try vardump($_POST); die('happy');.
It would also be better to handle missing Post data instead of just ignoring it so maybe if ($db_found) { should be
<?php
if ( $db_found
&& isset($_POST['survey_id'])
&& isset($_POST['marks'])
&& isset($_POST['id'])
)
{
$survey_id = $_POST['survey_id']; //maybe ensure int
$id = $_POST['id']; //maybe ensure int
$values = array(); //this is important $value will not be available outside the for loop or contain only the last value
foreach ((array)$_POST['marks'] as $value) { //ensure $_POST['marks'] is an array
$values[] = $value; //maybe mysql escape each $value here
}
$SQL2 = sprintf(
"UPDATE answer_table SET marks='%s' WHERE survey_id=%d AND student_id=%d",
impolde(',' $values), //assuming comma separated list here
$survey_id,
$id
);
$result2 = mysql_query($SQL2);
mysql_close($db_handle);
} else { ...
Please also consider to escape the values you read from POST. Doing it this way makes it very easy to SQL inject into your script!

Categories