(PROBLEM IS VERY DETAILED FOR TOO LONG DIDN'T READ: "My guess is that i'm using the MYSQL_FETCH_ARRAY wrong.")
Hello! The following codes purpose is to do a basic search in the database. The data is passed by a form. The tutorial I was using was written by: 'Frost of Slunked.com' and it was a basic register/login php MySQL tutorial, which worked perfectly. I managed to write a woking table-updater function and form-submit to add new data to the selected (so that's working as intended.
config.php - conncets to the MySQL server, selects the database, starts the session, requires the functions.php (with authors comments included)
<?php
/*****************************
File: includes/config.php
Written by: Frost of Slunked.com
Tutorial: User Registration and Login System
******************************/
// start the session before any output.
session_start();
// Set the folder for our includes
$sFolder = '';
/***************
Database Connection
You will need to change the user (user)
and password (password) to what your database information uses.
Same with the database name if you used something else.
****************/
mysql_connect('localhost', 'myusername', 'mypassword') or trigger_error("Unable to connect to the database: " . mysql_error());
mysql_select_db('tormex') or trigger_error("Unable to switch to the database: " . mysql_error());
/***************
password salts are used to ensure a secure password
hash and make your passwords much harder to be broken into
Change these to be whatever you want, just try and limit them to
10-20 characters each to avoid collisions.
****************/
define('SALT1', '24859f##$##$');
define('SALT2', '^&##_-=+Afda$#%');
// require the function file
require_once 'functions.php';
// default the error variable to empty.
$_SESSION['error'] = "";
// declare $sOutput so we do not have to do this on each page.
$sOutput="";
?>
functions.php - has multiple functions (login, createRide, Register etc.). Most of the functions purpose is to get the values from the submitted HTML forms and then maintain the required actions - I will only mentioned my searchRide function (which in my guess has the error or atleast, has to do something with it) and the createRide function, which is working properly.
<?php ...
unction searchRide($pWhen_min, $pWhen_max, $pFrom, $pTo){
if (!empty($pWhen_min) && !empty($pWhen_max) && !empty($pFrom) && !empty($pTo)) {
global $sql2, $query2;
$sql2 = "SELECT * FROM ride WHERE `from` ='$pFrom' AND `to` = '$pTo' AND `when` >= '$pWhen_min' AND `when` <= '$pWhen_max' ";
$query2 = mysql_query($sql2) or trigger_error("Query Failed: " . mysql_error());
}
}
function createRide($pFrom, $pTo, $pWhen, $pSeats, $pPrice, $pCar){
if (!empty($pFrom) && !empty($pTo) && !empty($pWhen) && !empty($pSeats) && !empty($pPrice) && !empty($pCar)){
$sql = "SELECT id FROM users WHERE username= '" . $username . "' LIMIT 1";
$result = mysql_query($sql);
if(!$result) {
trigger_error("ELKURTAD " . mysql_error());
}
$row = mysql_fetch_array($result);
$sql = "INSERT INTO ride (`from`, `to`, `when`, `seats`, `price`, `car`, `u_id`)
VALUES ('" . $pFrom . "', '" . $pTo . "', '" . $pWhen . "',
'" . $pSeats . "', '" . $pPrice . "', '" . $pCar . "', '" . $result . "');";
$query = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error());
if ($query) {
return TRUE;
}
}
return FALSE;
}
...?>
searchRide.php - checks if the variables which are dedicated to get the search filter values have any values; (in the else statement) if there are no values, the form wasn't submitted and displays the searchRide form and after result passes the variables for the searchRide.php ( $_SERVER['PHP_SELF'] )
<?php
require_once 'config.php';
$sOutput .= '<div id="searchRide-body">';
if (isset($_GET['action'])) {
switch (strtolower($_GET['action'])) {
case 'searchride':
if (isset($_POST['when_min']) && isset($_POST['when_max']) && isset($_POST['from']) && isset($_POST['to'])) {
if (searchRide($_POST['when_min'], $_POST['when_max'], $_POST['from'], $_POST['to'])) {
while($row = mysql_fetch_array($query2)){
$sOutput .= "' ID: '" .$row['id'] . "' <br />
When: '" . $row['when'] . "' <br />
From: '" . $row['from'] . "' <br />
To: '" . $row['to'] . "' <br />
Seats left: '" . $row['seats'];
}
}
}
}
}else{
if (isset($_SESSION['error'])) {
$sError = '<span id="error">' . $_SESSION['error'] . '</span><br />';
}
$sOutput .= '<h2>Search for rides</h2>
' . $sError . '
<form name="searchride" method="post" action="' . $_SERVER['PHP_SELF'] . '?action=searchride">
From: <input type="text" name="from" value=* /><br />
To: <input type="text" name="to" value=* />
When_min: <input type="text" name="when_min" value=* />
When_max: <input type="text" name="when_max" value=* />
<br /><br />
<input type="submit" name="submit" value="Search" />
</form>
<br />
<h4>Would you like to Go back?</h4>';
}
echo $sOutput . "<br />";
echo "TEST string" . "<br />";
echo $query2 . " query2<br /> ";
echo $sql2 . " sql2<br />";
echo $row . "<br />";
?>
At the end of this code You can see some printed variables, which are used to check their values after searRide form is submitted.
I updated my database with the following data and checked with phpMyAdmin for the exact values so I can test the search with existing data:
From: TEST01
To: TEST02
When: 500
Seats: 5
Price: 7
Car: volvo
Test data submitted with the searchRide form:
From: TEST01
To: Test02
When_min: 1
Whn_max: 3000
After is press Search button on the searchRide form these are the following results (what the browser shows):
(sOutput variable
TEST WRITE TEXT
Resource id #5 (query2 variable
SELECT * FROM ride WHERE from ='TEST01' AND to = 'TEST02' AND when >= '1' AND when <= '5000' (sql2 variable
(row variable
After this I inserted the SQL query in the phpMyAdmin SQL command line and resulted the data I was searching for.
Was trying many times to figure out what could be the problem, with my own knowledge and varius searches on google, php.net and w3chools.com.
My guess is that i'm using the MYSQL_FETCH_ARRAY wrong.
following condition will not work
if (searchRide($_POST['when_min'], $_POST['when_max'], $_POST['from'], $_POST['to'])) {
as you have not return any value from searchRide function you need to return true to go into the condition.
Related
I have a php page that interacts with a database. I am trying to display data from the database as options for a user to select. I am trying to record which option a user selects but the variable I use ($a_game_id) to record which button is clicked gets reverted back to its original value after submitting another form. I have tried declaring the variable as global within the loop and using session variables.
$a_game_id = 9;//starting value - it changes from 9 as desired, but reverts back when another form is submitted
$sql = "SELECT * FROM nbagames WHERE date = '" .$date ."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
global $a_game_id;
// output data of each row
$results = $conn->query($sql);
$resultset = array();
while($a_row = $results->fetch_assoc()){
$resultset[] = $a_row;
}
foreach ($resultset as $row){
echo "<form action='display_lines.php' method='POST'>
<br>" . $row["away"] . " " . $row['away_spread'] . "---TOTAL AVAILABLE: " . $away_sum_array[$row['game_id']].
" <input type='submit' value='Bet " . $row['away'] ."' name='" . $row['game_id']."A' />
at " . $row["home"] . " " . $row['home_spread'] . "---TOTAL AVAILABLE: " .$home_sum_array[$row['game_id']]. "
<input type='submit' value= 'Bet " . $row['home'] ."' name='" . $row['game_id']."H' /> " . $row['date'] . "
</form>
<br>";
///HERE $a_game_id has gets the desired value
if(isset($_POST[$row['game_id'].'H'])){
$a_game_id = intval($row['game_id']);
}else if(isset($_POST[$row['game_id'].'A'])){
$a_game_id = intval($row['game_id']);
}
}
} else {
echo "<br> 0 results";
}
$sql = "SELECT * FROM nbagames WHERE date = '" .$date ."'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
if(isset($_POST[strval($row['game_id']).'H'])){
echo '<h3>'.$row['game_id'].'<br>';
echo $row['home'].' '.$row['home_spread'].'<br>';
$team = $row['home'];
$team_spread = $row['away_spread'];
echo '<form action="display_lines.php" method="post">
<input type="text" name="new_bet_amount" placeholder="Enter Bet Amount">
<input type="submit" name="new_bet_submit" value="Submit Bet">
</form></h3>';
}
else if(isset($_POST[strval($row['game_id']).'A'])){
echo '<h3>' .$row['game_id'].'<br>';
echo $row['away'].' '.$row['away_spread'].'<br>';
$team = $row['away'];
$team_spread = $row['away_spread'];
echo '<form action="display_lines.php" method="post">
<input type="text" name="new_bet_amount" placeholder="Enter Bet Amount">
<input type="submit" name="new_bet_submit" value="Submit Bet">
</form></h3>';
}
}
if(isset($_POST['new_bet_submit'])){
//HERE $a_game_id reverts back to its original value which is undesirable
$sql3 = "INSERT INTO placed_bets (user_id, game_id, bet_amount, game_date) VALUES ('".$_SESSION['id']."', '".$a_game_id."', '".$_POST['new_bet_amount']."', '".$date."')";
echo $a_game_id.'<br>';
if ($conn->query($sql3) === TRUE) {
echo "<br><h3>BET PLACED SUCCESSFULLY</h3><br>";
} else {
echo '<h3>Error placing bet<br>';
echo $conn->error;
echo '</h3>';
}
}
Thank you for taking a look
Do you mean "when I make another request all my global variables get reset?" If so, yes, that's how they work. Each request is completely independent of others. They do not share variables or other data. All you get is what's in $_SESSION, $_GET, $_POST and $_COOKIE.
If you need to persist between requests you must put that in the session, the database, or something persistent.
If you're used to code where the process persists and the variables stick, like in client-side situations, that's a mode of thinking you need to completely abandon.
Below I have code that is supposed to update an entry in the database. When I click the submit button the form goes away but it is not replaced with anything and more importantly it doesn't update the database. I cannot seem to find where the error is and any help would be greatly appreciated.
<?php
define('TITLE', 'Quotes Entry!');
// Include the header:
include('header.php');
include('mysqli_connect.php');
// Leave the PHP section to display lots of HTML:
?>
<?php //
mysqli_set_charset($dbc, 'utf8');
if (isset($_GET['id']) && is_numeric($_GET['id']) ) { // Display the entry in a form:
// Define the query:
$query = "SELECT title, entry FROM Salinger WHERE entry_id={$_GET['id']}";
if ($r = mysqli_query($dbc, $query)) { // Run the query.
$row = mysqli_fetch_array($r); // Retrieve the information.
//make the form
print '<form action = "edit_entry.php" method = "post">
<p> Entry Titles <input type= "text" name = "title" size = "40" maxsize = "100" value = "' . htmlentities($row['title']) . '" /></p>
<p>Entry Text <textarea name = "entry" cols = "40" rows = "5">'. htmlentities($row['entry']).'</textarea></p>
<input type = "hidden" name = "id" value = "'.$_GET['id'] .'" />
<input type = "submit" name = "submit" value = "Update This Entry!" />
</form>';
} else { // Couldn't get the information.
print '<p style="color: red;">Could not retrieve the blog entry because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
}
} elseif (isset($_POST['id']) && is_numeric($_POST['id'])) { // Handle the form.
$problem = "false";
if(!empty($_POST['title']) && !empty($_POST['entry'])){
$title = mysqli_real_escape_string($dbc, trim(strip_tags($_POST['title'])));
$entry = mysqli_real_escape_string($dbc, trim(strip_tags($_POST['entry'])));
} else{
print '<p style="color: red;">Could not retrieve the blog entry because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
$problem = true;
}
if(!problem){
$query = "UPDATE Salinger SET title = '$title', entry = '$entry' WHERE entry_id = {$_POST['id']}";
$r = mysqli_query($dbc, $query); //execute the query
if(mysqli_affected_rows($dbc) == 1){
print'<p> The blog entry has been updated.</p>';
// Report on the result:
} else {
print '<p style="color: red;">Could not retrieve the blog entry because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
}
}
} else{
print '<p style="color: red;">Could not retrieve the blog entry because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
}
mysqli_close($dbc); // Close the database connection.
include('footer.php'); // Need the footer.
?>
Because you set $problem = "false"; you need to set it to $problem= false;
"false" is not false
And !problem should be !$problem
You have a problem with GET[id].
It's getting blank cause of POST event on screen, due to which your SQL is not finding the record.
To test assign hard coded value in your select statement.
Example
$query = "SELECT title, entry FROM Salinger WHERE entry_id=10";
I have a script on my website which handles a notification system for messages, and alerts. This script pulls in the data from a MySQL Database, and it works like a charm locally, but on my live site, the query fails. This script always returns false and goes to the else condition live, but locally it works exactly the way it should.
$queryNots = 'Select message, DATE_FORMAT(timeSent, "%h:%i %p %W, %M %D ") timeSent FROM notifications WHERE UserID="' . $userId . '" AND seen="n";';
if ($result = $con->query ($query)) {
$resultNum = mysqli_num_rows ( $result );
echo '<h2>You have ' . $resultNum . ' Notifications</h2>
<ul>';
while ( $row = $result->fetch_assoc () ) {
echo '<li>' . $row ["message"] . ' # ' . $row ['timeSent'] . '</li>';
}
if ($resultNum > 0) {
echo '
</ul>
<form method="post" action="deleteNots.php">
<input type="hidden" name="curID" value="' . $userId . '">
<input type="submit" value="Dismiss">
</form>
';
}
} else {
echo '<h2>Error reading table</h2>';
}
On the live site if I take out the if-else and just run the query not only does it fail, it kills the entire script. I have no idea what could be causing this, I know the tables are the same, because I use them in a different script just fine.
I have absolutely nothing to work with, because it isn't giving me any sort of MySQL error message to go off of. I really want to get this figured out because I want to have this site back working as soon as possible.
$query = 'Select message, DATE_FORMAT(timeSent, "%h:%i %p %W, %M %D ") timeSent FROM notifications WHERE UserID="' . $userId . '" AND seen="n"';
$result = $con->query($query);
if ($result) {
$resultNum = mysqli_num_rows($result);
echo '<h2>You have '.$resultNum.'Notifications</h2><ul>';
while($row = $result->fetch_assoc()) {
echo '<li>' . $row ["message"] . ' # ' . $row ['timeSent'] . '</li>';
}
if ($resultNum > 0) {
echo '
</ul>
<form method="post" action="deleteNots.php">
<input type="hidden" name="curID" value="' . $userId . '">
<input type="submit" value="Dismiss">
</form>
';
}
} else {
echo '<h2>Error reading table</h2>';
}
NOTE:
Change the $queryNots variable because you used the $query variable below code
i.e: $result = $con->query($query);
unwanted semicolon(;) in $queryNots :: seen="n";';
The solution to my issue ended up coming in the comments of the question, so I couldn't mark it as completed.
try echo mysql_error() to see what´s going on there – handsome Jul 29
'17 at 14:51
I am not sure why this hasn't been answered yet will not that I know of, I am wondering if it's possible to add a insert query with in a while loop I have tried,
but it keeps inserting the comment more then it should (say if it finds 4 status updates it will post the comment in the database 4 times)
I know I have the insert query twice this is not the problem as I had the query where it submits a comment to the database the current query is there for testing purposes.
<?php
require_once ("core/connection.php");
require_once ("core/group_functions.php");
//We need to post the message update in to the database
if(isset($mybb->input['post_message_submit'])) {
$post_message_submit = $mybb->input['post_message_submit'];
$post_message = $mybb->input['post_message'];
$comment_post = $mybb->input['comment_post'];
if(($post_message_submit) && ($post_message)) {
$insert_query = $db->query("INSERT INTO " . TABLE_PREFIX . "groups_posts" . "(posted_by, group_name, post_body)
VALUES ('$mybb_username', '$get_group_url' ,'$post_message')");
} else {
echo "<text style='color:red;'> You Must Specify A Message</a></text>";
}
}
echo "
<form action='' method='POST'>
<textarea name='post_message' id='post_message' placeholder='Whats Going On?'></textarea><br>
<input type='submit' name='post_message_submit' value='Post'>
</form>
";
$fetch_index_query = $db->query("SELECT post_id,posted_by,post_body,post_active,group_name FROM " . TABLE_PREFIX . "groups_posts WHERE group_name='$get_group_url'");
while($fetch_index_groups_array = $db->fetch_array($fetch_index_query)) {
$post_id_row = $fetch_index_groups_array['post_id'];
$posted_by = $fetch_index_groups_array['posted_by'];
$g_name = $_fetch_index_groups_array['g_name'];
$g_body = $fetch_index_groups_array['post_body'];
echo"<br>" . "<a href=''> $posted_by </a>" . "<br>" . $gname
. "<br>____________";
$fetch_comments_query = $db->query("SELECT g_name,post_body,comment_by FROM spud_groups_comments WHERE post_id='$post_id_row'");
while($fetch_groups_comments = $db->fetch_array($fetch_comments_query)) {
$post_body = $fetch_groups_comments['post_body'];
echo ("<br>" . $post_body);
}
$insert_query2 = $db->query("INSERT INTO " . TABLE_PREFIX . "groups_comments" . "(comment_by, post_id, post_body)
VALUES ('$mybb_username', '$post_id_row' ,'$comment_post')");
echo "<br>
<form action='' method='POST'>
<input type='text' name='comment_post' placeholder='Comment then Hit Enter'>
</form>
";
}
//We have done everything we need to do we can now exit and not execute anything beyond this point
exit();
?>
Try to instantiate other $DB object for the insert query. i.e. do not use the same one you are using to fetch the array, as the next use will overwrite the result of the first query that you are looping through.
I've checked my code compared with code elsewhere on my site and I can't see any inconsistencies, but for some reason the records are entering my database with blank data, here is my code.
<?php
include '../includes/connect.php';
include '../header.php';
echo '<h2>Create a Sub category</h2>';
if($_SESSION['signed_in'] == false | $_SESSION['user_level'] != 1 )
{
//the user is not an admin
echo 'Sorry, you do not have sufficient rights to access this page.';
}
else
{
//the user has admin rights
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
//the form hasn't been posted yet, display it
echo '<form method="post" action="">
Category name: ';
$sql = "SELECT cat_id, cat_name, cat_description FROM categories";
$result = mysql_query($sql);
echo '<select name="topic_cat">';
while($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
}
echo '</select><br />';
echo 'Sub category name: <input type="text" name="sub_cat_name" /><br />
Sub category description:<br /> <textarea name="sub_desc" /></textarea><br /><br />
<input type="submit" value="Add Sub Category" />
</form>';
}
else
{
//the form has been posted, so save it
$sql = "INSERT INTO subcategories(c_id, sub_cat_name, sub_desc)
VALUES('" . $_POST['categories.cat_id'] . "', '" . $_POST['sub_cat_name'] . "', '" . $_POST['sub_desc'] . "')";
$result = mysql_query($sql) or die (mysql_error());
echo 'The sub category <b>' . $row['sub_cat_name'] . '</b> has been added under the main category <b>' . $row['cat_name'] . '</b>';
if(!$result)
{
//something went wrong, display the error
echo 'Error' . mysql_error();
}
}
}
; ?>
My categories table is structured like so..
cat_id
cat_desc
My subcategories table is structured like so..
id(AI)
c_id
sub_cat_name
sub_desc
If I haven't provided enough information please let me know.
You don't appear to be reading the $POST variables into the variables you're using in your query. You probably want something like this:
$sub_cat_name = mysql_real_escape_string($_POST['sub_cat_name']);
// repeat for other variables.
It seems to me that $cat_id $sub_cat_name and $sub_desc are not defined anywhere.
Also, you're missing a pipe here:
if($_SESSION['signed_in'] == false || $_SESSION['user_level'] != 1 )
// --------------------------------^
Lastly, I should note that the mysql_* functions are deprecated. You should really be using mysqli or PDO.
if($_SESSION['signed_in'] == false || $_SESSION['user_level'] != 1 )
------------------------------------^ (OR)
I also don't see where you set the variables. ('" . $cat_id . "' and etc...)
You should store them into a variable like so:
$cat_id = mysql_real_escape_string($_POST['name_of_the_input']); //and etc..
Or in your insert query do this: (Depending on the values whether or not you need to escape it like above)
'".$_POST['name_of_input']."',