PHP - Check If Person_id Already Exist In The Table
Hi! I wrote a small function that check if person_id already exist in the table called persons_web_tbl. If the person_id exist I get a message otherwise I add twitter/facebook profile of that person. I'm just trying to prevent duplicated entries this way. I will get person_id from table person_tbl, where are all people saved. The function actually works, I'm just curious if I'm on the right path. Thanks! $person_id = 11; class test extends dbh{ public function personExist($person_id) { $sql = "SELECT person_id FROM persons_web_tbl WHERE person_id = ?"; $stmt = $this->conn->prepare($sql); $stmt->execute([$person_id]); $row = $stmt->fetchColumn(); if ($row > 0){ echo "found"; }else { $person_web_twitter = "add something"; $sql = "INSERT INTO persons_web_tbl (person_web_twitter, person_id) VALUES (?, ?)"; $stmt = $this->conn->prepare($sql); $stmt->execute([$person_web_twitter, $person_id]); } } } $person = new test (); $person = $person->personExist($person_id); Edited February 15, 2020 by mactron Similar TutorialsHi.. So what i want to do is basicly to check if id XX exist in my database. How can this be done? Im thinking of something like: if(xx exist){do this} else{do this} Iv'e tried google etc before i posted here, but couldent really find anything where i found a soutable answer.. Hope someone can help! (: Gud pm!! So i made this script to check if a username and password exist but it kinda fails me. It gives me a database connection error from my confirm_query() which means it returned false? so here's my code: Code: [Select] function check_if_exist($username, $password) { global $connection; $query = "SELECT username, hashed_password"; $query .= "FROM users "; $query .= "WHERE username = '$username' "; $query .= "AND hashed_password = '$password' "; $query .= " LIMIT 1"; $result_set = mysql_query($query, $connection); confirm_query($result_set); if(mysql_num_rows($result_set) == 1) { return true; } else { return false; } } my confirm_query(): Code: [Select] function confirm_query($result) { if(!$result) { die("Database connection failure ". mysql_error()); } } I have a another script to check if the email exist and it works perfectly, i dunno why this won't work properly.. maybe another simple mistake.. Any ideas or Violent reaction? Thanks! Hello, i want to check whether image exist or not, but i can't get any data about it. I have tried everything: getimagesize, file_exist, filesize, etc. <? $info = @getimagesize('http://jargames.eu/ic.php?lf=files/All phone/240x320/007-quantum_of_solace_240x320.jar'); if(isset($info['mime'])){echo 'Image exist';} else{echo 'Image doesnt exist';} ?> Ty, for your help. Is it possible to check if multiple rows exist at the same time. For example, if a row with the id "1" and another row with id "2" exists, and return something like true then false if only the first exists?
I have a file that provides tens of thousands to check and it takes forever. I know this sounds bad off the start, but it's not something that is run normally. Only to update my database with new additions.
Is there any good way to check a lot at once? I know you can insert many at a time and save a lot of time.
Hi everyone, I'm still learning, but getting intermediate in PHP now, but it is still challenge to learn. I'm trying to have php check to see if one file inside folder in server, seem I could not get it right, but I tested it on other site, it works, but not this script, I don't understand why it won't work...maybe logical is wrong? here my code: if ($_POST['video']) { $path1 = "UPLOADS/Home/"; $path2 = "UPLOADS/Breakfast/"; $path3 = "UPLOADS/Spider/"; $scan1 = scandir($path1); $scan2 = scandir($path2); $scan3 = scandir($path3); $count1 = count($scan1) - 3; $count2 = count($scan2) - 3; $count3 = count($scan3) - 3; if($count1 > 0) { header('location:exist.html'); }elseif ($count2 > 0) { header('location:exist.html'); }elseif ($count3 > 0) { header('location:exist.html'); } But other site, it works: $scan = scandir($path); $count = count($scan) - 3; echo $count; if($count > 1){ echo "Hello yourself!<br />"; } Anyone will help will be appreciate! Thank you! Gary Edited April 3, 2019 by sigmahokies//database create table mydata ( id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, fname varchar(20), phoneno int(12) NOT NULL /*......*/ ); //class my data php <?php include('connect.php'); class InsertMydata { public function insertnow($fname, $phoneno) { $connect = new Connect; $insrt = $db -> prepare('INSERT INTO mydata (fname, phoneno) VALUES (?,?)'); $insrt -> execute(array($fname, $phoneno)); } } ?> //insernow validate form <?php include('../classs/mydata.php'); //Declare data and error arrays $errors = []; $mydara = []; if(!preg_match('/^[a-zA-Z]{4,15}$/', $_POST['fname'])) { $errors['fname'] = 'Enter full name!'; } //this block not working even the phone exist $connect = new Connect; $phoneno = $_POST['phoneno']; $checkiexist = $connect -> prepare('SELECT * FROM mydata WHERE phoneno = ?'); $checkiexist -> execute([$phoneno]); if($checkiexist->rowCount() > 0) { $errors['phonenoexist'] = 'Try another phone number!'; } if(!empty($errors)){ $data['success'] = false; $data['errors'] = $errors; }else{ $data['success'] = true; $data['message'] = 'success message!'; $mydata = new InsertMydata; $mydata -> insertnow($fname, $phoneno); } echo json_encode($data); ?> //my ajax $("#insertbtn").click( function(e) { var fname = $('#fname').val(), phoneno = $('#phoneno').val(), $.ajax({ url: 'insertnow.php', type: 'POST', data: {fname:fname, phoneno:phoneno}, dataType: "JSON", encode: true, }).done( function (data) { if (data.success == false) { if (data.errors.fname) { $('#fname').append('<p class="text-danger">' + data.errors.fname + '</p>'); } if (data.errors.phonenoexist) { $('.card-header').append('<div class="alert alert-info alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+data.errors.phonenoexist+'</div>'); } } else { $('.card-header').append('<div class="alert alert-success alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+data.message+'</div>'); } }); e.preventDefault(); }); //the problem is, the code insert data even if the phone exist why? the problem is, the code insert data even if the phone exist why? Edited April 8 by mahendaCode: [Select] $arr = array('../', 'j/', 'AcidBB/', 'fileBOMB/', 'OurHome', 'up'); foreach ($arr as $value) { // echo "Value: $value<br /><br />"; if (is_dir($value)) { echo "<tr> <td>{$value}</td> <td><font color='#66FF33'>Exists</font></td></tr><br />"; } else { echo "<tr> <td>{$value}</td> <td><font color='#FF0000'>Does Not Exist</font></td></tr><br />"; } } ~~~ Solved after posting. Sorry. ~~~ Ok i have an Array of directories i need to check before the script installs itself, I know how to check for directories but i dont know how to scan each array in the list without calling each one seperately in Code: [Select] If() { } Else If { } Else If { } And so on and so on... My Question is, If a For Statement is neaded, How would i go about checking each string in the Array List? As the title says, how can i check if multiple arrays exist inside an array or not? Any help is greatly appreciated!
I have a customer registration form up and running, the form allows customers to complete the forms and the data is then inserted into mysql db table via php form. I want to prevent duplicates records from already existing customers from creating a new records instead I want the customers to update their existing records in the backend. That is allow them to complete the form as normal, once they hit the submit button, the code should check if the customer first name and last name is already in the database if yes then it should update their records and if not it should insert new record to the table. I do not want to alert the customer that their records already exist. I do not know where to start. Please help Thank you so much in advance for your help. Here is my code so far (I say it's PDO but it pretty much isn't. What is the object here? The database connection? LOL!); $sql = " SELECT SUM(IF(`sent` != 'N' , 1 , 0 )) as 'Emails Sent', SUM(IF(`completed` NOT IN('N','paper') , 1 , 0 )) as 'Completed Electronically', SUM(IF(`completed` = 'paper' , 1 , 0 )) as 'Completed Manually', SUM(IF(`completed` != 'N' , 1 , 0 )) as 'Total Number Completed', SUM(IF(`remindercount` = '1' , 1 , 0 )) as 'Reminder Sent Once', SUM(IF(`remindercount` = '2' , 1 , 0 )) as 'Reminder Sent Twice', SUM(IF(`remindercount` = '3' , 1 , 0 )) as 'Reminder Sent Thrice' FROM `tokens_$survey_id` "; $statement = $dbh->prepare($sql); $statement->execute(); $result = $statement->fetch(PDO::FETCH_OBJ); foreach($result as $key => $value) { echo "<tr> <td>$key</td> <td>$value</td> </tr>"; }This is all well and good if the tokens_$survey_id table is actually there. Sometimes, for a genuine reason, there won't be a tokens table for that particular survey. How do I account for this? At the moment I get an error.. Warning: Invalid argument supplied for foreach() in /var/www/html/index.php on line 149I tried this but I am not satisfied this is correct; if(!$result) { die(); }I don't want the code to die! If I take out the die() statement then this if is ignored for some reason I don't understand. Hi, No matter what I seem to change in my code, I sill get the same error! "Table 'suvoocom_wl.beta' doesn't exist" This is my 'core.php' file; Code: [Select] <?php session_start(); @include ('config.php'); @include ('connect.php'); // ######################################################################### // Check if Writing Lounge is under maintenance, and avoid, if possible $qry="SELECT * FROM fuse_rights WHERE username='".$_SESSION['username']."'"; $result=mysql_query($qry); if($result) { if(mysql_num_rows($result) == 1) { $checks = mysql_fetch_assoc($result); $am = $checks['avoid_maintenance']; } } if(isset($_SESSION['username']) && $am == 0) { $result = mysql_query("SELECT * FROM break") or die(mysql_error()); while($row = mysql_fetch_assoc($result)) { if($row['on'] == 1) { header('location:../maintenance'); exit(); } } } if(isset($_SESSION['username']) && $am == 1) { } else { $result = mysql_query("SELECT * FROM break") or die(mysql_error()); while($row = mysql_fetch_assoc($result)) { if($row['on'] == 1) { header('location:../maintenance'); exit(); } } } // ######################################################################### // Check if Writing Lounge has BETA activated if(!session_is_registered(betaaccess)){ $result = mysql_query("SELECT * FROM beta") or die(mysql_error()); while($row = mysql_fetch_assoc($result)) { if($row['on'] == 1) { header('location:../BETA'); exit(); } } } // ######################################################################### // Check if the user logged in is banned $result = mysql_query("SELECT username FROM bans WHERE username = '".$_SESSION['username']."'") or die(mysql_error()); if (mysql_num_rows($result) > 0) { header('location:../banned'); exit(); } // ######################################################################### // Define the variables Writing Lounge will use later on $remote_ip = $_SERVER[REMOTE_ADDR]; $H = date('H'); $i = date('i'); $s = date('s'); $m = date('m'); $d = date('d'); $Y = date('Y'); $j = date('j'); $n = date('n'); $today = $d; $month = $m; $year = $Y; $date_normal = date('d-m-Y',mktime($m,$d,$Y)); $date_reversed = date('Y-m-d', mktime($m,$d,$y)); $date_full = date('d-m-Y H:i:s',mktime($H,$i,$s,$m,$d,$Y)); $date_time = date('H:i:s',mktime($H,$i,$s)); $date_hc = "".$j."-".$n."-".$Y.""; $regdate = $date_normal; $forumid = strip_slashes($_GET['id']); ?> It's basically the backbone to my website. This is my 'config.php' file; Code: [Select] <?php $sqlhostname = "localhost"; $sqlusername = "suvoocom_wl"; $sqlpassword = "*****"; $sqldb = "suvoocom_wl"; ?> And this is my 'connect.php' file; Code: [Select] <?php mysql_connect("$sqlhostname", "$sqlusername", "$sqlpassword")or die("Unable to connect."); mysql_select_db("$sqldb")or die("Unable to select the database you provided. Either I do not have premission to connect to that database, or the database doesn't exist."); ?> Does anyone have any ideas? :S Thanks! Hi, My site was working fine, but I just switched servers/web hosts and now I'm getting the following errors (in blue). The thing is, I don't get the error if I try to run the query loop after just using 'mysql_select_db' once, but if I use it again to select a different database and then run the query loop, I start getting the error. Code: [Select] mysql_select_db ("database1", $mysql_con); $mysql_query = mysql_query ("SELECT ID FROM someTable1", $mysql_con); $someVar1 = 0; while ($mysql_array = mysql_fetch_array ($mysql_query)) { $someVar1 ++; } ////// The above code gives me no error. But If I then try to select a different database and run a loop in the same way (in the same file), I start getting the below error... mysql_select_db ("database2", $mysql_con); $mysql_query = mysql_query ("SELECT ID FROM someTable2", $mysql_con); $someVar2 = 0; while ($mysql_array = mysql_fetch_array ($mysql_query)) { $someVar2 ++; } Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/snubby5/public_html/coozymcmillan.com/view.php on line 86 So I looked it up and somewhere it told me to add some extra code to handle errors better: Code: [Select] if ($mysql_query === FALSE) { die (mysql_error ()); // TODO: better error handling } But when I do that, I get a different error: Table 'database1.someTable2' doesn't exist It doesn't seem to recognize that I switched databases, and it says 'database1.someTable2' doesn't exist (because it doesn't), when really it should be checking for 'database2.someTable2' (which exists). So to reiterate, I can run the query loop fine after selecting database1, but after that if I select database2, it either gives me the first error, or If I add the 'die' code it gives me the second error. Thanks much! PS: I can get it working if I put everything into one database, but I have multiple websites (which sometimes need to call eachothers' databases) and it would be a huge hassle to cram them all into one database unless I have to. i have error where my code should update existing data where id exist, it get updated ..but the others data is disappeared .only the data updated is remained $sql1 ="select*from semakan_dokumen where email='$stdEmail'"; $sqlsearch1 = mysqli_query($dbconfig,$sql1); $resultcount1 = mysqli_num_rows($sqlsearch1); if($resultcount1 > 0){ $query1=("UPDATE semakan_dokumen set student_id='$noMatrik', email= '$stdEmail', surat_tawaran='$fileName', ic='$fileName1',sijil_lahir='$fileName2',sijil_spm= '$fileName3',sijil_sekolah= '$fileName4', sijil_dip= '$fileName5',sej_julai='$fileName6',bm_julai='$fileName7',muet='$fileName8', mid1='$fileName9',yuran= '$fileName10',umpa_bend1= '$fileName11',umpa_bend2='$fileName12',bpkp='$fileName13', penaja='$fileName14',kesihatan= '$fileName15', jhepa='$fileName16' where email= '$stdEmail' "); }else{ //filezip $query1 = "INSERT INTO semakan_dokumen (email,surat_tawaran,ic,sijil_lahir,sijil_spm,sijil_sekolah,sijil_dip,sej_julai,bm_julai,muet,mid1,yuran,umpa_bend1,umpa_bend2,bpkp,penaja,kesihatan,jhepa) VALUES ('$stdEmail','$fileName','$fileName1','$fileName2','$fileName3','$fileName4','$fileName5','$fileName6','$fileName7','$fileName8','$fileName9','$fileName10','$fileName11','$fileName12','$fileName13','$fileName14','$fileName15','$fileName16')"; }
Hi all, hope some can help because this is giving me more grey hairs than I allready have.
I am trying to solve the following: I'm pulling in JSON data, decoding it to a array which I write to a database. However in the array are social security numbers that I don't want to store (privacyregulations). So I need to check if a row has a social security number and if it has one I want to replace it with 'anonymized'. I have got it to work successfully on a local Xampp test environment using the following script (extract off course): //first anonymize the social security number (ssn) if exists $data = json_decode($jsondata, true);
// then fill the tables foreach($data as $row) {
$insertstatement = mysqli_query($link,"INSERT INTO $tablename (personid, type, ssn) VALUES ('".$row["personid"]."', '".$row["type"]."', '".$row["ssn"]."') ON DUPLICATE KEY UPDATE type = VALUES(type), bsn = VALUES(ssn)");
This leads to a filled table where the ssn's are filled with 'anonymized' if they exist in the array and empty if it does not exist for that row. This is exactly what I want ;-).
Personid type ssn
However, when I run the same script on a Lamp production environment (lamp stack on an Azure server) it does not work. Then the scripts results in totally ignoring the whole row that contains a ssn??
Personid type ssn Hope someone can help to get this working on my production environment as well.
Richard
i wanting users to be able to update there email address and check to see if the new email already exists. if the email is the same as current email ignore the check. i have no errors showing up but if I enter a email already in the db it still accepts the new email instead of bringing the back the error message. Code: [Select] // email enterd from form // $email=$_POST['email']; $queryuser=mysql_query("SELECT * FROM members WHERE inv='$ivn' ") or die (mysql_error()); while($info = mysql_fetch_array( $queryuser )) { $check=$info['email']; // gets current email // } if($check!=$email){ // if check not equal to $email check the new email address already exists// $queryuser=mysql_query("SELECT * FROM members WHERE email='$email' "); //$result=mysql_query($sql); $checkuser=mysql_num_rows($queryuser); if($checkuser != 0) { $error= "0"; header('LOCATION:../pages/myprofile.php?id='.$error.''); } } cheers This is suppose to check a table to see if it has a value in it. I get this error: Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /homepages/6/d365637117/htdocs/EE Live/Active/Inc/session.php on line 33 This is the code if($checkProfile) { $result = mysql_query("SELECT prof_pic FROM members_profile WHERE id = '".$_SESSION['EEID']."'"); $mem_num_rows = mysql_num_rows($result); if($mem_num_rows =1) { } Hi, I just want to know how to check if a row/record already exists for a given table, but this code gives me message in browser: Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in myTest.php This is the the snippet I am running: Code: [Select] <?php $connxn=mysql_connect("localhost","root"); $db=mysql_select_db("siliconvalley"); $toyNodePath="#document/siliconValleyHELLO"; $queryA=mysql_query("SElECT FROM pathexpress (path_express) WHERE path_express='$toyNodePath'");//make sure AT MOST ONE ROW EXISTS!! if(mysql_num_rows($queryA)==1) print "ALREADY IN table pathexpress!"; else { mysql_query("INSERT INTO pathexpress (path_express) VALUES ('$toyNodePath')"); print "ADDED $toyNodePath to table pathexpress!"; } ?> Please, any help is greatly appreciated! Hi Guys just need some advice really I would like to know if there is a way I can check if a number is in a times table for example if(3 is in 4 times table){ do bla bla } the result for above will be false as 4 times table does not contain 3 if(12 is in 4 times table){ do bla bla } the above would be true Thanks guys Hi, I am creating a temporary table. I need to check if the table already exists or not. If exists, I have to use the existing data else have to create a new temporary table. I can use 'Create If Not Exists'. How practical is this query? any issues with the performance? If the table exists it will be a huge data, I don't want to loose that data because recreating is an un-necessary load on the database. Say you have three tables like this...
STUDENTS (studentid, name)
CLASSES (studentid, classname)
GRADES (studentid, grade)
And not all students have grades yet. If you're doing a mysql query like below, is there anything you can add to the statement to check if a grade exists for each student? So that if while lopping through the results of the main query, I can easily do something with the students who don't yet have a grade yet (like maybe mark their names in red).
I can do this by putting a whole separate mysql query inside the looping of the main query, but that seems terribly inefficient to call the database again for EVERY student.
$sql = "SELECT * FROM students, classes, grades WHERE students.studentid = classes.studentid ORDER BY students.lastname"; $info= mysqli_query($connection, $sql); if (!$info) { die("Database query failed: " . mysqli_error()); } else { //code }Thanks! Greg |