Jump to content

Does not update detabase.


MuphN
Go to solution Solved by Ch0cu3r,

Recommended Posts

Hello. So Im trying to make an update for exemple on click, that would update my database, but it doesnt function. button just dissapears. thats all.  

<?php $clicked = getIns($mysqli); ?>
<button type="button" onclick="<?php $clicked ?>">+5StatsUp</button>

----------------------------------------------------------

		$strp = getStr($mysqli) + 5;
		$agip = getAgi($mysqli) + 5;
		$rangep = getRange($mysqli) + 5;
		
function getIns($mysqli) {
    if ($stmt = $mysqli->prepare("UPDATE members SET str = ?, agi = ?, `range` = ? WHERE id = ? LIMIT 1")) {
            $user_id = $_SESSION['user_id'];
            $stmt->bind_param('iiii', $strp, $agip, $rangep, $user_id);
            if (!$insert_stmt->execute()) {
                header('Location: ../error.php?err=updateFailled: INSERT');
            }
        }
        header('Location: ./update_success.php');
    }

What it should do: Update members - str, agi, range + 5 where id is user id.

Hmmmm can you guys tell me whats wrong with my code? :/

Link to comment
Share on other sites

You cannot call PHP functions on an onlick event - or any any event that happens within the browser for that matter.

 

A http request will need to be made in order for PHP to do an action. For PHP to call to the getIns function you'll need to create a submit button

<form action="page.php" method="post">
   <input type="submit" name="add5" value="Add +5" />
</form>

 Now in your PHP code, you'd call the functin when $_POST['add5'] exits

// call getIns when $_POST['add5'] exists
if(isset($_POST['add5']))
   getIns($mysqli);

Also you can add 5 to a fields value within the SQL query itself. You dont need to retrieve the old value and then add 5

UPDATE members SET str = str+5, agi = agi+5, `range` = `range`+5 WHERE id = ? LIMIT 1
Edited by Ch0cu3r
Link to comment
Share on other sites

I understand now, but for some reason my script is not working. I made fc.php with inside:

<?php
include_once '../includes/db_connect.php';
include_once '../includes/functions.php';

sec_session_start(); 

		$str = getStr($mysqli);
		$agi = getAgi($mysqli);
		$range = getRange($mysqli);
		
		if(isset($_POST['add5'])){
			function getIns($mysqli) {
			if ($stmt = $mysqli->prepare("UPDATE members SET str = ?+5, agi = ?+5, `range` = ?+5 WHERE id = ? LIMIT 1")) {
				$user_id = $_SESSION['user_id'];
				$stmt->bind_param('iiii', $str, $agi, $range, $user_id);
				if (!$insert_stmt->execute()) {
					header('Location: ../error.php?err=Registration failure: INSERT');
				}
			}
			header('Location: ./register_success.php');
		}
	}	
?>

and then added this 

<?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';
include_once 'system/fc.php';
sec_session_start();
?>
<!DOCTYPE html>
<html>
    <head>

    </head>
<body>

<form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>" method="post">
   <input type="submit" name="add5" value="Add +5" />
</form>

</body>
</html>

But it doesnt react, just doesnt add + 5 to my database colums.

Edited by MuphN
Link to comment
Share on other sites

you need to set php's error_reporting to E_ALL and display_errors to ON in your php.ini to get php to help you. restart your web server to get any changes made to your php.ini to take effect. the reason for putting the setting into the php.ini is so that all php detected errors will be reported and you don't need to remember to put the settings into into your script for debugging and take them out when you are done.

 

your php code has some problems, partly because the original code you are trying to reuse wasn't written vary well (i posted a reply in your previous thread) and partly because you need to slow down and learn the basics of what you are doing before you can do them for your code and data.

 

1) using functions requires two things. a) the function definition, and b) the call to the function. your last posted code has a function definition, started by the function keyword, but you are never calling that function. also, in general, function definitions should be placed near the start of the code or be in an included file. they should also not be conditionally defined. your current function definition is inside the if(isset($_POST['add5'])){ ... } conditional statement, which is where your function call should actually be at.

 

2) your function code is assigning the prepared query statement handle to - $stmt. when you call the execute() method, it would be $stmt->execute().

 

