I'm trying to do a function that updates the field 'status' in the database from unpaid to paid on the click of a hyperlink/button. Here is what I'm doing but it is not working. Please help me debug my code.
function pay($idno, $secid) {
$query = "UPDATE payments SET status='paid' WHERE idNumber = '$idno' AND sec_id = '$secid'";
$result = mysqli_query($mysqli,$query); }
$sec_id = '2';
$idno= '3';
echo "<td><a href='' onclick='pay($idno, $secid);' >PAY NOW</a></td>";
}
This is what I attempted but nothing is happening. My SQL connection is correct I've checked already.
Without more information on the error it appears that your MySQL connection is undefined. You need to pass it as a parameter or reference it as a global:
function pay($idno, $secid) {
global $mysqli;
$query = "UPDATE payments SET status='paid' WHERE idNumber = '$idno' AND sec_id = '$secid'";
$result = mysqli_query($mysqli,$query); }
$sec_id = '2';
In addition, you can't call a PHP function from HTML as you are attempting to do. You must do an Ajax call to PHP from Javascript.
Related
I'm trying to make a bidding website and was writing a script which first shows the table of the product selected by the user, then allows them to put in their bidding amount. If the bidding value is less than the current bid, it goes back to the home page, or else it updates it.
The problem is that when the user presses the submit button and the isset function is called, the previous $amount and $id variables are no longer accessible and the SQL query does not run. This is probably due to the case that the above statements are executed again without the $_GET parameter receiving anything. Is there any way to change the scope of the variables or program execution so that they can be used in the POST function.
I tried printing the variables out but it was only giving me blankspace on doing the same.
My code for the same is as follows:
$db = mysqli_connect("localhost","root","","users");
$id = $_GET['id'];
$query = mysqli_query($db,"Select * from bid_items where product_id='$id'");
$array = mysqli_fetch_array($query);
$table_str = '<table id="product table"><tr>
<th>Item ID</th><th>Owner Name</th><th>Item Name</th><th>Closing date</th><th>Bid amount</th><th>Status</th><th>Bid</th><th>History</th></tr>';
$amount = $array["bid_amount"];
$table_str .= '<tr>';
$table_str .= '<td>'.$id.'</td><td>'.$array["owner_name"].'</td><td>'.$array["item_name"].'</td><td>'.$array["closing_date"].'</td><td>'.$amount.'</td><td>Open</td>'."<td><a href='add_bid.php?id={$array['product_id']}'>BID</a></td>".'</td><td>'.'<input type="submit" class="hist" value="history">'.'</td>';
$table_str .= '</tr>';
$table_str.='</table>';
echo $table_str;
if(isset($_POST['place_bid']))
{
$bid_val = mysqli_real_escape_string($db, $_POST['bid_amt']);
if($amount<$bid_val)
{
$db = mysqli_connect("localhost","root","","users");
$query = mysqli_query($db,"UPDATE bid_items set bid_amount='$bid_val' where product_id='$id'");
$result = mysqli_query($db,$sql1);
if($result)
{
header("Location:bidding.php");
}
}
else {
echo '<script>alert("Your bid amount is lesser than the current bid value")</script>';
header("Location:bidding.php");
}
}
?>
Is it needed to check if sid existed, casue this callback generates $sid if there is no $sid exists, so what I want to ask is, is there a possiblity that the $sid will be empty?
function read($sid) { //Callback function in session_set_save_handler
if(empty($sid)) {
//do something
}
}
Do you mean the function is called by session_set_save_handler?
If so, there is no need to worry. You can see these examples below from two different sites. They both not worry it.
Example
function read($SessionKey){
$sql = "SELECT uid FROM sessions WHERE session_id = '".$SessionKey."' limit 1";
$query =$this->db->query($sql);
if($row=$this->db->fetch_array($query)){
return $row['uid'];
}else{
return "";
}
}
Another example from http://php.net/manual/zh/function.session-set-save-handler.php:
function read($sessID) {
// fetch session-data
$res = mysql_query("SELECT session_data AS d FROM ws_sessions
WHERE session_id = '$sessID'
AND session_expires > ".time(),$this->dbHandle);
// return data or an empty string at failure
if($row = mysql_fetch_assoc($res))
return $row['d'];
return "";
}
I'm currently creating the account management system of my website and I decided to add a feature that enables me to declare weather a specific account is active or inactive. The data is retrieved from my mysql table.
$query = mysqli_query($DBConnect,"SELECT * from REG");
echo "<table class = 'table' style = 'width:90%;text-align:center'>";
while($getData = mysqli_fetch_assoc($query))
{
$username = $getData['uname'];
$fname = $getData['fname'];
$mname = $getData['mname'];
$lname = $getData['lname'];
$bday = $getData['bday'];
$email = $getData['email'];
$contact = $getData['contact'];
$gender = $getData['gender'];
if($getData['userlevel'] == 1)
{
$userlevel = "user";
}
else
{
$userlevel = "admin";
}
if($getData['status'] == 1)
{
$status = "active";
}
else
{
$status = "disabled";
}
echo "<tr>";
echo "<td>$username</td><td>$fname</td><td>$mname</td><td>$lname</td><td>$bday</td><td>$email</td><td>$contact</td><td>$gender</td><td>$userlevel</td><td>
<a href ='..\status.php' >$status </a></td></tr>";
}
echo "</table>";
This is the content of status.php
session_start();
$DBConnect = mysqli_connect("localhost", "root","","kenginakalbo")
or die ("Unable to connect".mysqli_error());
$query = mysqli_query($DBConnect,"SELECT * from REG where id = '$_SESSION[id]'");
while($getData = mysqli_fetch_assoc($query))
{
$status = $getData['status'];
echo "'$_SESSION[id]'";
}
if($status == 1)
{
$query = mysqli_query($DBConnect, "UPDATE REG SET status = 0 where id = '$_SESSION[id]'");
}
else if ($status == 0)
{
$query = mysqli_query($DBConnect, "UPDATE REG SET status = 1 where id = '$_SESSION[id]'");
}
header("Location: admin/login.php");
What I need to do is get the ID of the row clicked and declare it in my session so that it can be used in the "status.php" file. But in this code, the last id in the table is the one that is declared into the session because of the loop. How do I get the value of the id of the row that is clicked? (is there sort of like onClick function in php? Thank you.
pass id parameter,
status.php?id=$id;
in status.php
$id = $_GET['id'];
Change:
echo "<td>$username</td><td>$fname</td><td>$mname</td><td>$lname</td><td>$bday</td><td>$email</td><td>$contact</td><td>$gender</td><td>$userlevel</td><td>
<a href ='..\status.php' >$status </a></td></tr>";
to:
echo "<td>$username</td><td>$fname</td><td>$mname</td><td>$lname</td><td>$bday</td><td>$email</td><td>$contact</td><td>$gender</td><td>$userlevel</td><td>
<a href ='..\status.php{$getData['id']}' >$status </a></td></tr>";
And in your status.php change $_SESSION['id'] to $_GET['id']. But make sure to first prevent SQL injection either through mysql_real_escape_string($_GET['id']) or through PDO.
There is no onclick function in PHP but you can create a form with a button on each row that holds the value of the row that it is in. Have that form simply do a post or a get request back to the status.php. Adding it to the session might be a bad idea.
Instead of a button you can also create a link modify your loop so that there is a property called $rowid and increment it within your loop.
Perhaps, what you really want is to use a GET superglobal here. You can switch
for
Then, you use $_GET["userid"] instead of $_SESSION[id] on the status.php page.
Also, you dont need a while for the status page. You should check the number of results, if it was 1 it means the user exists, and then you just do a $getData = mysqli_fetch_assoc($query) without the while
I've been been on this for hours trying to find the small mistake I've done and I just can't find it... All I'm doing is calling a variable as global in a function and it's just not working even though it worked fine with the function above it...
I get an error saying mysqli is null...
include 'data/mysqli_connect.php';
function process_login(){
global $mysqli;
$username = $_SESSION['username'];
$sql = "SELECT * FROM auth WHERE user='".mysqli_real_escape_string($mysqli,$username)."'";
$query = mysqli_query($mysqli,$sql);
if(mysqli_num_rows($query)>0){
$sql = "DELETE FROM auth WHERE user='".mysqli_real_escape_string($mysqli,$username)."'";
$query = mysqli_query($mysqli,$sql);
if(!$query){
die(mysqli_error());
}
}
$sql = "INSERT INTO auth (user, session) VALUES ('".mysqli_real_escape_string($mysqli,$username)."', '".$_SESSION['id']."')";
$query = mysqli_query($mysqli,$sql);
if(!$query){
echo "Can not insert info into database!<br />". mysqli_error();
}else{
header("Location:chat.php");
}
}
function logout(){
global $mysqli;
$sql = "DELETE FROM auth WHERE session='".mysqli_real_escape_string($mysqli,$_SESSION['id']). "'";
$query = mysqli_query($mysqli,$sql);
if(!$query){
echo "Can not delete info from database!";
}else{
session_destroy();
header("Location: chat.php");
}
}
function get_username(){
global $mysqli;
$sql = "SELECT * FROM auth WHERE session='".mysqli_real_escape_string($mysqli,$_SESSION['id']). "'";
$query = mysqli_query($mysqli,$sql);
$row = mysqli_fetch_array($query);
if(mysqli_num_rows($query) == "0"){
$username = "Guest";
}else{
$username = $row['user'];
}
return $username;
}
function post_message(){
global $mysqli;
$text = addslashes(htmlentities(htmlspecialchars($_REQUEST['text'])));
$sql = "INSERT INTO chat (time, user, text) VALUES ('".date("H:i")."', '".get_username()."', '".$text."')";
$query = mysqli_query($mysqli,$sql);
if(!$query){
die(mysqli_error());
}
}
mysqli_connect.php
$mysqli = mysqli_connect(localhost, "info", "info", "info");
Like I said it worked on the function above this one but not this one, it doesn't make sens... I'm guessing I have a stupid mistake in there somewhere just don't know where.
By the way,the functions that I tested and work are process_login() and logout() and get_username()
get_username() runs first then process_login(). post_message() runs from a jquery code that calls it when i press on enter that probably works fine since i can see the error code when i press enter.
Oh and sorry about the bad code formatting,not sure how to fix it on here.
Thank you for any help or advice you may find.
How/When is post_message() called? From what you edited in, I can't find anything specifically in that that would clear the $mysqli variable - but to debug it, we would need more of the program flow.
Or you could create a 'hack' in the code and within post_message() after you declare global $mysqli;, do include 'data/mysqli_connect.php'; again since the $mysqli reference to your DB connection has been lost by then. But, ideally, you need to follow the flow of your code to figure out where to fix it correctly - and your flow seems not to be able to be posted fully, or is too great to post fully here.
(Too long for a comment, so this response comes in answer form, my apologies.)
Instead of making $mysqli a global variable, try passing it as an additional parameter to your functions. I was having the same problem and that's how i solved it. ie...
function post_message($mysqli){
$text = addslashes(htmlentities(htmlspecialchars($_REQUEST['text'])));
$sql = "INSERT INTO chat (time, user, text) VALUES ('".date("H:i")."',
'".get_username()."', '".$text."')";
$query = mysqli_query($mysqli,$sql);
if(!$query){
die(mysqli_error());
}
Hope this works for you.
I have this class am using to perform queries - insert, delete, drop create etc, but this time i created a method to update a table when the update have been submitted and to my surprise and hours of headache it is return success but not actually updating the record in the database am so confused, I have been debugging for hours to no avail
so i decided to share my worries to see if i can receive help as am actually 2 weeks old In OOP PHP
so here my class
class queryClass extends MYSQL{ //MYSQL is for connecting to database
//table fields
var $user_table = ''; //table names that will be used in all names, each query method will input its own table name
//connect to database
function dbconnect(){
MYSQL::dbconnect();
}
//prevent injection
function qry($query) {
$this->dbconnect();
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("?", "%s", $query);
$args = array_map('mysql_real_escape_string', $args);
array_unshift($args,$query);
$query = call_user_func_array('sprintf',$args);
$result = mysql_query($query) or die(mysql_error());
if($result){
return $result;
}else{
$error = "Error";
return $result;
}
//update quote function
function updatequote($table, $message1, $message2, $column_name1, $column_name2, $column_name3, $quote_id){
$this->dbconnect();
$this->quote_id = $quote_id;
echo $message1, $message2;
//make sure table name is set
$this->user_table = $table;
$this->column_name1 = $column_name1;
$this->column_name2 = $column_name2;
$this->column_name3 = $column_name3;
//execute login via qry function that prevents MySQL injections
$result = $this->qry("UPDATE ".$this->user_table." SET ".$this->column_name2."='?', ".$this->column_name3."='?'
WHERE ".$this->column_name1."='?';", $message1, $message2, $this->quote_id );
// $result = mysql_query("INSERT INTO ".$this->user_table."(username, password) VALUES('$username', '$password')");
if($result){
$_SESSION['success'] = "The Update Was Successfully Saved";
header('location: edit_quotes.html');
exit();
return true;
}else{
$_SESSION['success'] = "The Update Was Not Saved".mysql_error();
header('location: edit_quotes.html');
exit(); //do something on FAILED login
return false;
}
}
//quote form
function quoteEditorform($formname, $formclass, $formaction, $helptext, $first, $second){
//conect to DB
$this->dbconnect();
echo"
<form name=\"$formname\" method=\"post\" id=\"$formname\" class=\"$formclass\" enctype=\"application/x-www-form-urlencoded\" action=\"$formaction\">
<h2>$helptext</h2>
<div><label for=qoute>NGWA QUOTE
<input type=button value='Quote' onclick=\"wrapInTags(this.form.message1,'quote')\">insert [quote].[/quote]tags
</label>
<textarea name=\"message1\" cols=\"40\" rows=\"4\" onclick=\"copySelection(this)\">$first</textarea><br>
</div>
<div><label for=\"qoute\">ENGLISH MEANING
<input type=button value='Meaning' onclick=\"wrapInTags(this.form.message2,'meaning')\">
insert [meaning].[/meaning]tags
</label>
".$record['meaning']."
<textarea name=\"message2\" cols=\"40\" rows=\"4\" onclick=\"copySelection(this)\">$second</textarea></div>
<input name=\"action\" id=\"action\" value=\"sendeditedquote\" type=\"hidden\">
<div>
<input name=\"submit\" id=\"submitV value=\"Save\" type=\"submit\"></div>
</form>
<div align=\"center\">Read Before Posting</div>
"; }
function createquotetable($tablename){
//connect to DB
$this->dbconnect();
$qry = "CREATE TABLE IF NOT EXISTS ".$tablename."(
quote_id INT(8) NOT NULL AUTO_INCREMENT,
ngwaquote TEXT NOT NULL,
meaning TEXT NOT NULL,
saved_date date,
PRIMARY KEY (quote_id)
) TYPE=INNODB
";
$result = $this->qry($qry);
return;
}
here's my quote-editor.html after including my class files
// instantiate all other needed classes
$cleaner = new cleanPost();
$connect = new MySQL();
$connect->dbconnect();// connect to a database
$bbcode = new BBCode();
$log = new logmein();
if($_REQUEST['action'] == "sendeditedquote"){
//post all the values to the database using our main class
/*topic field checking */
if($_REQUEST['message1'] == "" || $_REQUEST['topic'] > 600) {
$errmsg_arr[] = 'Sorry You Can\'t Send An Empty Qoute OR quote greater than 500 characters at a time';
$errflag = true;
}
if($_REQUEST['message2'] == "" ) {
$errmsg_arr[] = 'Sorry You Can\'t Update With An Empty Qoute';
$errflag = true;
}
//If there are input validations, redirect back
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: edit_quotes.html");
exit();
}
$log->updatequote("quotes", $_REQUEST['message1'], $_REQUEST['message2'], "quote_id", "ngwaquote", "meaning", $cleaner->clean($_GET['quote_id']));
}
ai'ght when i perform the query the success/error line returns that the update was successful but on the other page where i display all available quotes the particular quote still is NOT updated
Anyone who's experienced such please tell me what am gon' do.
BEING ASKED THE LINE FOR THE RAW QUERY
HERE IS IT-
first is the the method that cleanse ouy my post and the I use it for query using $this->qry(somequeries here)
function qry($query) {
$this->dbconnect();
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("?", "%s", $query);
$args = array_map('mysql_real_escape_string', $args);
array_unshift($args,$query);
$query = call_user_func_array('sprintf',$args);
$result = mysql_query($query) or die(mysql_error());
if($result){
return $result;
}else{
$error = "Error";
return $result;
}
//update quote function using $this->qry()
function updatequote($table, $message1, $message2, $column_name1, $column_name2, $column_name3, $quote_id){
$this->dbconnect();
$this->quote_id = $quote_id;
echo $message1, $message2;
//make sure table name is set
$this->user_table = $table;
$this->column_name1 = $column_name1;
$this->column_name2 = $column_name2;
$this->column_name3 = $column_name3;
//execute login via ****qry function**** that prevents MySQL injections
$result = $this->qry("UPDATE ".$this->user_table." SET ".$this->column_name2."='?', ".$this->column_name3."='?'
WHERE ".$this->column_name1."='?';", $message1, $message2, $this->quote_id );
// $result = mysql_query("INSERT INTO ".$this->user_table."(username, password) VALUES('$username', '$password')");
if($result){
$_SESSION['success'] = "The Update Was Successfully Saved";
header('location: edit_quotes.html');
exit();
return true;
}else{
$_SESSION['success'] = "The Update Was Not Saved".mysql_error();
header('location: edit_quotes.html');
exit(); //do something on FAILED login
return false;
}
}
If the where clause of your update statement does not match any rows, the update statement will return success.
However it will not change anything.
Note that MySQL knows when a value has not really changed so the statement
UPDATE table1 SET col1 = 0 WHERE col1 = 0
Will always return 0 for the number of affected rows.
If you want to know if anything has been changed you need to call:
$rows_updated = mysql_affected_rows($this->connection);
or
$rows_updated = mysqli_affected_rows($this->connection); //if you're using mysqli
An update statement will only indicate failure is an error has occured.
A warning about SQL-injection
I notice that you use dynamic table and column names.
If those values are in any way alterable by a user or pass through superglobals that can be affected by another php session that can be affected by a user, you have an SQL-injection hole.
Here's how to secure yourself against that: How to prevent SQL injection with dynamic tablenames?
I think i have found the answer to my problem
In the place i had the $this->quote_id i later figured out that the page editor url was editor.html?quote_id=1
then when I submitted it will now process the form on a flat url === editor.html so my mistake was that I didn't request for the QUOTE ID when i was still on the editing url editor.html?quote_id=1 instead requesting for it when it was not possible ie in editor.html so it was meant to return empty quote id which i used to update thereby resulting in update success but not really updating anything
so
all I did was add an input tag hidden to get the quote_id being edited and then post it along with the rest of the form
So simple but took me me hours of rereading and re coding, wonderful,
small things cause much frustration
Thanks all
if the fields you are updating is not the same has the fields in the database, it will not update. although it return success simple means that it sees the table and connect to the database