My Problem
I'm trying to give persons over 16 special options on the website I am creating, but I'm struggling to get the PHP to check the age and then change the column to 1 for Yes or 0 for No.
What I've Tried
if ($account['age']>=16) {
echo 'True';
$sql = 'UPDATE accounts SET o16 = 1 WHERE id = ?';
} else {
echo 'False';
$sql = 'UPDATE accounts SET o16 = 0 WHERE id = ?';
};?>
I'm using MariaDB SQL at this moment.
It returns the values true or false but it does not change the value of the column.
I would be grateful if someone could help. I don't know if I have to do something different or if there's another way I could do this.
But what are you doing about the SQL? You are just doing an update but you don't execute it. Try somethings like this.
<?php
// $user_id = you put users id here, if you want to do it over session or something.
if ($account['age']>=16) {
echo 'True';
$sql = 'UPDATE accounts SET o16 = 1 WHERE id = ?';
$sql->bind_param('i',//$user_id);
$sql->execute();
} else {
echo 'False';
$sql = 'UPDATE accounts SET o16 = 0 WHERE id = ?';
$sql->bind_param('i',//$user_id);
$sql->execute();
}
Hope this helps you in some way, i think this could be right, but correct me if im wrong :)
use print_r($this->db->last_query()); to see the query and check under SQL execution in database server. You can check where you went wrong.
Related
I have been stuck on this for the past 2 hours and can't see what the problem is here.
When I execute the SQL in phpmyadmin manually it runs fine when i substitute :item_quant and :item_code for their true values.
When adding an echo on return false to see if $item_quant and $item_code are the correct values it shows them as the correct values.
$sql = "UPDATE inventory SET item_quant=item_quant+:item_quant WHERE item_code=':item_code' LIMIT 1";
$query = $database->prepare($sql);
$result = $query->execute(array(':item_quant' => $item_quant, ':item_code' => $item_code));
if ($result) {
return true;
}
return false;
Any help or insight as to why this would be failing would be greatly appreciated.
Placeholders must not be put inside quotes.
$sql = "UPDATE inventory SET item_quant=item_quant+:item_quant WHERE item_code=:item_code LIMIT 1";
Try removing the quotations:
$sql = "UPDATE inventory SET item_quant=item_quant+:item_quant WHERE item_code=:item_code LIMIT 1";
First post, here it goes.
So this is the code that I have so far:
include('Connection/connect-test.php');
$selected1 = $_POST['selected'];
$sqlget = "SELECT paymentid FROM highschoolpayment WHERE hsgameid = '$selected1'";
$sqldata = mysqli_query($dbcon, $sqlget);
$sqlupdate = "UPDATE highschool SET paymentid = '$sqldata' WHERE hsgameid = '$selected1'";
mysqli_query($dbcon, $sqlupdate);
What I'm trying to do is grab the 'paymentid' from the 'highschoolpayment' table and store that value into the $sqldata variable (line 4). Then I want to update a value in the 'highschool' table using the value that I got from line 4 as well as a value that was pulled from a POST submission (line 6). I know for a fact that the first 3 lines execute as they should. It is after those lines when things become iffy. I don't see the form (reappear) like I normally would when everything else is working. To me, this indicates that the PHP has successfully run. I go to the 'highschool' table but I don't see the value (paymentid) that I am expecting to see. I personally can't think of a single reason why this wouldn't work, but, I am not that experienced in PHP or MySQL so I am open to any help that I can get.
I hope this makes sense without seeing the structure of the tables but if I need to post those, let me know. I've spent a couple hours trying to troubleshoot this problem but with no forward progress.
Thanks!
Assuming this query returns only one row:
$sqldata = mysqli_query($dbcon, $sqlget);
$row = mysqli_fetch_array($sqldata);
$paymentid = $row['paymentid']; // then use $paymentid in the next query
$sqlupdate = "UPDATE highschool SET paymentid = '$paymentid'
WHERE hsgameid = '$selected1'";
if(mysqli_query($dbcon, $sqlupdate)){
echo 'Update successfull';
} else {
echo 'Update query is wrong. The query generated was <br />'.$sqlupdate;
}
try like this,
include('Connection/connect-test.php');
$selected1 = $_POST['selected'];
$sqlupdate = "UPDATE highschool SET paymentid = (select paymentid FROM highschoolpayment WHERE hsgameid = '$selected1') where hsgameid = '$selected1'";
mysqli_query($dbcon, $sqlupdate);
you need to do fetch_assoc(), and while you are at it you should parameterize your query to make it more secure, good practice for the future. here is what your code should look like
$selected1 = $_POST['selected'];
$connect = mysqli_connect("localhost","user","pass","database");//i connect this way to my database
//the first statement that will get your paymentid
$stmt = $connect->prepare("SELECT paymentid FROM highschoolpayment WHERE hsgameid = ?")
mysqli_stmt_bind_param($stmt, 's', $selected1);//'s' is for string, 'i' for int, google rest
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){//it fetches each id
//the second statement that will use the payment id and update the database
$stmt2 = $connect->prepare("UPDATE highschool SET paymentid = ? WHERE hsgameid = ? ;")
mysqli_stmt_bind_param($stmt2, 'ss',$row['paymentid'], $selected1 );//'s' is for string, 'i' for int, google rest
$stmt2->execute();
$stmt2->close();
}
$stmt->close();
I just threw this quickly together, so if anyone sees something wrong don't hesitate to edit it or mark it down if completely wrong, Would rather that.
I am trying to award a user a badge if their points are 10,000. There is a field in the table called badge1 with a default value set to locked and a points row. I am running and if statement that if the users points are 10,000 then UPDATE the badge1 row from locked to unlocked. My code seems correct but It is neither updating the the field nor showing any errors.
<?php
$db = new PDO('mysql:host=hostname;dbname=databasename;charset=UTF-8', 'username', 'password');
$username = $_SESSION['username'];
$q = "SELECT Points FROM login_users WHERE username ='$username'");
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$Points = $row['Points'];
if($Points == "10000") {
$awardBadge = $db->exec("UPDATE login_users SET badge1=unlocked WHERE username=?");
$Points->execute(array($username))
} else {
print "";
}
?>
UPDATE:
I managed to get it working.. however the problem is I am a bit new to converting old sql to PDO so this is not very secure but this is what works:
<?php
$connect = mysql_connect("host","username","password");
mysql_select_db("databasename");
$username = $_SESSION['jigowatt']['username'];
$q = "SELECT Points FROM login_users WHERE username = ('$username')";
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$Points = $row['Points'];
?>
// Place somewhere
<?php
if($Points >= "10000") {
$result = mysql_query("UPDATE login_users SET maneki='unlocked' WHERE username='$username'");
} else {
print "Badge has not been unlocked";
}
?>
"10000" string should be an 10000 int
And also, you might want to make a choice here too. You're using 2 types of setting up a mysql-database connection. the old-fashioned mysql_function() way and the new fancy PDO method.
I think working with the PDO version is safer, since newer PHP versions will not support the old methods anymore... That... and it just looks dirty ;P
Try this:
<?php
session_start();
$dbSession = new PDO('mysql:host=***;dbname=***', '***', '***');
$selectQuery = $dbSession->prepare('
SELECT `User`.`Points`
FROM `login_users` AS `User`
WHERE `User`.`username` = :username
');
$selectQuery->bindParam(':username', $_SESSION['username'], PDO::PARAM_STR);
$user = $selectQuery->fetch(PDO::FETCH_ASSOC);
if ( !empty($user) && $user['Points'] == 10000 ) {
$updateQuery = $dbSession->prepare('
UPDATE `login_users`
SET `badge1` = \'unlocked\'
WHERE `username` = :username');
$updateQuery->bindParam(':username', $_SESSION['username'], PDO::PARAM_STR);
$updateQuery->execute();
}
?>
Usefull resources:
PHP Database Objects (PDO)
PHP Sessions
MySQL Datamanipulation
MySQL SELECT syntax
MySQL UPDATE syntax
Better check if >= 10000 and not yet awarded. That could you also be done in SQL so you don't need that logic in PHP.
UPDATE login_users SET badge1=unlocked WHERE points >= 10000 and badget1 <> unlocked
The issue is caused by $point value which actually is not equal to 10000, but is NULL.
So I propose to always use var_dump() to get the actual value of the variable in such cases.
one tip: check the PDO docs, before you write php code! You use PDO and mysql commands on same time for same job!?? why???
Try this if($Points == 10000) instead of if($Points == "10000")
mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier.
if($Points==10000){
$awardBadge = $db->prepare("UPDATE login_users SET badge1=unlocked WHERE username=?");
$awardBadge->execute(array($username));
}
I was wondering if someone would be able to shed some light on how I may overcome this problem.
I'm trying to add and update information on a database, so when a user first enters completes the questionnaire its fine and it works, However when they go back to update the questionnaire it throws an error, "Please go back and try again".
I have updated the PHP code with the recommendations given to me so far.
Thank You.
PHP code:
function updatePartCTQ_part1($questionAns, $memberid) {
//First Insert MemberID
$ctqmemberinsert = "INSERT INTO ctq_questionnaire (user_id) VALUES ('$memberid')";
$addresult = mysqli_query($ctqmemberinsert);
if ($addresult) {
$update = "UPDATE ctq_questionnaire SET Item1= '{$questionAns[0]}', Item2 = '{$questionAns[1]}' WHERE user_id = '$memberid'";
mysqli_query($conn, $update);
} else {
echo 'Please go back and try again';
}
}
Any help will be greatly appreciated.
Finished Code
Thanks to Michael and the rest of the guys I was able to get the code working, so I thought I'd post an update, if anyone else gets stuck they'd be able to have a glance at the working version of the code:
function updatePartCTQ_part1($questionAns, $memberid) {
//Check whether user exists
$exists = mysql_query("SELECT * FROM ct1_questionnaire WHERE user_id = '$memberid'");
if (mysql_num_rows($exists) === 0) {
// Doesn't exist. INSERT User into Table
$ctqmemberinsert = "INSERT INTO ctq_questionnaire (user_id) VALUES ('$memberid')";
mysqli_query($ctqmemberinsert);
}
// UDPATE after INSERT
$update = "UPDATE ctq_questionnaire SET Item1= '{$questionAns[0]}', Item2 = '{$questionAns[1]}, Item3 = '{$questionAns[2]}',
Item4 = '{$questionAns[3]}',Item5 = '{$questionAns[4]}', Item6 = '{$questionAns[5]}', Item7 = '{$questionAns[6]}',
Item8 = '{$questionAns[7]}', Item9 = '{$questionAns[8]}', Item10 = '{$questionAns[9]}', Item11 = '{$questionAns[10]}',
Item12 = '{$questionAns[11]}', Item13 = '{$questionAns[12]}', Item14 = '{$questionAns[13]}', Item15 = '{$questionAns[14]}'
WHERE user_id = '$memberid'";
mysql_query($update);
}
Your UPDATE syntax is incorrect. You must not repeat the SET keyword:
$update = "UPDATE ctq_questionnaire SET Item1= '{$questionAns[0]}', Item2 = '{$questionAns[1]}' WHERE user_id = '$memberid'";
//-------------------------------------------------------------^^^^^^^ no SET here
For readability it is recommended to enclose the array values in {}, although your way should work.
Note that your try/catch isn't going to be of much use since mysql_query() does not throw an exception. Instead it will just return FALSE on error. Instead, store it in a variable and test for TRUE/FALSE as you did with the INSERT.
// We assume these values have already been validated and escaped with mysql_real_escape_string()...
$update = "UPDATE ctq_questionnaire SET Item1= '{$questionAns[0]}', Item2 = '{$questionAns[1]}' WHERE user_id = '$memberid'";
$upd_result = mysql_query($update);
if ($upd_result) {
// ok
}
else {
// error.
}
Finally, and I suspect you've heard this before, the old mysql_*() functions are scheduled for deprecation. Consider moving to an API which supports prepared statements, like MySQLi or PDO.
Update
Assuming you have a unique index or PK on ctq_questionnaire.user_id on subsequent calls, the first query will error and your second won't be run. The simplest fix is to use INSERT IGNORE, which will treat key violations as successful.
$ctqmemberinsert = "INSERT IGNORE INTO ctq_questionnaire (user_id) VALUES ('$memberid')";
A more complicated solution is to first test if the username exists in the table with a SELECT, and if not, do the INSERT.
$exists_q = mysql_query("SELECT 1 FROM ct1_questionnaire WHERE user_id = '$memberid'");
if (mysql_num_rows($exists_q) === 0) {
// Doesn't exist. Do the INSERT query
}
// proceed to the UDPATE after INSERTing if necessary
Just change your insertion to this:
$ctqmemberinsert = "INSERT INTO `ctq_questionnaire` (`user_id`, `Item1`, `Item2`)
VALUES ( '$memberid', '" .
mysql_real_escape_string($questionAns[0]) . "', '" .
mysql_real_escape_string($questionAns[1]) . "' )";
I'm trying to get this to update the messages table in my database, and set the message_read cell to 1.
But I can't get it to work. It always says 0 where it supposed to change to 1.
I'm pretty sure the variables are right.
$q = "UPDATE messages SET message_read='1' WHERE id='$messageid' AND to_user='$usermsg'";
mysql_query($q);
I do not get any errors either.
"usermsg" = the session username
"messageid" = the id of the message
Try this:
$q = "UPDATE messages SET message_read='1' WHERE id=".mysql_real_escape_string($messageid)." AND to_user='".mysql_real_escape_string($usermsg)."';";
$result = mysql_query($q);
if(!$result)
{
die( mysql_error() );
}
else
{
echo 'Number of affected rows:'.mysql_affected_rows();
}
If there was something wrong with your query you will be able to see the error printed on screen. And if not you can see how many rows were affected by the query.
I've also added some SQL injection projection just in case.
I think this is the correct syntax:
$q = "UPDATE messages SET message_read = 1 WHERE id = ".$messageid." AND to_user='".$usermsg."'";
Don't use quotes when the field type is INT.