PHP - Problem In Mysql Indexing.
Hello everyone.
I have a large table consisting of 135497 rows
I have found that by indexing the table, it will take less time in quering the results.
In some site it shows that Using "Explain" before the queries will show that how much rows it has to travel to get the desired results.
SO I have doen and it shows like below...
mysql> EXPLAIN select * FROM ip2country WHERE 3084727327 BETWEEN begin_long_ip AND end_long_ip; +----+-------------+------------+------+---------------------------------------------------------------------------------+------+---------+------+--------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+------------+------+---------------------------------------------------------------------------------+------+---------+------+--------+-------------+ | 1 | SIMPLE | ip2country | ALL | ip_adress,begin_long_ip,end_long_ip,begin_long_ip_3,count_index,begin_long_ip_2 | NULL | NULL | NULL | 135497 | Using where | +----+-------------+------------+------+---------------------------------------------------------------------------------+------+---------+------+--------+-------------+The above results shows 135497. means it has to travel all the rows to get the result. So i have done index on the column ("begin_long_ip and end_long_ip) mysql> CREATE INDEX count_index ON ip2country(begin_long_ip,end_long_ip); Query OK, 135497 rows affected, 1 warning (0.87 sec) Records: 135497 Duplicates: 0 Warnings: 1But it still shows the same result. mysql> EXPLAIN select * FROM ip2country WHERE 3084727327 BETWEEN begin_long_ip AND end_long_ip; +----+-------------+------------+------+---------------------------------------------------------------------------------+------+---------+------+--------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+------------+------+---------------------------------------------------------------------------------+------+---------+------+--------+-------------+ | 1 | SIMPLE | ip2country | ALL | ip_adress,begin_long_ip,end_long_ip,begin_long_ip_3,count_index,begin_long_ip_2 | NULL | NULL | NULL | 135497 | Using where | +----+-------------+------------+------+---------------------------------------------------------------------------------+------+---------+------+--------+-------------+Ahy help will be greatly apprecaited... Similar TutorialsIn phpmyadmin, once I do a fulltext on a field, is that the only time I have to do it or does it have to be indexed anytime new data is added or altered? This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=351279.0 Is there such thing? I designed a while back a rudimentary form based app for my users. We receive from our suppliers hardware manufacturing data in XML files: file name is made of eleven fields separated by tildes, with each field having its own meaning. R&D guys wanted to be able to search each field of the file names so I used regex() with decent results. Problem is that we have now in the upwards of 2.5 million files. And my app can't hack it anymore. I looked at Apache Lucene & Solr. Though it seemed like the best solution to my problem, the fields in the filenames are not peers to the file content. Big no-no with Solr. What is the best way to implement a PHP app with indexing and search capability with such large number of files? Do I have to buy Zend and use Zend_Search? Is it the only way? Thanks for your input. HI - I am dynamically populating a drop down form list from the table 'hotels', and the 'est_town' column. It is supposed to only list each town once, but several towns appear multiple times. Am I using the DISTINCT command correctly and if so, what can i do to stop multiple appearances of towns? Code: [Select] $query_hotels_select = "SELECT DISTINCT est_town FROM hotels ORDER BY est_town ASC"; $hotels_select = mysql_query($query_hotels_select, $contractors) or die(mysql_error()); $row_hotels_select = mysql_fetch_assoc($hotels_select); $totalRows_hotels_select = mysql_num_rows($hotels_select); FORM BIT Code: [Select] <select name="digs" id="digs"> <?php do { ?> <option value="<?php echo $row_hotels_select['est_town']?>"<?php if (!(strcmp($row_hotels_select['est_town'], $row_hotels_select['est_town']))) {echo "selected=\"selected\"";} ?>><?php echo ucwords(strtolower($row_hotels_select['est_town']))?></option> <?php } while ($row_hotels_select = mysql_fetch_assoc($hotels_select)); $rows = mysql_num_rows($hotels_select); if($rows > 0) { mysql_data_seek($hotels_select, 0); $row_hotels_select = mysql_fetch_assoc($hotels_select); } ?> </select> i could connect to the database and i dod nothing but to go through privileges in phpmyadmin by selecting privileges of the data base i design and by using the icon (action) it gave me a page to edit user i selected all check boxes mentioned in the global privileges then pressed go and for resource limits i read a note that said setting these options to zero removes the limit i set then to 1 and by using the connection function i could connect to the data base Code: [Select] <?php $connectdb = mysql_connect('localhost','root','') or die("not connected"); $selectdb = mysql_select_db("koora", $connectdb); if($selectdb) { echo "ok you,re now connected to table "; }else die("couldn,t connect to the database"); when refreshing my page it showed a message that said ok you,re now connected to table but i got another problem which is by using this form <form action="admins.php" method='post'> <table align="center" valign="center"> <tr> <td> Admin,s name: </td> <td><input type="text" name="adminname" /><br /></td></tr> <td>Admin,s Password: </td> <td><input type="password" name="adminpassword" /></td></tr> <td><input type="submit" value="Add New Admin" /></td></tr> </form> </tr> </table> to enter user name and password and by using the following code to get the data to the page the form directs to $admin = $_POST['adminname']; $password = $_POST['adminpassword']; if($admin&&$password){ mysql_query("INSERT INTO 'admin'('','admin','password') VALUES('','$admin','$password');"); echo "admin was added"; }else die("not added"); every time i enter a name and password to the text box and press enter it shows the message that admin was added and by checking the table which data are entered and stored i find nothing was added and the table is empty i guess that this problem is because of something wrong with the database may be something with settings or some like that i need your help with this problem Thanks in advance So i started on a project and not within long, i hit a wicked wall. The upper part works fine, i get the correct $pilotcorpid, however it doesnt seem to query the 2nd time, it just uses the variable from the first time. I have the information in the database, i just need to pick em out right. Code: [Select] <?php include 'config.php'; //database config include 'opendb.php'; //connect database $search = @$_GET['q'] ; //getting a name from a form $result = mysql_query("SELECT * FROM kb3_pilots WHERE plt_name='$search'")or die(mysql_error()); //here i choose to check in the kb3_pilots table, the plt_name column for the name written in the form earlier. $pilotcorpid=mysql_result($result,"plt_crp_id"); //since i found the guy in the query, i need info from that column, the plt_crp_id. $resultcorp = mysql_query("SELECT * FROM kb3_corps WHERE crp_id='$pilotcorpid'")or die(mysql_error()); //now we query the kb3_corps table to check if the corp exists. $pilotcorpname=mysql_result($resultcorp,"crp_name"); //Because it did, i will now pull out the name echo "TEST: Pilot Id: $pilotcorpid and corp name: $pilotcorpname"; include 'closedb.php'; ?> If somebody also have a big php/mysql ebook which explains commands great, that would be awesome. Best regards, Mumlebumle I creating a members only web for my wife's 45th reunion. Everything went great untill I tackled something I never did before. PHP! From the home page I'm having the user enter a username and password. I created the db using phpmyadmin and populated the table with two users. I checked the include and it is attempting to open the db and proper table. however, the php loginck.php, goes to the programed error message. Can I get a little assistance, it would be greatly appreciated. The form calls loginck,pfp and it gets there OK. <div class="art-blockcontent"> <div class="art-blockcontent-body"> <!-- block-content --> <div style="border: medium ridge blue;padding:15px; font-size:.8em;"> To assist in maintaining contact with our alumni, please register. <br> Already registered, sign in. <br><br> <form action="loginck.php" method="POST"> <label>Username: </label><input type="varchar" style="height: 1em;" size="15" name="passWord" required> <br> <label>Password: </label><input type="password" style="height: 1em;" size="15" name="passWord" required> <br><br> <center><input type="submit" value="Sign In"> <input type="reset" value="Clear"></center> </form> <br><br> <a href="register.html">Register</a> <br> <hr> <br> This site best viewed using Google Chrome, FireFox, or Opera browsers. </form> </div> <!-- /block-content --> I attached loginck.php and the inserted a called file 'z_db.php' for your review. I know if I can get this figured out I can do the others I need to do. Sorry, if ther's too many typos, I'm relegated to typing with one finger (Stroke) and in a wheel chair. Well im using paypal IPN im trying to get it to update something out of my database. Heres the code I think this is all you need Quote <?php include('config.php') ?> <?php function updatePayments($data){ global $link; if(is_array($data)){ $sql = mysql_query("INSERT INTO `serverb` WHERE name = 'Official' (gold) VALUES ('yes')"); } } ?> How do i get it to work? Hi all. I'm not sure if this post belongs here or in the MySQL forum because I'm not entirely sure where the problem is. I have a script that takes data from a form and puts it into a database. There are several tables that were hand built and the script works fine with those. There are several tables that were converted from M$ Access to MySQL and the script does not work with those. All tables are InnoDB (if that matters). My inkling is that the converted tables that have weird field names, some containing "%","#", and "-" characters, are interfering with the MySQL statement to do the insert. Any thoughts on this? Would those odd characters for field names in fact affect the MySQL statement to enter data? P.S. I don't have access to the code at the moment. Can post it later unless the solution to this problem is simple (i.e. weird characters are the problem). Thanks in advance! Hello All, I Develop a small e-shop and i am facing a problem with invoice number I attach to an order the invoice number after client has successfully paid the order through Paypal, so i use the function below to retrieve the next inv num function GET_NEXT_INV_NUM() { $query= "SELECT MAX(inv_num) AS max_inv_num FROM orders"; $rs_query = mysql_query($query, $db) or die(mysql_error()); $row_query = mysql_fetch_assoc($rs_ws_mod_tvg_program_rec); $Next_inv_num = $row_query['max_inv_num']+1; return $Next_inv_num; } all looked to work fine but one day i realised that i have some invoice numbers that are missing, because in some cases instead of next inv to increase by one, is increased by two for example: INV NUMBERS: ============ 101 102 103 --->PROBLEM HERE (MISSING 104) 105 106 107 108 109 110 --->PROBLEM HERE (MISSING 111) 112 113 114 115 116 ... I check all of my code 3-4 times and all looks ok Can anyone help me please??? Thanks in advance (i apologise for my english) This is my code it always returns null i know that there is info in the table but it never works
$sql = 'SELECT * FROM $user WHERE ticker = "$ticker"'; $resultsql = mysqli_query($conp,$sql); $row = mysqli_fetch_array($resultsql); echo $row[ticker]; var_dump($row); echo '<br>'; this is probably going to be really simple to fix but i cant figure it out :/ on one page i have a form which uses php to populate a dropdown box, now this form will allow the user to add 1 to the person which was selected in the dropdown box. The code for this looks like this.. <form action="addpoint.php" method="post"> <select> <?php $sql="SELECT id,name FROM man"; $result =mysql_query($sql); while ($data=mysql_fetch_assoc($result)){ ?> <option value ="<?php echo $data['id'] ?>" ><?php echo $data['name'] ?></option> <?php } ?> </select> <input type="submit" value="Add Point"/> </form> the php to process this form looks like this.. <?php $sql="UPDATE man SET points = (points + 1) WHERE name = ('$_POST[name]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "$_POST[name] has been added"; mysql_close($con) ?> The problem i have is that i dont think its pulling the name from the form so therefore it wont effect the database, ive tried the sql like this.. UPDATE man SET points = (points + 1) WHERE name = 'joe' and it works fine, any help would be gratefully received Owen Hi, I would appreciate any help with this at all that you guys can give me. I am trying to get a list of unique users from a mysql table, then get the records for each of those user. I am then converting to a .csv and sending it through an email. I have the following code and I always only get the same record. The file name changes to the correct user but the data in the .csv is always only the first user. Thanks in advance. Code: [Select] echo "getusers"; $server = "localhost"; $link = mysql_connect("$server", "$user", "$password"); mysql_select_db("$database"); $getusers = "select distinct(`User`) from realtordata"; $result1 = mysql_query($getusers); $numusers = mysql_num_rows($result1); $userarray[$numusers]; // $s = 0; $userarray[$numusers]; $uservar = $userarray[$s]; echo "<table width = 5% border = '2'"; while ($row = mysql_fetch_array($result1)) { $userarray[$s] = $row['User']; // echo $userarray[$s]; $csv_file_name = "$uservar.csv"; echo "<tr><td>$userarray[$s] </td></tr>"; // $s++; $mySQL_query = "SELECT * FROM `realtordata` where `User` = '$uservar' order by `Status`"; $result = mysql_query($mySQL_query); $numrecs = mysql_num_rows($getdata); echo "<table border = '1'"; echo "<th> User </th><th>Date Added</th><th>First Name</th><th>Last Name </th><th> Status</th><th> Loan Timeframe</th><th>Need Purchase Realtor</th> <th> Real Estate Agent Name</th><th>Real Estate Agent Phone</th><th>Need Selling Realtor</th><th>Agent Company or Broker</th> <th> Agent Email</th><th>Agent City</th><th>Agent State</th>"; while($row = mysql_fetch_array($result)) { $s++; echo "$uservar"; $userarray[$s] = $row['User']; $user = $userarray[$s]; $date = $row['Date Added']; $fname = $row['First Name']; $lname = $row['Last Name']; $timeframe = $row['Loan Timeframe']; $needpurchaserealtor = $row['Need Purchase Realtor']; $agentname = $row['Real Estate Agent Name']; $agentphone = $row['Real Estate Agent Phone']; $needsellingrealtor = $row['Need Selling Realtor']; $agentcompanyorbroker = $row['Real Estate Agent Company or Broker']; $agentemail = $row['Real Estate Agent Email']; $agentcity = $row['Real Estate Agent City']; $agentstate = $row['Real Estate Agent State']; echo "<tr><td> $user </td>"; echo "<td> $date </td>"; echo "<td> $fname </td>"; echo "<td> $lname </td>"; echo "<td> $timeframe </td>"; echo "<td> $needpurchaserealtor </td>"; echo "<td> $agentname </td>"; echo "<td> $agentphone </td>"; echo "<td> $needsellingrealtor </td>"; echo "<td> $agentcompanyorbroker </td>"; echo "<td> $agentemail </td>"; echo "<td> $agentcity </td>"; echo "<td> $agentstate </td></tr>"; // Reuseable CSV file variables $csv_contain = '"'; $csv_separate = ","; $csv_end_row = "\n"; /* // run the MySQL query and check to see if results were returned*/ $result = mysql_query($mySQL_query); if (!$result) { die("ERROR: Invalid query \n MySQL error: " . mysql_error() . "\n Your query: " . $query); } echo "Step 3: MySQL query ran successfully. \n\n"; // store the number of columns from the results $columns = mysql_num_fields($result); // Build a header row using the mysql field names $header_row = ''; for ($i = 0; $i < $columns; $i++) { $column_title = $csv_contain . stripslashes(mysql_field_name($result, $i)) . $csv_contain . $csv_separate; $header_row .= $column_title; } $csv_file .= $header_row . $csv_end_row; // add header row to CSV file // Build the data rows by walking through the results array one row at a time $data_rows = ''; while ($row = mysql_fetch_array($result)) { for ($i = 0; $i < $columns; $i++) { // clean up the data; strip slashes; replace double quotes with two single quotes $data_rows .= $csv_contain . preg_replace('/"/', '\'\'', stripslashes($row[$i])) . $csv_contain . $csv_separate; } $data_rows .= $csv_end_row; // add data row to CSV file } $csv_file .= $data_rows; // add the data rows to CSV file echo "Step 4: CSV file built. \n\n"; /* -------------------------------------- SEND EMAIL WITH ATTACHMENT This requires the use of complex variable parsing {curly braces surrounding variable} For more information see: "PHP: Complex Variables in Strings" at Tinsology.net http://tinsology.net/2009/06/php-complex-variables-in-strings/ */ // start setting up the email header $headers = "From: ".$email_from; // create boundary string // boundary string must be unique using MD5 to generate a pseudo random hash $random_hash = md5(date('r', time())); $mime_boundary = "==Multipart_Boundary_x{$random_hash}x"; // set email header as a multipart/mixed message // this allows the sending of an attachment combined with the HTML message $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; // multipart boundary for the HTML message $email_message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $email_html_msg . "\n\n"; // encode CSV file with MIME base64 // required for sending it as an email attachment $data = chunk_split(base64_encode($csv_file)); // multipart boundary for the email attachment $email_message .= "--{$mime_boundary}\n" . "Content-Type: application/octet-stream;\n" . " name=\"{$csv_file_name}\"\n" . "Content-Disposition: attachment;\n" . " filename=\"{$csv_file_name}\"\n" . "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n"; // end the multipart message $email_message .= "--{$mime_boundary}--\n"; // try to send the email and verify the results $sendit = @mail($email_to, $email_subject, $email_message, $headers); if(!$sendit) { die("ERROR: The Email could not be sent."); } echo "Step 5: Email sent with attachment. \n\n"; } } How can I get this query to work? I am having problems with the HAVING section of it. Code: [Select] SELECT id,price, ( 6371 * acos( cos( radians($lat) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( lat ) ) ) ) AS distance FROM fuelstations HAVING distance < 250 , price > 0 ORDER BY price LIMIT 0 , 60; Hi PHP Freaks. Noobie here. Trying to learn PHP, following lecturesnippets.com PHP lessons. This is lesson 38. This seems like it should be simple, but no matter what I do, I can't get the database to update. Any help would be greatly appreciated. Thanks. Here's my code right now:
<html> well i am having a new problem i didnt relize this till now and my website has gone live and i need a fix asap before my user's leave and never return ='( well when i set up a auction there is a image upload where you can upload your image... when trying to upload the image it change page and gave me this error Code: [Select] A Mysql error has occurred while running the script: The query you are trying to run is invalid Mysql Error Output: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AND page_handle='auction'' at line 2 SQL Query: SELECT box_id, box_value FROM custom_fields_data WHERE owner_id= AND page_handle='auction' it was working before then i change some things around and dont remember what i change and found that this came up when setting up the image.... please help really need the help asap. i dont know what to do =( Hello again guys, am having trouble with a login script I have been working on. Have crawled the web for answers so thought i would post here again for some help. A brief run down on what the script is intended to do: 1.) The script checks to see if a user is logged in, and asks them to if their not. 2.) If theuser is logged in their userid is grabbed from $_SESSION and assigned to $userid 3.) Connection to the database is made and the field premium is updated with value "1" where userid = $userid A error message is supposed to be shown if the query has an error, but currently an error is not produced, the premium field remains NULL and the echo is shown. Can't for the the life of me fiqure out why it isn't working, but i think it is quite simple. Heres my script <?php if (!is_authed()) { echo 'You are not logged-in. Please login so we can add your purchased video to your account.'; include 'login_form.inc.php'; } else { include 'cp/config.php'; include 'cp/opendb.php'; $_SESSION['userid'] = $userid; $query = "UPDATE user SET premium='1' WHERE userid='$userid'"; mysql_query($query) or die('Error, query failed : ' . mysql_error()); echo 'Thank You for purchasing our series. We have added it to your account so you can use it straight away.'; } ?> For some reason the Hello , i need some help on this line. Line: $compose_a = mysql_query("SELECT * FROM users WHERE username LIKE '%". realEscape($sendto) ."%' LIMIT 1") or die(mysql_error()); From the code : <?php if(isset($_GET['usercp']) && $_GET['send'] == 'true') { if($_POST['sendtitle'] == "") { echo "You need to have a message title."; } else { if($_POST['sendto'] == "") { echo "You must enter the username of the user you wish to send a message to."; } else { if($_POST['sendtext'] == "") { echo "You have not entered anything to send"; } else { $sendto = str_replace('_', ' ' , $_POST['sendto']); $compose_a = mysql_query("SELECT * FROM users WHERE username LIKE '%". realEscape($sendto) ."%' LIMIT 1") or die(mysql_error()); if(mysql_num_rows($compose_a) >= 1) { While($compose_b = mysql_fetch_array($compose_a)) { $sendto = $compose_b['id']; } mysql_query("INSERT INTO `notifications` (ipaddress, senderid, recieverid, sent, title, text) VALUES ('". $_SERVER['REMOTE_ADDR'] ."', '". $_SESSION['id'] ."', '" . $sendto . "', NOW(), '". htmlspecialchars($_POST['sendtitle']) ."', '". htmlspecialchars($_POST['sendtext']) ."')") or die(mysql_error()); echo "Message has been sent."; } else { echo "The username you entered does not Exist"; } } } } } ?> The $sendto is a username. i want to make it so if a user puts a Uppercase letter or a lowercase letter or a space where a '_' should be. it still matchs whats in the database. if you find a better way of doing this please post it <?php $username="a7564065_si"; $password="*****"; $database="a7564065_food"; mysql_connect(mysql4.000webhost.com,$username,$password); ... I am trying to connect to mysql but having trouble. The host name: mysql4.000webhost.com I get the error: Parse error: syntax error, unexpected T_DNUMBER in /home/a7564065/public_html/Index.html on line 17 Any ideas? |