I built a website that takes a random row from a MySQL table.
The values I am interested in are Exercise and solution.
When I check if the solution the user wrote is the same as the one I got from the database, a new query is running and replacing my solution.
the query:
$query="SELECT Exercise,solution FROM exercises WHERE rank = '".$Rank."' ORDER BY RAND() LIMIT 1";
$result=mysql_query($query) or die ("Query to get data from firsttable failed: ".mysql_error());
while ($row=mysql_fetch_array($result)) {
$Exercise=$row["Exercise"];
$Solution=$row["solution"];
checking the answer:
<?php
if (isset($_POST['postBTN']))
{
if($_POST['solution'] == $Solution){
echo "<script type='text/javascript'>alert('yes');</script>";
$progression = ($progression+1);
$query="UPDATE users SET progression = '".$progression."' WHERE username = '".$_SESSION['username']."'";
$result=mysql_query($query) or die ("Query to get data from firsttable failed: ".mysql_error());
}else{
echo "<script type='text/javascript'>alert('no');</script>";
}
}
?>
When I check the answer a new query is running and replacing the solution.
Related
First and formost, yes i know PHP5.6 is deprecated version, but i want to stick with it and fully learn PHP for myself, before updating to MySQLi.
I'm trying to make a text based game running MySQL and PHP, and currently trying to create a system that:
1.Gets information from user table, username and total actions done (+)
2.At the certain timestamps save all usernames and actions into separete table (-)
3.Resets actions column to 0 for ALL players. (+/- planning to use a mysql trigger and/or cron-job)
My questions:
2) How would you suggest me to insert usernames into seperate table? (only idea i come up is to explode array somehow get variables and sumbit to mysql, question is how to do so? )
3) regarding this number 3, would you suggest something else then triggers or cron-jobs?
Code example bellow
<?php
include './config/connect-db.php';
$result= mysql_query("SELECT * FROM user WHERE actions > 100 ORDER BY
actions DESC LIMIT 5");
while($row = mysql_fetch_array($result)){
if ($row['u_dmisijos'] >= 100) {
echo '<li>'.$row["u_name"].' ('.$row["actions"].')<br>';
} // if actions
} //while loop
?>
EDIT:
MySQL includes a lot of columns, there are only 2 specific I'm focusing on, u_name (username) and actions (actions).
EDIT2:
What i am expecting on second table: ID (AI), username of player with the most action points, username of player with second action points etc. And Datastamp.
expected SQL
ID, nr1, nr2, nr3, nr4, nr5, Datastamp.
Cheers!
I am not sure this will work or not as I have not tested it. But, I hope you might get a general idea.
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT * FROM user WHERE actions > 100 ORDER BY actions DESC LIMIT 5";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
$q = "INSERT INTO `new_table` (`u_name`, `actions`) VALUES
($row['u_name'],$row['actions'] )";
mysql_query($q);
}
?>
Regarding resetting all actions to 0 you can create a functions like:
function resetActions(){
//update actions to 0
$q = "UPDATE table_name SET actions = 0";
mysql_query($q);
}
Now, whenever you need to reset it you can call this function. Or you can call this function in cron job as you required.
I have tables in one db, and one is foreign keyed to the other. My problem is that I'm trying to call up information stored in one table based on the user name which links the 2 tables stored in the other. Here is my php, mind you I'm pretty fresh on the databasing and php, so cut some slack. Here is my code:
<?php
$loaduser= $_SESSION['username'];
$loaduser_conn= #mysql_connect("DB_NAME","DB_USER","DB_PASS");
mysql_select_db("user_register") or die ("Couldn't find user database.");
$gal_result= mysql_query("SELECT shoot_name FROM images WHERE username='$loaduser'") or die (mysql_error());
while($row = mysql_fetch_assoc($gal_result,MYSQL_ASSOC))
{
foreach($results['shoot_name'] as $result)
{
echo $result['shoot_name'], '<br>';
if(mysql_num_rows($gal_result) !=1) {
die("No galleries found for this user.");
}
}
}
You can google "PHP PDO tutorial" and find many resources. Here's one that is very clear and well written: like: https://phpdelusions.net/pdo
Here's a better example:
<?php
$loaduser = $_SESSION['username'];
// use PDO, not the deprecated mysql extension
$dsn = "mysql:host=localhost;dbname=user_register";
$conn = new PDO($dsn, "DB_USER", "DB_PASS");
// set exception errmode, so code dies automatically if there's an error
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// use a parameterized query instead of concatenating variables into SQL
$sql = "SELECT shoot_name FROM images WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->execute([$loaduser]);
// fetch all into an array of results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// check the count of the results with < 1 instead of != 1
// in case it's 2 or more
if ($stmt->rowCount() < 1) {
die("No galleries found for this user.");
}
// loop through results
foreach($results as $row) {
// use dot for string concatenation instead of comma.
echo $row["shoot_name"] . "<br>";
}
$results has to be fetched before tryin to get its contents.
While trying to get its contents you were fetching $row instead of $results
You are using mysql, mysql has been deprecated try using mysqli or PDO in the future.
Try this anyway.
<?php
$loaduser= $_SESSION['username'];
$loaduser_conn= #mysql_connect("DB_NAME","DB_USER","DB_PASS");
mysql_select_db("user_register") or die ("Couldn't find user database.");
$gal_result= mysql_query("SELECT shoot_name FROM images WHERE username='$loaduser'") or die (mysql_error());
$results = mysql_fetch_assoc($gal_result,MYSQL_ASSOC)
while($results = mysql_fetch_assoc($gal_result,MYSQL_ASSOC)){
foreach($results['shoot_name'] as $result) {
echo $result['shoot_name'], '<br>';
if(mysql_num_rows($gal_result) !=1){
die("No galleries found for this user.");
}
}
}
?>
Try rewriting to this untested snippet (in case you want to keep using deprecated code ;))
$loaduser= $_SESSION['username'];
$loaduser_conn= #mysql_connect("DB_NAME","DB_USER","DB_PASS");
mysql_select_db("user_register") or die ("Couldn't find user database.");
$gal_result= mysql_query("SELECT shoot_name FROM images WHERE username='$loaduser'") or die (mysql_error());
if(mysql_num_rows($gal_result)==0){ // returns number of rows so if 0 there are no rows
die("No galleries found for this user.");
}
while ($row = mysql_fetch_array($gal_result)) { // "while" is already your loop. No need for the foreach within.
echo $row['shoot_name'], '<br>';
}
If you want to select from multiple tables with some reference try this query:
$gal_result= mysql_query("SELECT shoot_name FROM images AS a LEFT JOIN your_other_table AS b ON a.username = b.username WHERE a.username='$loaduser'") or die (mysql_error());
Like anyone i would advise you on using more up to date code.
See here for more info: http://php.net/manual/de/function.mysql-query.php
Ive been trying to display a "bid" from the database to no success.
here is my error
Fatal error: Function name must be a string in /home/rslistc1/public_html/get-bids.php on line 7
here is my code
<?php
include('session.php');
?>
<?php
require_once('mysql_connect.php');
$query3 = "SELECT id, username, bid FROM bids WHERE username = '$login_session'";
$result3 = mysql_query($query3) OR die($mysql_error());
$num = mysql_num_rows($result3);
while ($row = mysql_fetch_array($result3, MYSQL_ASSOC)) { ?>
<?php echo''.$row['bid'].'';
}
?>
Any idea
Before we address the line 7 issue, lets check other errors. In order to request a query to a MYSQL database, we need to create a connection:
$con = mysqli_connect("ip_address","user","password","database_name");
Once we have that connection, let us check if we can actually connect to the database:
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
Appreciate that mysqli_error() function uses the connection. Now the query string:
$query3 = "SELECT id, username, bid FROM bids WHERE username = '$login_session'";
You are sending a query to look for a username called "$login_session" and it would most likely not find any match. To add strings from variables will be as follow:
$query3 = "SELECT id, username, bid FROM bids WHERE username = '" . $login_session . "'";
Now, for the error in line 7
result3 = mysql_query($con, $query3) OR die($mysql_error($con));
As you can see, both mysql function use the connection to check for errors. Try it and let me know if everything works fine.
Edit:
Terribly sorry my friend, I just forgot to put a little letter "i" on the line, also, I would like to show you my way to deal with the query result. First, the line as it should be:
$result3 = mysqli_query($con, $query3);
Notice the i after mysql. Now let us check whether we got some rows or not:
if (!$result3) {
die('Could not retrieve data: ' . mysqli_error($con));
} else {
while ($row = mysqli_fetch_array($result3)) {
//Show your results
}
}
I have run across a problem during my query service to add a row in an online database in PHP. The addition of the row works just fine. I get user id and book id from the url and fetch the names of the book and the user to put into the row which i add to my third and last table.
When I get the names, put them in an array, json encode it and then echo it, it works. But when I put them in the row it prints resource id#3 and resource id#4 instead of the names.
Any ideas?
Here is my service:
<?php
$con = mysql_connect("localhost","root","root");
$userid=$_GET['uid'];
$id = $_GET['bookid'];
$type = $_GET['type'];
$zero = '0';
$one = '1';
$date = date("Y-m-d");
$arr = array();
if (!$con)
{
die('Could not connect: ' . mysql_error());
echo "error connection";
}
mysql_select_db("Jineel_lib",$con) or die("Could not select database");
$bkName = mysql_query("SELECT Name from books where ID='".$id."'");
$userName = mysql_query("SELECT Name from people WHERE User_ID='".$userid."'");
while($obj = mysql_fetch_object($userName))
{
$arr[] = $obj;
}
echo json_encode($arr);
if($type == 'borrow')
{
$query="UPDATE books set Availablity = '".$zero."' where ID= '".$id."' ";
mysql_query($query) or die (" borrow operation failed due to query 1");
$query1="INSERT into borrowed (BookID, BookName, BorrowerID, BorrowedName, DateBorrowed, Extended, Returned) values('".$id."','".$bkName."','".$userid."','".$userName."','".$date."','".$zero."','".$zero."')";
mysql_query($query1) or die (" borrow operation failed to due query 2");
echo "borrow success";
}
else if($type=='return')
{
$query="UPDATE books set Availablity = '".$one."' where ID= '".$id."' ";
mysql_query($query) or die (" return operation failed");
$query1="UPDATE borrowed set Returned = '".$one."' where BookID= '".$id."' ";
mysql_query($query1) or die (" return operation failed 1");
echo "return success";
}
else
echo "invalid parameters";
?>
THANK YOU IN ADVANCE
You don't actually retrieve the userName value here:
$userName = mysql_query("SELECT Name...
$userName is just the result resource object returned from the query. You do use mysql_fetch_object later on, which is appropriate, but then you try to use the actual result resource in your insert query:
$query1="INSERT into borrowed ...
It gets converted to the string you see. Instead, you need to use $obj->Name (you fetch the result into $obj, and presumably there is only one result). If there is more than one possible result, you will have to do that in a loop.
Listen to all of the comments on your question.
I want to show the maximum value of a particular column of mysql table in php. Here is my code:
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$var = $_POST['value'];
$sql = mysql_query(" SELECT MAX(column) FROM tableName WHERE variable='$var' ") or die(mysql_error());
$row = mysql_fetch_array($sql) or die(mysql_error());
echo "Maximum value is :: ".$row['column'];
?>
output:::
Maximum value is ::
Or you could be a bit creative:
$sql = mysql_query("SELECT `column` FROM tableName WHERE variable='$var' ORDER BY `column` DESC LIMIT 1") or die(mysql_error());
This is the same problem that I was searching for a solution. The approach below worked. The solution was using "MYSQLI_NUM". While the code below gives the intended result it still seems way too complex. Is there a way to "short-cut" using the "while" statement to search an array since there is only one returned value?
Selecting a max value only returns one number, yet PHP still seems to require a loop to evaluate an entire array. I was expecting something easy, like: max_value=result(0).
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error.' Sorry, could not connect to the database server');
$query = "SELECT MAX(IssueIDNUM) FROM tblIssueList";
$result =$conn->query($query);
if (!$result) die($conn->error);
while($row=mysqli_fetch_array($result, MYSQLI_NUM))
{
$maxresult=$row[0];
echo $maxresult;
}
$result->close();
$conn->close();
?>
With further experimentation, I was also able to adapt the code by Jim H. to develop the following solution. Though it works the code still seems too complex.
// Solution #2
$result =$conn->query("SELECT MAX(IssueIDNUM) `max` FROM tblIssueList");
if (!$result) die($conn->error);
while($row=mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo $row['max'];
}
The real name of column is MAX(column), try:
print_r($row);
You may either do:
$sql = mysql_query(" SELECT MAX(column) AS `column` FROM tableName WHERE variable='$var' ") or die(mysql_error());
Or:
$row = mysql_fetch_row($sql) or die(mysql_error());
echo "Maximum value is :: ".$row[0];
You have two choices. By Index or by Column Name. If you really want to use a column name, alias the column in your query.
$sql = mysql_query(" SELECT MAX(column) `max` FROM tableName WHERE variable='$var' ") or die(mysql_error());
Then you can use
$row['max'];
or
$row[0];
You are probably not returning any rows. You should try WHERE variable LIKE '%$var%';
$sql = mysql_query(" SELECT MAX(column) AS GIVE_A_NAME FROM tableName WHERE variable='$var' ") or die(mysql_error());
and
echo "Maximum value is :: ".$row['GIVE_A_NAME'];