3) the point where the header('Location: ./register_success.php'); statement is at (you should probably make that a page specific to what you are currently doing) is in the wrong place in the code and will redirect even if the prepare() statement fails. it should be moved up in the code by one } so that success will only be indicated if the prepare worked and the update at least ran without any errors.

Link to comment
Share on other sites

Thank you for showing my mistakes, so I created a script newly now, its not working, but IM trying to learn it now. As I understood the tut from a site. This should be correct?

<?php
include_once '../includes/db_connect.php';
include_once '../includes/functions.php';

sec_session_start(); 

		$str = getStr($mysqli);
		$agi = getAgi($mysqli);
		$range = getRange($mysqli);

		$host="localhost";
		$username="aassdasda";
		$password="maasdasd3";
		$database="asdasrudsfm";
		
		if(isset($_POST['add5'])){
			mysql_connect($host,$username,$password);
			@mysql_select_db($database) or die( "Unable to select database");
			$user_id = $_SESSION['user_id'];
			$query = "UPDATE members SET str = '$str + 5', agi = '$agi + 5', `range` = '$range + 5' WHERE id = '$user_id'";
			if(mysql_connect($host,$username,$password)) {
				echo "The db has been connected, going to update";
				mysql_query($query);
				if(mysql_query($query)) {
				echo "Querry has been updated!";
				mysql_close();	
				}else{
				echo "The querry didint update..";
				mysql_close();	
				}
			}else{
			echo "The connection was lost, it didint connect";
			mysql_close();	
			}
				
	}	
?>

It shows no errors, that its sucsessiful, but it dosnt actually update the db.

Edited by MuphN
Link to comment
Share on other sites

What information do you have in your

include_once '../includes/db_connect.php'; 

because it appears as if you are duplicating your connection to your database.

db_connecti.php
<?php
include_once 'psl-config.php';   // As functions.php is not included
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
?>

-------------------
psl-config.php 
<?php
define("HOST", "localhost");     // The host you want to connect to.
define("USER", "gasdasda");    // The database username. 
define("PASSWORD", "masdasdfgsd");    // The database password. 
define("DATABASE", "asfugm");    // The database name.
?>

but its defined as mysqli, It shouldnt be a prob I guess. I did remove the include, But it still doesnt add things to database, Maybe the '$str' + 5 is wrong, or the script is correct afterall?

Link to comment
Share on other sites

  • Solution

 

This should be correct?

No. Not sure why but you have changed from mysqli to to mysql_* database library. Stick with one database library throughout your code.

 

 

You also have an error in your SQL query. I think you mis-understood my reply here

 

 

Also you can add 5 to a fields value within the SQL query itself. You dont need to retrieve the old value and then add 5
UPDATE members SET str = str+5, agi = agi+5, `range` = `range`+5 WHERE id = ? LIMIT 1

str, agi and range are not PHP variables they are MySQL column names. For each of these columns it will add 5 to their current value. You do not need to get the current value and add 5 with PHP, MySQL can do this itself within the update query.

 

Reverting your code back to a function (with mac_gyver suggestions) you'll code it like this

<?php
include_once '../includes/db_connect.php';
include_once '../includes/functions.php';

// define the function first. Maybe move to functions.php
function getIns($mysqli) {
	if ($stmt = $mysqli->prepare("UPDATE members SET str = str+5, agi = agi+5, `range` = `range`+5 WHERE id = ? LIMIT 1")) {
		$user_id = $_SESSION['user_id'];
		$stmt->bind_param('i', $user_id);
                // check if the query did execute and that it affected a row
		if ($stmt->execute() && $mysqli->affected_rows > 0) {
			return true; // success return true
		}
	}
	
	return false; // all other cases return false. Something went wrong. Logging an error at this stage would be recommended.
}

sec_session_start(); 

if(isset($_POST['add5']))
{
	// call getIns function when $_POST['add5'] exists
	if(getIns($mysqli))
	{
		// getIns will return TRUE when record has been updated.
		// redirect to register_success.php
		header('Location: ../register_success.php');
	}
	else
	{
		// on failure it will return false.
		header('Location: ../error.php?err=Registration failure: INSERT');
	}
}	
?>
Edited by Ch0cu3r
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.