PHP writing to MYSQL is variable equals 0 - php

I am trying to write to my database if a variable is equal to 0. The problem is that it still writes to the database even when the variables equals 1. What is wrong??
echo $new_user;
if ($new_user == 0) {
//SENT NEW USER WELCOME MESSAGE
$adminid = '9';
$welcomemessagetitle = 'Welcome to The site';
$welcomemessagecontent = 'Hello and welcome';
$addmessages = "INSERT into `user_messages`(`to_user`,`from_user`,`title`,`content`)
VALUES ('$userid','$adminid','$welcomemessagetitle','$welcomemessagecontent');";
$query = mysql_query($addmessages) or die(mysql_error());
//SET USER AS NOT NEW USER
$newuservalue = '1';
$notnewuser = "UPDATE users SET new_user = $newuservalue WHERE id = $userid" ;
$query2 = mysql_query($notnewuser) or die(mysql_error());
} elseif ($new_user == 1) {};
UPDATE FULL CODE::
<?php
session_start();
include "../includes/db_connect.php";
///profile/index.php
if($_SESSION['id'])
{
$username = $_SESSION['username'];
$userid = $_SESSION['id'];
//WRITE FIRST TIME LOGIN INFORMATION TO DATABASE
$sql="SELECT new_user from `users` WHERE `id`= $userid ";
$res=mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_assoc($res)) $new_user = $row['new_user'] ;
echo $new_user;
if ($new_user == 0) {
//SENT NEW USER WELCOME MESSAGE
$adminid = '9';
$welcomemessagetitle = 'Welcome to Escorvee';
$welcomemessagecontent = 'Hello and welcome';
$addmessages = "INSERT into `user_messages`(`to_user`,`from_user`,`title`,`content`)
VALUES ('$userid','$adminid','$welcomemessagetitle','$welcomemessagecontent');";
$query = mysql_query($addmessages) or die(mysql_error());
//SET USER AS NOT NEW USER
$newuservalue = '1';
$notnewuser = "UPDATE users SET new_user = $newuservalue WHERE id = $userid" ;
$query2 = mysql_query($notnewuser) or die(mysql_error());
} elseif ($new_user == 1) {};
}
?>

It the variable $new_user is the value 1 then your code won't be executed so I would guess one of the following applies:
$new_user isn't 1.
The database is being modified from another location.
Your script is being called twice.
To work out which you will have to provide more information in your question.

Related

How to draw an image into QR code with PHP

In my project I am trying to generate a QR code with an image in it based on stored blobs (1 Qr code + 1 logo) in my SQL table.
I have thw following code but can't seem to store the new image into my table.
Any help is appreciated.
<?php
//for connection
$sName = "localhost";
$sUser = "Username";
$sPass = "Password";
$sDb = "Database";
$Conn = new mysqli ($sName, $sUser, $sPass, $sDb);
//variables i pass from another app
$Email = mysqli_real_escape_string($Conn, $_POST["PassEmail"]);
$qContent = addslashes(file_get_contents($_FILES["file"]["tmp_name"]));
$qOverlay = addslashes (file_get_contents($_FILES["overlay"]["tmp_name"]));
$Sql = "SELECT * FROM `userprofile_login` INNER JOIN `userprofile_personalprofile` ON userprofile_login.userid = userprofile_personalprofile.userid WHERE userprofile_login.email = '".$Email."' ";
$Result = mysqli_query($Conn, $Sql);
if (mysqli_num_rows ($Result) > 0) {
$Row = mysqli_fetch_assoc ($Result);
$qCheckSql = "SELECT `userid` FROM `userprofile_qr` WHERE userid = '".$Row['userid']."' ";
$qCheckResult = mysqli_query($Conn, $qCheckSql);
$Row2 = mysqli_fetch_assoc($qCheckResult);
if (mysqli_num_rows ($qCheckResult) < 1) {
//if there 0 result from previous query, insert new data
$InsertSql = "INSERT INTO `userprofile_qr` (`userid`, `qrcode`, `overlay`)
VALUES ('".$Row['userid']."', '$qContent', '$qOverlay')";
$InsertResult = mysqli_query($Conn, $InsertSql);
} else {
//is there ia a result from the previous query, update data
$UpdateSql = "UPDATE `userprofile_qr` SET
`qrcode` = '$qContent',
`overlay` = '$qOverlay'
WHERE userid = '".$Row2['userid']."' ";
$UpdateResult = mysqli_query($Conn, $UpdateSql);
}
The first part works, the problem is the bottom part where I want to combine the QR code and the logo:
$qSql = "SELECT `qrcode`, `overlay` FROM `userprofile_qr` WHERE userid = '".$Row2['userid']."' ";
$qSelect = mysqli_query($Conn, $qSql);
include 'phpqrcode/qrlib.php';
$qRow = mysqli_fetch_assoc($qSelect);
$tImage = "<img src='data:image/png;base64,".base64_encode($qRow['qrcode'])."'/>";
$tOverlay = "<img src='data:image/png;base64,".base64_encode($qRow['overlay'])."'/>";
header("Content-type: image/png");
$aQr = imagecreatefromjpeg($tImage);
$QrWidth = imagesx($aQr);
$QrHeight = imagesy($aQr);
$aOverlay = imagecreatefrompng($tOverlay);
$OverlayWidth = imagesx($aOverlay);
$OverlayHeight = imagesy($aOverlay);
$OverlayQrWidth = $QrWidth / 3;
$OverlayQrHeight = $OverlayHeight / ($OverlayWidth / $OverlayQrWidth);
imagecopyresampled($aQr, $aOverlay, $OverlayQrWidth, $OverlayQrHeight, 0, 0, $OverlayQrWidth, $OverlayQrHeight, $OverlayWidth, $OverlayHeight);
imagepng($aQr);
$oImage = "<img src='data:image/png;base64,".base64_encode($aQr)."'/>";
$UpdateCombineSql = "UPDATE `userprofile_qr` SET
`combine` = '$oImage'
WHERE userid = '".$Row2['userid']."' ";
$CombineResult = mysqli_query($Conn, $UpdateCombineSql);
echo "Success";
}
?>

