I Am trying to check if the REF number added when creating a new mysql row is already in use. I don't have problems in adding a new row however, the script does not check the database first.
if ($_POST['add_new_bus']){
if (($_POST['add_ref'] != "")&&($_POST['add_name'] != "")&&($_POST['add_address'] != "")&&($_POST['add_area'] != "")){
$add_ref = $_POST['add_ref'];
$add_name = $_POST['add_name'];
$add_address = $_POST['add_address'];
$add_area = $_POST['add_area'];
$chech_sql = "INSERT INTO `Details` (`REF`) VALUES ('$add_ref')";
if (!($conn->query($chech_sql))) {
echo "REF is already in use";
}else{
mysqli_query($conn, "INSERT INTO `Details` (`REF`, `NAME`, `ADDRESS`, `AREA`) VALUES ('$add_ref', '$add_name', '$add_address', '$add_area')");
echo "<p style='float:right;'>" . $_POST['add_name'] . " " . "has been added to the register with REF number:" . " " . $_POST['add_ref'] . "</p>";
}
}
Any Idea how to check if the REF number is already in use?
For giving you a correct idea how to do it, Please check below code:-
<?php
if (isset($_POST['add_new_bus']){
if (($_POST['add_ref'] != "") &&($_POST['add_name'] != "")&&($_POST['add_address'] != "")&&($_POST['add_area'] != "")){
$add_ref = $_POST['add_ref'];
$add_name = $_POST['add_name'];
$add_address = $_POST['add_address'];
$add_area = $_POST['add_area'];
$chech_sql = "SELECT add_ref FROM Details WHERE add_ref = '".$add_ref."'";
$result = $conn->query($chech_sql);
if (mysqli_num_rows($result) > 0) {
echo "REF is already in use";
}else{
mysqli_query($conn, "INSERT INTO `Details` (`REF`, `NAME`, `ADDRESS`, `AREA`) VALUES ('$add_ref', '$add_name', '$add_address', '$add_area')");
echo "<p style='float:right;'>" . $_POST['add_name'] . " " . "has been added to the register with REF number:" . " " . $_POST['add_ref'] . "</p>";
}
}
}
?>
Note:- checking variables value and other things is up to you. because you only have them in your code.thanks.
Related
I have a phpscript which takes values (Manually entered) and inserts into the column in the database. Now I want to know how would I be adding new values to the existing values for the same card number entered.
if(isset($_POST['insert-btn'])){
#$cardnumber=$_POST['cardnumber'];
#$amount=$_POST['amount'];
if($cardnumber=="" || $amount==""){
echo '<script type="text/javascript">alert("Insert values in all fields")</script>';
}
else{
$query = "insert into Client_Details values('$cardnumber',$amount/2)";
$query_run=mysqli_query($con,$query);
if($query_run){
echo '<script type="text/javascript">alert("Values inserted successfully")</script>';
}
else{
echo '<script type="text/javascript">alert("Values not inserted successfully")</script>';
}
}
}
?>
For example , I have
card number: _________
Sale value: __________
Now for the same card number the sale value entered every different time should be added. If anybody can help me with that. It would be helpful.
Before you insert data into DB, check whether a record for the card number already exists in the DB.
If it exists, use UPDATE query else use INSERT query.
Try the below code:
<?php
if (isset($_POST['insert-btn']))
{
#$cardnumber = $_POST['cardnumber'];
#$amount = $_POST['amount'];
if ($cardnumber == "" || $amount == "")
{
echo '<script type="text/javascript">alert("Insert values in all fields")</script>';
}
else
{
$newQuery = mysqli_query($con, "SELECT * FROM Client_Details WHERE cardnumber='" . $cardnumber . "'");
if (mysqli_num_rows($newQuery) > 0)
{
$query = "UPDATE Client_Details SET amount = amount + '" . $amount . "' WHERE cardnumber = '" . $cardnumber . "'";
}
else
{
$query = "INSERT into Client_Details values('$cardnumber',$amount/2)";
}
$query_run = mysqli_query($con, $query);
if ($query_run)
{
echo '<script type="text/javascript">alert("Values inserted successfully")</script>';
}
else
{
echo '<script type="text/javascript">alert("Values not inserted successfully")</script>';
}
}
}
*Modify the table name and column names accordingly
<?php
include('session.php');
?>
<?php
$conn = new mysqli("127.0.0.1","root","","foo");
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
$sew = $_SESSION['login_user'];
$a = $_GET["en"];
$l = 1;
$d = -1;
if($a == 1)
{
$sqlw = " INSERT into dlkeuser VALUES('$a','$sew')" ;
if ($conn->query($sqlw) === FALSE)
{
echo "you have already disliked the song";
}
else
{
//query1
$sql = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' ";
//query2
$sql = "UPDATE liking
SET count = count - 1 ";
if ($conn->query($sql) === TRUE) {
echo "you disliked the song";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
In this php code snippet, query1 is not working whereas query 2 is fine.
I am trying to insert (songid, userid) in dlkeuser(dislike) table against user i/p($_GET["en"]) and delete the record(songid,userid) from lkeuser(like) table if it exists. (songid,userid) pair is the composite primary key here. count is the net like/dislike of a song.
let's try this,
it will work
<?php
include('session.php');
?>
<?php
$conn = new mysqli("127.0.0.1","root","","foo");
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
$sew = $_SESSION['login_user'];
$a = $_GET["en"];
$l = 1;
$d = -1;
if($a == 1)
{
$sqlw = " INSERT into dlkeuser VALUES('$a','$sew')";
if ($conn->query($sqlw) === FALSE)
{
echo "you have already disliked the song";
}
else
{
//query1
$sql = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' " ;
//query2
$sql1 = "UPDATE liking
SET count = count - 1 ";
if ($conn->query($sql) === TRUE) {
echo "deleted the song";
}
if ($conn->query($sql1) === TRUE) {
echo "you disliked the song";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
You need to execute query1, before reuse your $sql variable.
//query1
$sql = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' " ;
$conn->query($sql);
//query2
$sql = "UPDATE liking
SET count = count - 1 ";
if ($conn->query($sql) === TRUE) {
You are not executing your query1 anywhere. Just the following code won't execute your query
$sql = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' " ;
You need another line like the following (as you did for query2)
if ($conn->query($sql) === TRUE) {
echo "you liked the song";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
This executes the query and also checks for errors.
I'm trying to check whether major, grade and university in candidates table, are empty, if so then insert in university...Else...
Is my syntax appropriate?
$sqlCheck1 = "SELECT `Major`, `Grade`, `University` FROM Candidates WHERE ID='".$_GET["cid"]."'";
$result5 = mysqli_query($con,$sqlCheck1);
while($row5 = mysqli_fetch_array($result5)) {
$major = $row5['Major'];
$grade = $row5['Grade'];
$university = $row5['University'];
if (mysqli_num_rows($result5) == 0)
{
$sql5 = "INSERT INTO `university` (`major`, `degree`, `univ`, `afnumber`) VALUES ('$major','$grade','$university','".$_GET["af"]."')";
if (mysqli_query($con,$sql5) === TRUE) {
} else {
echo "Error: " . $sql5 . "<br>" . mysqli_error($con);
}
}
else
{
Use the follwing code
$sqlCheck1 = "SELECT `Major`, `Grade`, `University` FROM Candidates WHERE ID='".$_GET["cid"]."'";
$result5 = mysqli_query($con,$sqlCheck1);
if (mysqli_num_rows($result5) == 0)
{
$sql5 = "INSERT INTO `university` (`major`, `degree`, `univ`, `afnumber`) VALUES ('$major','$grade','$university','".$_GET["af"]."')";
if (mysqli_query($con,$sql5) === TRUE) {
} else {
echo "Error: " . $sql5 . "<br>" . mysqli_error($con);
}
}
else
{
well you are saying that if major, grade and university are empty than insert those empty values in university but the question here is why you want to enter those values if they are empty, even if you want to do so along with inserting afnumber using "$_GET["af"]" variable than you can use following code..
$sqlCheck1 = "SELECT `Major`, `Grade`, `University` FROM Candidates WHERE ID='".$_GET["cid"]."'";
$result5 = mysqli_query($con,$sqlCheck1);
if (mysqli_num_rows($result5) == 0)
{
$sql5 = "INSERT INTO `university` (`afnumber`) VALUES ('".$_GET["af"]."')";
if (mysqli_query($con,$sql5) === TRUE) {
} else {
echo "Error: " . $sql5 . "<br>" . mysqli_error($con);
}
}
its quite short and fulfill the purpose but make sure you have checked null in database for major, grade and univ fields in university table .
Well it seems I've found the problem.
Because the values for the fields where automatically produced by taking substrings of the names of an HTML form fields, one of the values was appearing as id (it can be seen in the echo I've posted bellow). The update as it seems, didn't fail but produced this unexpected behavior.
Thanks to all who tried to help and sorry for the stupid question.
After I execute an update statement like
UPDATE tablename SET field='value' WHERE field='value'
without ever touching my primary key, it change's value from what it was before to 0.
Any ideas?
MySQL Server version: 5.5.37-0+wheezy1
This is the code that generates the query
$query2 = "UPDATE student SET ";
foreach ($_POST as $the_key => $a_post_arg) {
if (strcmp($the_key, "student_password") === 0) {
//without activation
$a_post_arg = md5($a_post_arg);
//with activation
//$a_post_arg = "Not activated!";
}
if (strcmp($the_key, "student_registration_year") === 0)
$a_post_arg = $a_post_arg . "-00-00";
if (strcmp(substr($the_key, 0, 14), "student_stats_") === 0 || strcmp($the_key, "student_validationImageTextfield") === 0) {
$student_stats[$the_key] = $a_post_arg;
continue;
}
if (strcmp(substr($the_key, 0, 7), "student") === 0 && strcmp($the_key, "student_email_retype") !== 0 && strcmp($the_key, "student_password_retype") !== 0) {
if (strcmp($the_key, "student_email") !== 0) {
if (strcmp($the_key, "student_select_dept") === 0) {
$query2 .= "dept='" . addslashes($a_post_arg) . "', ";
} else if (strcmp($the_key, "student_semester") === 0) {
$query2 .= "studying_semester='" . addslashes($a_post_arg) . "', ";
} else if (strcmp($the_key, "student_father_name") === 0) {
$query2 .= "fathers_name='" . addslashes($a_post_arg) . "', ";
} else if (strcmp($the_key, "student_academic_id") === 0) {
$query2 .= "academicIDNumber='" . addslashes($a_post_arg) . "', ";
} else {
$query2 .= substr($the_key, 8) . "='" . addslashes($a_post_arg) . "', ";
}
}
}
}
$query2 .= "status='registered' WHERE email='" . $_POST['student_email'] . "';";
This is an echo of $query2. The PK for the table is the auto increment field id and the email field.
query 2 = UPDATE student SET name='Όνομα', surname='Επώνυμο', dob='1970-09-09',
fathers_name='Ονοματεπώνυμο πατέρα', mother_name='Ονοματεπώνυμο μητέρας',
nationality='Υπηκοότητα', adt='Α.Δ.Τ.', password='0cc175b9c0f1b6a831c399e269772661',
dept='biology', id='Αριθμός μητρώου', studying_semester='6', registration_year='2001-00-00',
atlas_id='1234', academicIDNumber='123456789012', perm_address_road='Οδός',
perm_address_number='Αριθμός', perm_address_area='Περιοχή/Πόλη', perm_address_PObox='Τ.Κ.',
perm_address_Country='Χώρα', study_address_road='Οδός', study_address_number='Αριθμός',
study_address_area='Περιοχή/Πόλη', study_address_PObox='Τ.Κ.', study_address_Country='Χώρα',
telephone='+305555555555', cellphone='+305555555555', fax='+305555555555', afm='Α.Φ.Μ.',
eforia='Δ.Ο.Υ.', amka='Α.Μ.Κ.Α.', amika='Α.Μ.ΙΚΑ', status='registered' WHERE email='20#send.com';
I am working on a php script that stores message ids (Msg_ID, Ref_ID) in their corresponding user account tables.
What I've is, the Msg_ID is properly written, but the Ref_ID is always blank.
How ever when I run the query separately it works, but doesn't work in the script for some odd reason.
Here is the code :
$qry = "SELECT Ref_ID FROM Chat WHERE Msg_ID = " .$MsgID. ")";
$resp = mysqli_query($con, $qry);
$xx = mysqli_fetch_array($resp);
$ref_id = $xx['Ref_ID'];
foreach ($Array as $user){
$query = "Insert into ".$user."(POST_ID, REF_ID) values ('". $MsgID . "', '" .$ref_id. "')";
mysqli_query($con, $query);
}
The $ref_id is always blank and as a result, the blank value is written to the respective database.
Some help with what is wrong will be helpful.
Here is the full code :
<?php
function PostMainThread($Heading, $Message, $Author, $MarkedList){
$con=mysqli_connect("mysql.serversfree.com", "u521497173_root", "123456", "u521497123_mydb");
$Array = explode(',', $MarkedList);
if (mysqli_connect_errno()){
$response["success"] = 0;
$response["message"] = "Connection Failed.";
echo json_encode($response);
}else{
here:$MsgID = rand(1, 9999999);
$query = "Insert into Chat(Msg_ID, Header, MsgBody, Author) values (". $MsgID . "," . "'" . $Heading . "' ," .
"'" . $Message . "', '". $Author . "')";
$result=mysqli_query($con, $query);
if (!$result){
goto here;
}else{
//Put the MsgID in the respective user tables.
$qry = "SELECT Ref_ID FROM Chat WHERE Msg_ID = " .$MsgID. ")";
$resp = mysqli_query($con, $qry);
$xx = mysqli_fetch_array($resp);
$ref_id = $xx['Ref_ID'];
foreach ($Array as $user){
$query = "Insert into ".$user."(POST_ID, REF_ID) values ('". $MsgID . "', '" .$ref_id. "')";
mysqli_query($con, $query);
}
$response["success"] = 1;
$response["message"] = "Submission successful.";
mysqli_close($con);
echo json_encode($response);
}
}
}
function PostReplyToThread($PostID, $Author, $Reply){
$con=mysqli_connect("mysql.serversfree.com", "u521497123_root", "123456", "u521497123_mydb");
if (mysqli_connect_errno()){
echo 2;
}else{
$query = "Insert into Chat(Msg_ID, Header, MsgBody, Author) values (". $PostID . "," . "'" . " " . "' ," .
"'" . $Reply . "', '". $Author . "')";
$result=mysqli_query($con, $query);
if ($result){
echo 3;
}else{
echo 4;
}
mysqli_close($con);
}
}
if (isset($_POST['what_to_do'])){
if ($_POST['what_to_do'] == 0){
if ((isset($_POST['Title'])) &&(isset($_POST['Body']))&&(isset($_POST['Marked']))&&(isset($_POST['_Author']))){
PostMainThread($_POST['Title'], $_POST['Body'], $_POST['_Author'], $_POST['Marked']);
}
}else if ($_POST['what_to_do'] == 1){
if ((isset($_POST['Thread_ID'])) &&(isset($_POST['Answer']))&&(isset($_POST['_Author']))){
PostReplyToThread($_POST['Thread_ID'], $_POST['_Author'], $_POST['Answer']);
}
}
}else{
$response["success"] = 0;
$response["message"] = "Unspecified action";
echo json_encode($response);
}
Definition of the Chat table :
Create table Chat(Ref_ID INT Auto_Increment, Msg_ID INT, Header varchar(50), MsgBody varchar(500
), Author varchar(30), Primary Key(Ref_ID, Msg_ID));
$xx = mysqli_fetch_array($resp);
Will only return a numerically indexed array, as in $xx[0], $xx[1].
To use the column names, you need to use:
$xx = mysqli_fetch_array($resp, MYSQLI_ASSOC);
Or the shorter version:
$xx = mysqli_fetch_assoc($resp);
As a side note, don't forget security, when inserting data that comes from outside the function and could possibly have a quotes or SQL, it needs to be escaped!
$Heading = mysqli_real_escape_string($con, $Heading);
Otherwise it will come back to bite you.