PHP - How Do I Write A 0 Count If A Row Doesn't Exist?
I'm printing some mysql results to a table and sometimes I have rows with no results so they never get counted... which results in an ugly looking parenthesis on my page with nothing it (). For these times, I'd like to print a zero.
How can I rewrite the following to achieve this? Code: [Select] if($row['mycount'] does not exist) { $row['mycount'] = '0'; } Similar TutorialsHi guys, I need your help. I am trying to insert the rows in the mysql database as I input the values in the url bar which it would be like this: Code: [Select] www.mysite.com/testupdate.php?user=tester&pass=test&user1=tester&email=me@shitmail.com&ip=myisp However i have got a error which i don't know how to fix it. Error: Column count doesn't match value count at row 1 <?php session_start(); define('DB_HOST', 'localhost'); define('DB_USER', 'mydbusername'); define('DB_PASSWORD', 'mydbpassword'); 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']); $password = clean($_GET['pass']); $adduser = clean($_GET['user1']); $email = clean($_GET['email']); $IP = clean($_GET['ip']); if($username == '') { $errmsg_arr[] = 'username is missing'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'PASSWORD is missing'; $errflag = true; } if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; echo implode('<br />',$errmsg_arr); } else { $sql = "INSERT INTO `members` (`username`,`email`,`IP`) VALUES ('$adduser','$email','$IP')"; if (!mysql_query($sql,$link)) { die('Error: ' . mysql_error()); } echo "The information have been updated."; } ?> Here's the name of the columns i have got in my database: Code: [Select] username IP I have input the correct columns names, so I can't correct the problem I am getting. Please can you help? This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=331562.0 Why am I getting this error when there are 3 Fields with 3 values? Column count doesn't match value count at row 1 Code: [Select] $sql5="INSERT INTO participants (participant_name, team_no, sport) VALUES ('".implode("','$_POST[team]'),('",$_POST['participant_name'])."','$_POST[team]','$sport')"; 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. I have a script that uses simplexml_load_file to download weather xml files. It works great except when the file doesn't exist. The server returns an HTML page when the xml file isn't available but the title is something.xml. How can I check to be sure it is an xml file and handle the error when it isn't. I have tried file_exists and access the return code (it's always 200). Can I access the doctype and determine if it HTML or XML? I'm trying to do a simple image upload. It works fine on my local server but i'm moving all my files to my production server and some files i attempt to upload, via an html form, don't register. The $_FILES variable doesn't exist sometimes. I think its because of the file size but i'm not sure. The form has two inputs: "title" and "userfile". I can put something in the title and attempt to upload a small excel file and both $_POST and $_FILES exist but if i do a larger image file both $_POST and $_FILES don't even get set. I did an "echo ini_get('post_max_size');" and i get "8M". The image i'm attempting to upload is only 0.34M so i should be good there. I've replaced the actual upload script with this, which is how i found out the variables only get set sometimes Any suggestions would be much appreciated. Code: [Select] <?php echo "Upload: " . $_FILES["userfile"]["name"] . "<br />"; echo "Type: " . $_FILES["userfile"]["type"] . "<br />"; echo "Size: " . ($_FILES["userfile"]["size"] / 1024) . " Kb<br />"; echo "Stored in: " . $_FILES["userfile"]["tmp_name"]; echo "<hr><pre>"; print_r($_POST); echo "</pre><hr>"; echo "<pre>"; print_r($_FILES); echo "</pre>"; Delete. I guess I'm just stupid cause it seems like every time i get stuck and i post on here and its gets answered in less than 30 min.'s and i keep getting stuck! Here my script... function scoring($user){ $query = "SELECT Game_ID, Pick FROM Cfb WHERE User_ID= 1"; $result = mysql_query($query); $query1 = "SELECT Game_ID, Pick FROM Cfb WHERE User_ID= $user"; $result1 = mysql_query($query1); $affected = mysql_num_rows($result); for($i=0; $i< $affected; $i++) { $scores =mysql_fetch_assoc($result); $scores1 =mysql_fetch_assoc($result1); $main = array_diff_assoc($scores,$scores); $me = array_diff_assoc($scores, $scores1); $m = count($me); $m1 = count($main); if ($m == $m1){ $points += 1; }else{ $points += 0; } } echo '<br />'; echo '<br />'; echo $user; echo '<br />'; echo $points; echo '<hr />'; } $sql="SELECT id FROM users WHERE approved=1 AND user_level !=10"; $result=mysql_query($sql); while($row = mysql_fetch_object($result)) { $ids[] = $row->id; } print_r($ids); Alright heres what this script does... The script has a function that scores 1 individual user for his/her choices. Then I'm getting the user_ids from the users table at the bottom. Taking those and plugging them back into the function to score all the users at one time. Problem... Not all users will make picks. So how do i break the script in the function if that user_id is not is the CFB table attached to picks I have 2 tables im using Cfb and users users controls user info such as id # name username ect.. Cfb controls the picks. When a user makes there selection it stores there User_ID, Game_ID, and Pick So not all user ids are in the Cfb table. So if the script tries to input a user id thats not in the Cfb table it needs to break. Right now it just screws everything up! So how can i make it break that way? Thanks for any help And how can I make it so if it does already exist, it doesn't over-write information already in it? Thanks First time post, be easy on me...
I'm using preg_match_all to return an array with all the matches. I know I'm missing something fundamental, but I either keep looking past it or am more screwy than I know.
Sample String
CC-BY-ND-NCI'm using the following code preg_match_all("/cc|creative commons|copyright|by|sa|nc|nd/i",$exifmeta['copyright'],$cmeta)I would expect to see Array ( [0] => Array ( [0] => CC [1] => BY [2] => ND [3] => NC ) )What I get is Array ( [0] => Array ( [0] => CC [1] => BY [2] => ND [3] => NC [4] => sa ) ) 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. *delurk! It had to happen sooner or later!* OK, I am totally and utterly stumped. I have this script: $this->clear_cache ($this->cache_dir, $this->cache_time); if ($this->cache_time > 0) { $current_page = $_SERVER ['REQUEST_URI']; $current_page_encoded = base64_encode($current_page); $current_page_path = $this->cache_dir . $current_page_encoded; if (file_exists($current_page_path)) { // see if there is still a file with the name of the current request URI after cache cleared $content = file_get_contents ($current_page_path); return $content; } } Basically, it is for checking if there is a cached version of the page before running the rest of the script, using the REQUEST_URI as the identifier. So it calls a function to clear the cache, which works fine (and I've tried just deleting the cache files manually anyway). Then it checks if we are even caching, i.e. if cache time is greater than 0. Then it uses the BASE64-encoded REQUEST_URI (under which name the file would have been cached previously) to check if a file with that name still exists in the cache dir, and if so loads it. Now, this works perfectly with a url like: mysite/myscript/mysubpage But when the page has parameters, like: mysite/myscript/mysubpage?search=widgets the file_exists function returns TRUE, even though the directory is empty. I did do a clearstatcache(); but it made no difference and anyway, it wouldn't explain why the URI with query string would fail while the regular one would not. And even if something is wrong with my code elsewhere, the fact is it is returning TRUE for a non-existent file. Can someone prevent my slide into insanity?! Why doesn't it add a new line when I open up index.php Code: [Select] $fp = fopen('text.txt','w'); fwrite($fp, "Your IP: ".$_SERVER['REMOTE_ADDR']."\n"); fclose($fp); Hi there, If anyone has a spare minute, id really appreciate someone casting their eye over this and seeing if there's anything obviously wrong. Writing to the txt file works fine, but the redirect to the thankyou.html page doesn't. Cheers Guys. <?PHP $filename = "output.txt"; #CHMOD to 666 $forward = 1; # redirect? 1 : yes || 0 : no $location = "thankyou.html"; #set page to redirect to, if 1 is above ## set time up ## $date = date ("l, F jS, Y"); $time = date ("h:i A"); ## mail message ## $msg = ""; foreach ($_POST as $key => $value) { $msg .= ucfirst ($key) .", ". $value . ", "; } $msg .= "\n"; $fp = fopen ($filename, "a"); # w = write to the file only, create file if it does not exist, discard existing contents if ($fp) { fwrite ($fp, $msg); fclose ($fp); } else { $forward = 2; } if ($forward == 1) { header ("Location:$location"); } else if ($forward == 0) { echo ("Thank you for submitting our form. We will get back to you as soon as possible."); } else { "Error processing form. Please contact the webmaster"; } ?> Many thanks, Mike 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')"; }
Anyone can help me? <?php $tbl_name="menu"; $kategorije = mysql_query("SELECT * FROM $tbl_name WHERE Left(menu_name, 1) BETWEEN 'A' AND 'M' ORDER BY menu_name ASC"); if (!$kategorije) { die("Database query failed: " . mysql_error()); } while ($row=mysql_fetch_array( $kategorije )) { echo "<div id=lista-header><h4>{$row["menu_name"]}</h4></div>"; $id_sub=$row['id_menu']; $podkategorije = mysql_query("SELECT * FROM submenu WHERE id_menu=$id_sub ORDER BY sub_name ASC", $connection); if (!$podkategorije) { die("Database query failed: " . mysql_error()); } echo "<ul class=\"pod\">"; while ($pod=mysql_fetch_array( $podkategorije )) { echo "<li><a href=index.php?=podkate?".$pod["id_sub"]." class=black>{$pod["sub_name"]}</a><hr size=1 align=left width=100px color=#cccccc></li>"; } echo "</ul>"; } ?> In this way, I get list with categories and hes subcategories. How to count how many subcategories have each categories, and count how many articles have each categories? Example (I wanna get this kind of look): Categories name (3) subcategoriesname (2) subcategoriesname (4) subcategoriesname (7) Categories name (5) subcategoriesname (1) subcategoriesname (14) subcategoriesname (9) subcategoriesname (2) subcategoriesname ( Categories name (2) subcategoriesname (28) subcategoriesname (17) Where the numbers represent how many categories and sub-items have articles if ($count==1){ header("Location:store.php"); }very simple I have issolated it and it doesn't redirect maybe u can see where my mistake is if so how would they be used in a mysql query? |