How to properly update a SQL table row using PHP

Current update: I've cleaned up the code, and there are still some issues.
NOTE this code runs every 3 seconds. The outermost 'else' statement seems to run, setting the time to 0 in the database table, but then there is no activity.
After the initial time of running, the outermost 'else' statement should never run, and the time value stored under the user's alias should keep updating with the latest time stamp, but it just sits at '0'.
This is the JS that runs the php file:
//CHECK FOR NEW CHAT MESSAGES
setInterval(function()
{
$.post("chat_update.php", function(data) { $("#rect_comments_text").append(data);} );
}, 3000);
Code:
<?php
session_start();
$alias = $_SESSION['username'];
$host = 'localhost';
$user = '*';
$pass = '*';
$database = 'vethergen_db_accounts';
$table = 'table_messages';
$time_table = 'table_chat_sync';
$connection = mysqli_connect($host, $user, $pass) or die ("Unable to connect!");
mysqli_select_db($connection,$database) or die ("Unable to select database!");
$timestamp = time();
$last_time_query = "SELECT alias FROM $time_table";
$last_time_result = mysqli_query($connection,$last_time_query);
$last_time_rows = mysqli_fetch_array($last_time_result);
if ($last_time_rows['alias'] === $alias)
{
$last_time = $last_time_rows['time'];
$query = "SELECT * FROM $table WHERE time > $last_time ORDER BY text_id ASC"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
//APPEND NEW MESSAGES
while($row = mysqli_fetch_array($result))
{
if ($row['alias'] === "Vether")
{
echo '<p id = "chat_text">'.'<b>'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
else
{
echo '<p id = "chat_text">'.'<b class = "bold_green">'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
echo '<hr class = "chat_line"></hr>';
}
//UPDATE LAST SYNC TIME
$update_query = "UPDATE $time_table SET time = '$timestamp' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
else
{
echo '<p> HERE </p>';
$update_query = "INSERT INTO $time_table (alias, time) VALUES('$alias','0')";
mysqli_query($connection,$update_query);
}
?>
You try this
$sql_update = "UPDATE time_table SET time= '$timestamp' WHERE alias = '$alias'";
if ($con->query($sql_update ) === TRUE) {
}
else{
echo "Error: " . $sql_update . "<br>" . $con->error;
}
You need to only check mysqli_num_rows to whether to insert or update data. You have to add ' around $alias in select query also. change your code as below:
//EITHER UPDATE THE EXISTING VALUE OR CREATE ONE FOR FIRST TIME VISITORS...
$last_time_query = "SELECT * FROM $time_table WHERE alias = '$alias'"; //change here add '
$last_time_result = mysqli_query($connection,$last_time_query);
if (mysqli_num_rows($last_time_result) == 0) //Only check number of rows
{
$update_query = "INSERT INTO $time_table (alias, time) VALUES('$alias','$timestamp')";
mysqli_query($connection,$update_query);
}
else
{
$update_query = "UPDATE $time_table SET time = '$timestamp' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}

Multiple queries with addition of column in another table

Please i would like to delete a record from a particular table and insert same record into another table. this is working fine if all the tables contain same columns but i need to add another column to the table where the deleted record is inserted.
here is my code thank you
<?php
// connect to the database
$con=mysqli_connect("localhost", "root", "");
if(mysqli_select_db($con, "e-office"));
$execute ='';
$Posting_User = mysqli_escape_string($con, $_SESSION[('Uname')]);
// confirm that the 'id' variable has been set
if (isset($_GET['execute'])) $execute = $_GET['execute'];
{
// get the 'id' variable from the URL
if($execute=='delete'){
$id = $_GET['id'];
// delete record from database
$sql = mysqli_query($con, "INSERT INTO tbl_income_approved SELECT * FROM
tbl_income WHERE (trn_no = '$id' AND Approved_by ='$Posting_User') ");
$sql = mysqli_query($con, "DELETE FROM tbl_income WHERE trn_no = '$id'");
if($sql)
// redirect user after delete is successful
header("Location: income_report.php");
else
// if the 'id' variable isn't set, redirect the user
echo "query not successful";
}
}
?>
To God be the glory! I have a working code now, thanks all
<?php
session_start();
if(!$_SESSION[('Uname')]){
header("location:login.php");
}
// connect to the database
$con=mysqli_connect("localhost", "root", "");
if(mysqli_select_db($con, "e-office"));
$execute ='';
$Posting_User = mysqli_escape_string($con, $_SESSION[('Uname')]);
// confirm that the 'id' variable has been set
if (isset($_GET['execute'])) $execute = $_GET['execute'];
{
$id = $_GET['id'];
///testing
$sql="SELECT * FROM tbl_income WHERE trn_no='$id'";
$result=mysqli_query($con, $sql);
//echo $count;
while($row = mysqli_fetch_assoc($result)){
$Posting_User = mysqli_escape_string($con, $row['Posting_User']);
$date = mysqli_escape_string($con, $row['date']);
$rno = mysqli_escape_string($con, $row['rno']);
$source = mysqli_escape_string($con, $row['source']);
$subsidiary = mysqli_escape_string($con, $row['subsidiary']);
$deposit = mysqli_escape_string($con, $row['deposit']);
$amount = mysqli_escape_string($con, $row['amount']);
$narration = mysqli_escape_string($con, $row['narration']);
$timestamp = mysqli_escape_string($con, $row['timestamp']);
$trn_no = mysqli_escape_string($con, $row['trn_no']);
$Approved_by = mysqli_escape_string($con, $_SESSION[('Uname')]);
$sql=mysqli_query($con, "INSERT INTO tbl_income_approved (Posting_User, date, rno, subsidiary, deposit, source, amount, narration, Approved_by) VALUES ('$Posting_User','$date','$rno', '$subsidiary', '$deposit', '$source', '$amount', '$narration', '$Approved_by')");
}
///close testing
// get the 'id' variable from the URL
if($execute=='delete'){
$id = $_GET['id'];
$sql = mysqli_query($con, "DELETE FROM tbl_income WHERE trn_no = '$id'");
if($sql)
// redirect user after delete is successful
header("Location: income_report.php");
else
// if the 'id' variable isn't set, redirect the user
echo "query not successful";
}
}
?>

Problems updating correct row in databse with php

I'm trying to create a voting system for artists played on my radio station. I'm using the source code from: http://dl.howcode.org/download/97ff383c7d4dc9939c65c9e6fab2a5dc
The problem I have found is that the votes update using the number from the first row in the database no matter which option is selected, thus if for instance the first row has 3 votes in and the user tries to vote on someone with 0 votes, it will change the votes for the correct artist to 4 instead of 1... I hope that makes sense?
The code I have is:
[EDIT] I have changed the queries to fetch assoc to make it easier to understand.
<?php
$voteID = $_GET['voteID'];
$connect = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx');
$query = "SELECT * FROM listenervotes WHERE voteID='$voteID'" ;
$q = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($q)){
$id = $row["id"];
$voteTitle = $row["voteTitle"];
$voteID = $row["voteID"];
$ipaddress = $row["ipAddress"];
echo "<h3>$voteTitle</h3>";
?>
<table>
<form action="" method="POST">
<?php
$artists = "SELECT * FROM artists WHERE voteID='$voteID'" ;
$q2 = mysqli_query($connect, $artists);
while($r = mysqli_fetch_assoc($q2)){
$artist = $r["artistName"];
$votes = $r["votes"];
$genre = $r["genre"];
$ip = $_SERVER['REMOTE_ADDR'];
$newIpAddress = $ipaddress."$ip, ";
$newVotes = $votes + 1;
if (isset($_POST['vote'])) {
$voteOption = $_POST['voteOption'];
if ($voteOption == ""){
die("You haven't selected anyone!");
}else{
$ipaddressE = explode(",", $ipaddress);
if(in_array($ip, $ipaddressE)){
die("You have already voted!");
}else{
mysqli_query($connect, "UPDATE artists SET votes='$newVotes' WHERE voteID='$voteID' AND artistName='$voteOption'");
mysqli_query($connect, "UPDATE listenervotes SET ipaddress='$newIpAddress' WHERE voteID='$voteID'");
die('You voted successfully!<br><tr><td>'.$artist.'</td><td>'.$genre.'</td><td>'.$votes.' Votes</td></tr>');
}
}
}
echo '<tr><td>'.$artist.'</td><td>'.$genre.'</td><td><input type="radio" name="voteOption" value="'.$artist.'"</td></tr>';
}
}
?>
I could be missing something obvious, in my mind I'm thinking that I somehow need to iterate through the rows before setting the new value, if so, how and where?
It looks like you are always looping over all rows and updating the relevant row with the first value found. Adding a check on the ID should do:
<?php
$voteID = $_GET['voteID'];
$connect = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx');
$query = "SELECT * FROM listenervotes WHERE voteID='$voteID'" ;
$q = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($q)){
$id = $row["id"];
$voteTitle = $row["voteTitle"];
$voteID = $row["voteID"];
$ipaddress = $row["ipAddress"];
echo "<h3>$voteTitle</h3>";
?>
<table>
<form action="" method="POST">
<?php
$artists = "SELECT * FROM artists WHERE voteID='$voteID'" ;
$q2 = mysqli_query($connect, $artists);
while($r = mysqli_fetch_assoc($q2)){
$artist = $r["artistName"];
$votes = $r["votes"];
$genre = $r["genre"];
$ip = $_SERVER['REMOTE_ADDR'];
$newIpAddress = $ipaddress."$ip, ";
$newVotes = $votes + 1;
if (isset($_POST['vote'])) {
$voteOption = $_POST['voteOption'];
if ($voteOption == ""){
die("You haven't selected anyone!");
}else{
$ipaddressE = explode(",", $ipaddress);
if(in_array($ip, $ipaddressE)){
die("You have already voted!");
}elseif ($voteOption === $artist) { // Don't run UPDATE when we're on the wrong row.
mysqli_query($connect, "UPDATE artists SET votes='$newVotes' WHERE voteID='$voteID' AND artistName='$voteOption'");
mysqli_query($connect, "UPDATE listenervotes SET ipaddress='$newIpAddress' WHERE voteID='$voteID'");
die('You voted successfully!<br><tr><td>'.$artist.'</td><td>'.$genre.'</td><td>'.$votes.' Votes</td></tr>');
}
}
}
echo '<tr><td>'.$artist.'</td><td>'.$genre.'</td><td><input type="radio" name="voteOption" value="'.$artist.'"</td></tr>';
}
}
?>

PHP SQL Not updating row in database

I'm currently making a simple script that takes a user input named comments and putting it in a database. Every time I use the same email, I want it to overwrite their last entry. However, it keeps putting a new entry every time. Here is my code:
if($comments){
try{
echo "<img width=\"245\" height=\"130\" src=\"logo.png\"/><br/>";
echo "<h1>Thank you. You should receive your order on xx-xx-xx</h1>";
$TF = "TRUE";
if($numrows == 0){
$postquery = "INSERT INTO TTT25 (email,card,changes,comments) VALUES ('$email','$businesscard','$TF','$comments')";
$querythepost = sqlsrv_query($conn, $postquery);
}
else{
$postquery = "UPDATE TTT25 SET changes = '$TF', comments = '$comments' WHERE email = '$email'";
$querythepost = sqlsrv_query($conn, $postquery);
}
}
catch(Exception $e){}
}
elseif($optout=="false"){
echo "<img width=\"245\" height=\"130\" src=\"logo.png\"/><br/>";
echo "<h1>Thank you. You should receive your order on xx-xx-xx</h1>";
$TF = "FALSE";
$comments = "";
if($numrows == 0){
$postquery = "INSERT INTO TTT25 (email,card,changes,comments) VALUES ('$email','$businesscard','$TF','$comments')";
$querythepost = sqlsrv_query($conn, $postquery);
}
else{
$postquery = "UPDATE TTT25 SET changes = '$TF', comments = '$comments' WHERE email = '$email'";
$querythepost = sqlsrv_query($conn, $postquery);
}
}
Sorry it must have cut off:
my num rows and other variables defined before the conditional statements:
$optout = $_GET['opt'];
$encodedemail = $_GET['email'];
$email = base64_decode($encodedemail);
$originalcard = base64_decode($_GET['card']);
$businesscard = $originalcard;
$comments = $_POST['comments'];
//$primary = md5(uniqid(rand (), true)); no longer needed
$postquery;
$TF;
$sqlmatch = sqlsrv_query("SELECT * FROM TTT25 WHERE email = '".$email."'");
$numrows = sqlsrv_num_rows($sqlmatch);
echo $numrows;

Categories