When getting data from the databas my if statement isn't working as expected, even though I have the $badgename in the database for that user I got "You get a new badge". But it dosen't put it on.
Im new to MySQLI so it's probably something I missed...
$numberofposts=$row['posts'];
$userid = $_SESSION['userid'];
$badgename = "Legend";
if($numberofposts >= 10){
$SQL = $mysqli->query("SELECT 1 FROM `badges` WHERE `mid`='$userid' AND 'badge' = '$badgename'");
$num = $SQL->num_rows;
if($num > 0){
echo "You got a new badge";
$mysqli->query("INSERT INTO badges ('mid', 'badge') VALUES ('$userid', '$badgename')");
}
else
{
echo "You already have this badge";
}
Thanks.
YOu have typo's in both queries:
replace the single quotes( ' ) on badge with backticks( ` )
from your select query.
then replace the single quotes with backticks in the insert query. ex:
$numberofposts=$row['posts'];
$userid = $_SESSION['userid'];
$badgename = "Legend";
if($numberofposts >= 10){
$SQL = $mysqli->query("SELECT 1 FROM `badges` WHERE `mid`='$userid' AND `badge` = '$badgename'");
$num = $SQL->num_rows;
if($num > 0){
echo "You got a new badge";
$mysqli->query("INSERT INTO `badges` (`mid`, `badge`) VALUES ('$userid', '$badgename')");
}
else
{
echo "You already have this badge";
}
Your INSERT query is wrong.
You have single-quotes around your column names, but you should be using backticks instead (like in the SELECT query)
Related
I have 3 queries like
$q1 = select email from tbl students
$q2 = select email from tbl corporates
$q3 = select email from tbl institutes
i want check to all 3 tables if email count is zero from all above then only do proceed like that,,
can i write like this:
if(mysqli_num_rows($q1) || mysqli_num_rows($q2) || mysqli_num_rows($q3) ==0){
proceed to process.
}else{
do nothing
}
My question is it a correct way to approach or anything is better left which i need to learn.
you need to use & instead of || and also check rows count for each of your mysql object
if(mysqli_num_rows($q1) == 0 && mysqli_num_rows($q2) == 0 && mysqli_num_rows($q3) ==0){
//proceed to process.
} else {
//do nothing
}
You should execute those queries first so you will have:
$db = mysqli_connect("localhost","my_user","my_password","my_db");
$q1 = "select email from tbl students";
$q2 = "select email from tbl corporates";
$q3 = "select email from tbl institutes";
$db_q1 = mysqli_query($db, $q1);
$db_q2 = mysqli_query($db, $q2);
$db_q3 = mysqli_query($db, $q3);
if(mysqli_num_rows($db_q1) == 0 && mysqli_num_rows($db_q2) == 0 && mysqli_num_rows($db_q3) == 0) {
proceed to process.
}
try can do easier using mysqli_multi_query()
$con=mysqli_connect("localhost","my_user","my_password","my_db");// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = select email from tbl students";
$sql .= select email from tbl corporates";
$sql .= "select email from tbl institutes";
// Execute multi query
if (mysqli_multi_query($con,$sql)){
do{ // Store first result set
if ($result=mysqli_store_result($con)) { // Fetch one and one row
if (mysqli_fetch_row($result) == 0) {
//your code here
}
}
}
i am trying to insert into multi table after select query return 0 (not found raws) select query working and insert query never done when submite "displayid" and there is no any syntax error
code:
<?php
if ($_POST["displayid"] == TRUE) {
$sqlid = "SELECT * FROM doc1 WHERE idnum ='$pidnum' AND stats='$ok'";
$result = mysqli_query($conn, $sqlid);
if (mysqli_num_rows($result) > 0) {
$sqlup = "UPDATE doc1 SET m_phone='$pm_phone', seen='$dataseen' WHERE idnum ='$pidnum'";
mysqli_query($conn, $sqlup);
$found = 1;
} else {
$found = 0;
$sqlfail = "INSERT INTO fail(fname,lname,tname,funame,idnum,m_phone,reg_date)
VALUES ('$pfname','$plname','$ptname','$pfuname','$pidnum','$pm_phone','$todaydate')";
$conn->query($sqlfail)
}
}
?>
Use this code:
$sqlfail = "INSERT INTO fail(fname,lname,tname,funame,idnum,m_phone,reg_date)
VALUES ('".$pfname."','".$plname."','".$ptname."','".$pfuname."','".$pidnum."','".$pm_phone."','".$todaydate."')";
make similar changes for update command as well
you actually have one error
$conn->query($sqlfail)
should be
$conn->query($sqlfail);
AND stats='$ok'";
i can't see a variable with this name i think you mean AND stats='ok'";
I'm having a user enter a desired name, then check the database to see if it exists before I make it. It's not working properly though, sometimes it echos the right thing, sometimes not.
$makeName = $_POST["userName"];
$nameFind = "SELECT userName FROM usertable WHERE userName = $makeName";
$nameCompare = mysqli_query($con, $nameFind);
if($nameCompare == false)
{
echo "This is a new name";
}
else
{
echo "Pick a new name please";
}
The query doesn't fail just because it returns no rows. Use mysqli_num_rows() to find out if there was a match or not.
Also xkcd
Don't do it that way.
Instead,
Create a unique constraint on the column "username".
Insert the user's desired name.
Trap the error when the desired name already exists.
Why? Your approach always requires two round-trips to the database, and it doesn't account for errors. And you have to trap errors anyway; there are lots of things that can go wrong with an insert statement.
Use quotes and escaping:
"select userName FROM usertable WHERE userName = '" . mysqli_real_escape_string($makeName) . "'"
And then use mysqli_num_rows()
$result = mysqli_query($query); $num_rows = mysqli_num_rows($result);
if(mysqli_num_rows($nameCompare))
{
echo "Pick a new name please";
}
else
{
echo "This is a new name";
}
this will check the result, if there is a row, it's already used.
You need two queries for that anyways
$username = mysqli_real_escape_string($con,$username);
$query = "SELECT * FROM tbl_login WHERE username='$username'";
$result = mysqli_query($con,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_array($result);
if( $num_row ==1 ) {
echo 'false';
}
else{
$query_insert = "INSERT INTO login (username, password)VALUES ('$username','$password');";
$result = mysqli_query($con,$query_insert) or die(mysqli_error());
}
I want to check and compare the information on my input form with information that is stored in my database.
Basically. if trainer, sessionslot eventdate is the same dbtrainer, dbeventdate dbsessionslot ECHO "Booked";
Else insert into booking table
I know very little about programming, could really do with some help on this one.
This is snippet of the code i am using.
if(isset($_GET['add'])){
$trainee = $_POST['txttrainer'];
$trainer = $_POST['txttrainee'];
$sessionSlot = $_POST['txtsession'];
$eventdate = $month."/".$day."/".$year;
$query = mysql_query("SELECT * FROM BOOKING WHERE trainer='$trainer' AND SessionSlot='$sessionslot");
$sqlinsert = "insert into booking (Trainee,Trainer,sessionSlot,eventDate,dateAdded) values ('".$trainee."','".$trainer."','".$sessionSlot."','".$eventdate."',now())";
$resultinsert = mysql_query($sqlinsert);
$numrows = mysql_num_rows($query);
if($numrows == 1) {
echo "this timeslot is booked"
if($resultinsert){
echo "Booking Successful....";
}else{
echo "Booking Failed";
}
}
}
if(isset($_GET['add'])){
$trainee = $_POST['txttrainer'];
$trainer = $_POST['txttrainee'];
$sessionSlot = $_POST['txtsession'];
$eventdate = $month."/".$day."/".$year;
$query = mysql_query("SELECT * FROM BOOKING WHERE trainer='$trainer' AND SessionSlot='$sessionslot");
$sqlinsert = "insert into booking (Trainee,Trainer,sessionSlot,eventDate,dateAdded) values ('".$trainee."','".$trainer."','".$sessionSlot."','".$eventdate."',now())";
$numrows = mysql_num_rows($query);
if($numrows >0) {
echo "this timeslot is booked"
}else{
$resultinsert = mysql_query($sqlinsert);
if(mysql_error()==""){
echo 'time slot booked';
}else{
echo 'error';
}
}
}
Explanation:
if there are rows selected, the timeslot is booked, else execute the query. If there is no error with the query, then print out success.
If you call mysql_query, the query is executed. So you're executing the INSERT before you check whether the SELECT returned a row or not.
That means you should place the INSERT part inside an if($numrows != 1) condition.
Please be aware that using mysql_query is deprecated: http://ch1.php.net/manual/en/function.mysql-query.php and you should use MySQLi or PDO_MySQL. Your code is vulnerable to SQL injections.
Thanks for checking out my question. I am trying to only update a value in my database if that field is null (so existing users won't be overwritten if someone tries to signup for a spot that is all ready taken and an error message will be output). I have listed below 2 of the most recent scripts I have tried. The first script works for updating the database if the select statement is not there but will overwrite users if entered for the same day and time. Thanks everybody!
$sql = ("SELECT `player1` FROM `users` where id = '$id' and Times = '$time'");
$result = $conn->query($sql);
if ($result->fetch_assoc === NULL) {
$update_player = ("UPDATE users SET player1 = '$name' where id = '$id' AND Times = '$time'")
if($update_player){
echo "Date for $name inserted successfully!";
}
}
else {
echo 'That spot is all ready taken!';
}
//2nd script
$query=mysql_query("UPDATE users SET
player1 = isNULL (player1, $name)
where id = '$id' AND Times = '$time'" );
if($query){
echo "Data for $name inserted successfully!";
}
else {
echo 'That spot is all ready taken!';
}
The following code should do the trick:
$query=mysql_query("UPDATE users SET
player1='$name'
where id = '$id' AND Times = '$time' AND player1 IS NULL" );
if(mysql_affected_rows() == 1){
echo "Data for $name inserted successfully!";
}
else {
echo 'That spot is all ready taken!';
}
Note that you should use pdo or mysqli functions instead.
Try This.
while($row = $result->fetch_assoc) {
if($row['player1'] == NULL){
$update_player = ("UPDATE users SET player1 = '$name' where id = '$id' AND Times = '$time'")
}