PHP - Check Data Type And Value
hi guys, in my form i need to insert an ID which is 5 digits number only. can anyone please tell me how can i check this before i insert? and also i need to check existing ID in my database.
Similar TutorialsHi, I have an image handling php script which works fine here if the image is actually a readable format by the php program... Code: [Select] <?php //determine image type if($this->ext == 'jpeg' || $this->ext == 'jpg') { $imageObject = imagecreatefromjpeg($image); } elseif($this->ext == 'gif') { $imageObject = imagecreatefromgif($image); } ?> However, I tested the script with a random gif created in photoshop and i got an ugly php error returned saying the image was not the correct type for imagecreatefromgif even tho the image was a .gif file. In response I then tried to make a safety test, but it doesn't seem to work: Code: [Select] <?php //determine image type if($this->ext == 'jpeg' || $this->ext == 'jpg') { if(imagecreatefromjpeg($image)) { $imageObject = imagecreatefromjpeg($image); } else{ //now remove the old TEMP file ($image) unlink($image); return 'Sorry there is a file type error with the image you are uploading.';*/ } } elseif($this->ext == 'gif') { if(imagecreatefromjpeg($image)) { $imageObject = imagecreatefromgif($image); } else{ //now remove the old TEMP file ($image) unlink($image); return 'Sorry there is a file type error with the image you are uploading.';*/ } } ?> The $image can be either a jpg jpeg gif or png... Could anyone please tell me how to correctly check if the file is in readable by the php program in this context? Any help would be very much appreciated I have a payment form with the following code... Code: [Select] <!-- Expiration Month --> <span class="group"> <label class="innerlabel" for="expMonth">Month</label><!-- --> <select id="expMonth" name="expMonth"> <option></option> <option>01</option> <option>02</option> <option>03</option> <option>04</option> <option>05</option> <option>06</option> <option>07</option> <option>08</option> <option>09</option> <option>10</option> <option>11</option> <option>12</option> </select> </span> How is that data represented as far as Data-Type?? Is it treated as a String or an Integer?? How can I ensure that when I sent it to the Payment Gateway that it is treated as a Two-Digit value?? Thanks, Debbie Hi Masters,
I'll be making a big ticketing program with PHP and I cant decide what data type to use.
Thanks,
Marvin
Coming from the world of Excel, I can easily format numbers as $1,500.00, or 27%. When I uploaded a large chunk of data into SQL to be read back through a table, the values all come out as exactly what they were uploaded as. For example, I have an SQL column set as Decimal(19,4) that I want formatted like currency, but which shows up as 1500.0000 in my table, or another column with type decimal(5,2) which shows up as 5500.0000, but which I want to show up as 55%. How do I do this?
Is this proper PHP... function setHeat(Building $b) { $this->hotness = $b->getInsideHeat(); } That looks more like Java to me. I thought you didn't define data-types anywhere in PHP?! TomTees Hey Folks! So, my brain is hurting now... I am making a little process to go through a table and if a row as one set of data, and the next row as the same data based on 3 fields then update a field in the current row. Here is a snippet of what I have been working on: <?php date_default_timezone_set('AUSTRALIA/BRISBANE'); $lasthour = (time() - 3600); $lastattack45 = (time() - 2820); $lasthalfhour = (time() - 1800); $lastfifteen = (time() - 900); $lastfhourhalf = (time() - 5400); $next15 = (time() + 900); $now = time(); mysql_connect($mysql_host, $mysql_user, $mysql_password) or die('Error connecting to mysql'); mysql_select_db($mysql_database); $result = mysql_query("SELECT feeder, attacker, defender, attacklandunix, smurfid, smurf, unixtime, record, leader FROM nation_incoming WHERE attacklandunix > $now && smurf <> 'smurfed' ") or die("SELECT Error: ".mysql_error()); while($row = mysql_fetch_array($result)){ $a[][feeder] = $row['feeder']; $a[][defender]= $row['defender']; $a[][landing]= $row['attacklandunix']; } foreach($a as $b){ //in here it is to compare the 'feeder' && 'defender' && 'attacklandunix' to the next row. IF the same combo exists, then update field 'leader' to "0". else update 'leader' to "1" } ?> How can/should I pull up the next row? I am using a query to select everything out of a table in to an array. I have 4 fields as follows name, email, comment and datatime. What i want to do is use one of the stated function to grab the datetime elements and split them at the break point, but i am displaying more than one record with in the table, i think this is were i am fucking up. for example i tryied this: Code: [Select] $commentsTable = "comments"; $comments = "SELECT * FROM $commentsTable"; $commentResults = mysql_query($comments); $commentRows = mysql_fetch_array($commentResults); $dateTimeSplit = explode(" ", $commentRows['datetime']); <?php while($commentRows = mysql_fetch_array($commentResults)){?> <div id="comments"> <div id="CommentWrapper"> <div id="comment"> <div id="UserComment"><? echo $commentRows['comment'];?></div> // here is were am having the problem!!! <div id="PostDateTime"><i>Posted: </i><? echo $dateTimeSplit['0'];?><i> Time: </i><? echo $dateTimeSplit['1'];?></div> </div> </div> </div> <?php } mysql_close(); ?> any sudgestions? Hello all, I just created this function that I want to use in CLi mode. It works perfectly in regular browser mode, but gives me this error on Cli mode if I do convertToCamelCaps('TEST STRING'); PHP Catchable fatal error: Argument 1 passed to convertToCamelCaps() must be an instance of string, string given in file... if (!function_exists('convertToCamelCaps')) { function convertToCamelCaps(string $string, $initialCaps=FALSE) { if ($words = explode(' ',$string)) { foreach ($words as $index => &$word) { $word = strtolower($word); if($index==0 && $initialCaps===FALSE) { continue; } $word = ucwords($word); } return implode('',$words); } return FALSE; } } If I remove the string datatype requirement in the function before the function argument list, it works fine in CLi mode. Hi Guys, Im using the code below to display the value of checked checkboxes on form submission, however im also trying to pull the price from the database for each checked value. foreach ($_POST['check'] as $product) { echo $row['price'] . " " . $row['currency'] . " for " . $product . "<br />"; } Please could somebody point me in the right direction as to what id need to do. As iv only been able to get it to display the price of the first checked value. Thanks Hey Guys, I have got 3 chained select boxes working. Basically what you do is check for a region with the country, then once you pick a region, you select a club within that region. Once you have selected the club, you can then choose a team from within that club. Screenshot: Attchment As part of this chained select boxes's, a user can register. Although, the user has to FIRST check if the TEAM has already been registered in the database. I have taken a screenshot of my database, which shows the regions, clubs, and teams from the chained select boxes. What i want to do now is be able to check if a TEAM is already registered in the database. So as you can see in the database, the team 'NPOB, Senior As' has already been taken. Database Screenshot: Attachment *** How do i check if a user has been registered to one of the teams? And if there is not a registered user to that team, they can then register it. Here is my code: <?php include"database.php"; ?> <script type="text/javascript"> /* Triple Combo Script Credit By Philip M: http://www.codingforums.com/member.php?u=186 Visit http://javascriptkit.com for this and over 400+ other scripts */ var categories = []; categories["startList"] = ["Taranaki","Auckland"] // Regions + Clubs categories["Taranaki"] = ["NPOB","Tukapa"]; categories["Auckland"] = ["Marist","Takapuna"]; // Clubs + Teams within that Club categories["NPOB"] = ["Senior As","Senior Bs","Colts U21s"]; categories["Tukapa"] = ["Senior As","Senior Bs","Colts U21s"]; categories["Marist"] = ["Senior As","Senior Bs","Colts U21s"]; categories["Takapuna"] = ["Senior As","Senior Bs","Colts U21s"]; var nLists = 3; // number of select lists in the set function fillSelect(currCat,currList){ var step = Number(currList.name.replace(/\D/g,"")); for (i=step; i<nLists+1; i++) { document.forms['tripleplay']['List'+i].length = 1; document.forms['tripleplay']['List'+i].selectedIndex = 0; } var nCat = categories[currCat]; for (each in nCat) { var nOption = document.createElement('option'); var nData = document.createTextNode(nCat[each]); nOption.setAttribute('value',nCat[each]); nOption.appendChild(nData); currList.appendChild(nOption); } } // function getValue(L3, L2, L1) { // alert("Your selection was:- \n" + L1 + "\n" + L2 + "\n" + L3); // } function init() { fillSelect('startList',document.forms['tripleplay']['List1']) } navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false); </script> <form name="tripleplay" action="testingdropdown.php" method="post"> <select name='List1' onchange="fillSelect(this.value,this.form['List2'])"> <option selected>Choose Region</option> </select><br /><br /> <select name='List2' onchange="fillSelect(this.value,this.form['List3'])"> <option selected>Choose Club </option> </select><br /><br /> <select name='List3' onchange="getValue(this.value, this.form['List2'].value, this.form['List1'].value)"> <option selected >Choose Team </option> </select> <input type="submit" name="tripleplay" value="Register"> </form> <?php if (isset($_POST['tripleplay'])) { $region = addslashes(strip_tags($_POST['List1'])); $club = addslashes(strip_tags($_POST['List2'])); $team = addslashes(strip_tags($_POST['List3'])); $email = 'email'; $check = mysql_query("SELECT * FROM managers WHERE email='$email'"); if ($email == '') { echo "You can register that club"; } else { echo "Sorry that team has already been registered"; } } ?> Hi guys, I'm recent working on my php to add the row in mysql database. I need a bit of your help as I would like to know how to check the data in mysql database if it have added in mysql and then print it out without adding another same row? here's the current code: Code: [Select] <?php session_start(); define('DB_HOST', 'localhost'); define('DB_USER', 'mydbuser'); define('DB_PASSWORD', 'mydbpass'); define('DB_DATABASE', 'mydbname'); $errmsg_arr = array(); $errflag = false; $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } function clean($var){ return mysql_real_escape_string(strip_tags($var)); } $username = clean($_GET['user']); $pass = clean($_GET['pass']); $login = clean($_GET['login']); $all = clean($_GET['all']); if($username == '' && $pass == ''){ // both are empty $errmsg_arr[] = 'Username and password are missing. You must enter both or the other one.'; $errflag = true; } if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; echo implode('<br />',$errmsg_arr); } else { $insert = array(); if(isset($_GET['user'])) { $insert[] = 'username = \'' . clean($_GET['user']) .'\''; } if(isset($_GET['pass'])) { $insert[] = 'pass = \'' . clean($_GET['pass']) . '\''; } if(isset($_GET['login'])) { $insert[] = 'LoggedUser = \'' . clean($_GET['login']) . '\''; } if(isset($_GET['all'])) { $insert[] = 'all = \'' . clean($_GET['all']) . '\''; } if (count($insert)>0) { $names = implode(',',$insert); if($username) { $qrytable1="SELECT username, LoggedUser FROM Online_Users WHERE username='$username'"; $result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error()); while ($row = mysql_fetch_array($result1)) { echo "<p id='LoggedUser'>"; echo $row['LoggedUser'] . "</p>"; } } if($username && $login == '1') { $sql="INSERT INTO Online_Users (username, LoggedUser) VALUES ('$_GET[user]','$_GET[login]')"; $result = mysql_query($sql); if($result) { $qrytable1="SELECT username, LoggedUser FROM Online_Users WHERE username='$username'"; $result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error()); while ($row = mysql_fetch_array($result1)) { echo "<p id='LoggedUser'>"; echo $row['LoggedUser'] . "</p>"; } } } elseif($username == 'all') { $names = implode(',',$insert); $result = mysql_query("SELECT * FROM Online_Users") or die('Error: ' . mysql_error()); $num_rows = mysql_num_rows($result); echo "There are $num_rows Users Online right now"; } } } ?> I have two questions regarding $byte_array. 1. Is there a general way to check if a $byte_array contains any data? 2. Is there a way to confirm if the $byte_array contains an actual PNG image? hi all, I have an array(1,2,3,4) and i make a form and make checkboxes for this array and user selects 2,3 and 4 when user submit form then i save it in table by making selected check boxes and converting selected values into bitwise equivalent value like this foreach($data['meal_types'] as $v){ $mealTypeBits += pow(2,$v-1); } Now when i have to show user his selected data how will i compare table bitwise saved record with array(1,2,3,4) to get the values that he checked while saving. Hi, I have multiple table Table -1 order_no name 1 raj table -2 order_no name 1 raj table 3 order_no name 1 raj table 4 order_no name 1 raj table 5 order_no name 1 raj I want a query to check if the id (one) is present in all tables or not, i create this. select order_no from prepress, press, postpress, qc, binding, dispatch where order_no=prepress.order_no AND order_no=press.order_no AND order_no=postpress.order_no AND order_no=qc.order_no AND order_no=binding.order_no AND order_no=dispatch.order_no but the ambiguous error for order_no. how to achieve this can anyone suggest me? thanks Hello. I want to check if an e-mail address is stored into a database. I've found this type of code: Code: [Select] function verifmail($email) { db_connect(); if (mysql_num_rows(mysql_query("SELECT email FROM users WHERE email='$email';"))) { return 1; } else { return 0; } } Is it correct ? Is there any other way? //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 mahendaHi guys, im inserting data into the table using drop-down list & multi select list,well it works very well. but i need to make sure i should not insert same StudentID & CourseID twice. here my code for you could anyone tell me pls where should i write code to check existing data? <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("uni", $con)or trigger_error('MySQL error: ' . mysql_error()); $result = mysql_query("SELECT * FROM student") or trigger_error('MySQL error: ' . mysql_error()); echo '<select name="sid">'; while($row = mysql_fetch_array($result)) { echo '<option value="' . $row['StudentID'] . '">' . $row['StudentName'] . '</option>'; } echo '</select>'; // ---------------- ?> </div> <div class="style41" id="Layer7"> <?php $result = mysql_query("SELECT * FROM course") or trigger_error('MySQL error: ' . mysql_error()); echo '<select name ="cid[]" multiple="multiple" size="10">'; while($row = mysql_fetch_array($result)) { echo '<option value="' . $row['CourseID'] . '">' . $row['CourseName'] . '</option>'; } echo '</select>'; mysql_close($con); ?> ------------------------------------ <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("uni", $con)or trigger_error('MySQL error: ' . mysql_error()); if (!empty($_POST['sid']) && !empty($_POST['cid'])) { $ct = 0; $student = $_POST['sid']; foreach ($_POST['cid'] as $key => $course) { $sql = "INSERT INTO take (StudentID, CourseID) VALUES('".mysql_real_escape_string($student)."', '".mysql_real_escape_string($course)."')"; $query = mysql_query($sql) or trigger_error('MySQL error: ' . mysql_error()); if (mysql_affected_rows() > 0){$ct++;} } echo $ct . ' rows added.'; } mysql_close($con); ?> Hi guys Can someone help me about this: The php code can be revise username and password with CURL then check database and if username & password is correct return true else false. Thanks Hey! I have it so users can submit info to my site. They have to check some check boxes and radio buttons. I want them to be able to edit this information, so I want to have the data pulled from the MySQL database and have the correct radio button selected (and the text bolded). So I'm thinking some sort of array to check for each value in the database... but I don't really know. There are a few groups of radio boxes and check boxes but here is an example of one. Code: [Select] <input type="radio" name="stage" value="Stage 1" /> Stage 1 <input type="radio" name="stage" value="Stage 2" /> Stage 2 <input type="radio" name="stage" value="Stage 3" /> Stage 3 The information is pulled from the database like this: Code: [Select] $res=mysql_query("SELECT * FROM ACTIVE WHERE INDEX_ID=$id"); if(mysql_num_rows($res)==0) echo "There is no data in the table <br /> <br />"; else { for($i=0;$i<mysql_num_rows($res);$i++) { $row=mysql_fetch_assoc($res); } } So when I pull information (lets say I want to echo it) it'd look like this: Code: [Select] $row[STAGE] The value for the stage selection can only be Stage 1, Stage 2 or Stage 3 so I need it to be selected when the page loads. Thanks! hi there, i am fairly new to OOPs in php, i get an error when i declare the argument type (as object) in a function and pass the same type (object). class eBlast { public static function getEmail(object $result) { return $result->email; } } $r = mysql_fetch_object($query); eBlast::getEmail($r); echo gettype($r); // outputs: object error is : Code: [Select] Catchable fatal error: Argument 1 passed to eBlast::getEmail() must be an instance of object, instance of stdClass given, called in C:\wamp\www\integra\client\pl_eblast\admin\send_emails.php on line 145 and defined in C:\wamp\www\integra\client\pl_eblast\app\app.eBlast.php on line 8 if i remove the type declaration in the function it works, but just would like to know why it shows error when pass the same type, also isnt mysql_fetch_object is the instance of stdclass? thanks in advance! |