PHP - Updating To Mysqli
I am updating some old code to the IMPROVED version of PHP and running into a problem in this section after connecting successfully to my database: // retrieve the record that was selected $record_id = (isset($_POST['record_id'])) ? $_POST['record_id'] : ''; //check for $record_id emptiness if(!empty($record_id)){ // Retrieve ALL the data from the "example" table $result = mysqli_query($conn, "SELECT * FROM $table WHERE id = $record_id ") or die(mysqli_error()); // store the record of the "example" table into $row $row = mysqli_fetch_array( $result, MYSQLI_BOTH ); } Not sure what I'm missing or what needs to be re-organized. Please advise. Similar TutorialsHello, I've been tasked with updating our code base from mysql to something that will work with php 7. It's older code that was written by 2 or 3 individuals before me and it's not at all object oriented. There are about 540 different files that I will end up having to edit to make it all up to date. I'm not a very experienced programmer myself, and I'm in need of some guidance. There are some files that have functions that call and use mysql queries three or four files deep and going through and editing one function leads me to having to update 4 or 5 other files which breaks stuff somewhere else down the road. I was wondering if anyone has some suggestions on ways to make this process less painful. The other thing is that by using PDO in a not OO style, it seems like I'm losing a lot of its benefits. Should I consider using MYSQLi instead of PDO considering the circumstances? Are there any resources that you could point me to in order to help me learn the skills I need to make it through this upgrade? Thanks for the help! Hi, The following code is what I want in that it creates a menu and I can select and display a table row.
I still need to use that selection to update the "lastused". I really appreciate your help. <!DOCTYPE><html><head><title>email menu</title></head> <body><center> <form name="form" method="post" action=""> <?php $con=mysqli_connect("localhost","root","cookie","homedb"); //============== check connection if(mysqli_errno($con)) {echo "Can't Connect to mySQL:".mysqli_connect_error();} else {echo "Connected to mySQL</br>";} //This creates the drop down box echo "<select name= 'target'>"; echo '<option value="">'.'--- Select email account ---'.'</option>'; $query = mysqli_query($con,"SELECT target FROM emailtbl"); $query_display = mysqli_query($con,"SELECT * FROM emailtbl"); while($row=mysqli_fetch_array($query)) {echo "<option value='". $row['target']."'>".$row['target'] .'</option>';} echo '</select>'; ?> <input type="submit" name="submit" value="Submit"/><!-- update "lastused" using selected "target"--> </form></body></html> <!DOCTYPE><html><head><title>email menu</title></head> <body><center> <?php $con=mysqli_connect("localhost","root","cookie","homedb"); if(mysqli_errno($con)) {echo "Can't Connect to mySQL:".mysqli_connect_error();} if(isset($_POST['target'])) { $name = $_POST['target']; $fetch="SELECT target,username,password,emailused,lastused, purpose, saved FROM emailtbl WHERE target = '".$name."'"; $result = mysqli_query($con,$fetch); if(!$result) {echo "Error:".(mysqli_error($con));} $lastused = "CURDATE()"; // update "lastused" using selected "target" //display the table echo '<table border="1">'.'<tr>'.'<td bgcolor="#ccffff align="center">'. 'Email menu'. '</td>'.'</tr>'; echo '<tr>'.'<td>'.'<table border="1">'.'<tr>'.'<td bgcolor="#ccffff align="center">'.'target'.'</td>'.'<td bgcolor="#ccffff align="center">'.'username'.'</td>'.'<td bgcolor="#ccffff align="center">'.'password'.'</td>'.'<td bgcolor="#ccffff align="center">'.'emailused'.'</td>'.'<td bgcolor="#ccffff align="center">'.'lastused'.'</td>'.'<td bgcolor="#ccffff align="center">'.'purpose'. '</td>'.'<td bgcolor="#ccffff align="center">'. 'saved' .'</td>'.'</tr>'; while($data=mysqli_fetch_row($result)) {echo ("<tr><td>$data[0]</td><td>$data[1]</td><td>$data[2]</td><td>$data[3]</td><td>$data[4]</td><td>$data[5]</td><td>$data[6]</td></tr>");} echo '</table>'.'</td>'.'</tr>'.'</table>'; } ?> </body></html> I dont know whether the statement is correct.....i just tried it.....and it didn't work. $stmt->bind_param('ssiiiss',$_POST['name'],$_POST['email'],$_POST['d'],$_POST['m'],$_POST['y'],$_POST['add'],$_POST['phone']); here my first two values are strings and next 2 tiny int's next is int and last 2 again strings.
The below code produces a dropdown and when a selection is made and submitted produces --------------------------------------------------------------------------- <!DOCTYPE><html><head> <title>lookup menu</title> </head> <body><center><b> <form name="form" method="post" action=""> <?php // error_reporting(0); error_reporting(E_ALL ^ E_NOTICE); include 'homedb-connect.php'; //This creates the drop down box echo "<select name= 'target'>"; echo '<option value="">'.'--- Select account ---'.'</option>'; $query = mysqli_query($con,"SELECT target FROM lookuptbl"); $query_display = mysqli_query($con,"SELECT * FROM lookuptbl"); while($row=mysqli_fetch_array($query)) {echo "<option value='". $row['target']."'>".$row['target'] .'</option>';} echo '</select>'; ?> <input type="submit" name="submit" value="Submit"/> </form><center> <?php // error_reporting(0); error_reporting(E_ALL ^ E_NOTICE); include 'homedb-connect.php'; if(isset($_POST['target'])) { $name = $_POST['target']; $fetch="SELECT target, purpose, user, password, email, visits, date, saved FROM lookuptbl WHERE target = '".$name."'"; $result = mysqli_query($con,$fetch); if(!$result) {echo "Error:".(mysqli_error($con));} //display the table echo '<table border="1"><tr><td bgcolor="#ccffff" align="center">lookup menu</td></tr> <tr><td> <table border="1"> <tr> <td> Target </td> <td> Purpose </td> <td> User </td> <td> Password </td> <td> Email </td> <td> Visits </td> <td> Date </td> <td> Saved </td> </tr>'; while($data=mysqli_fetch_row($result)) { $url= "http://localhost/home/crud-link.php?target=". $data[0]; $link= '<a href="'.$url.'">'. $data[0]. '</a>'; echo ("<tr><td> $link </td><td>$data[1]</td><td>$data[2]</td><td>$data[3]</td> <td>$data[4]</td><td>$data[5]</td><td>$data[6]</td><td>$data[7]</td></tr>"); } echo '</table> </td></tr></table>'; } ?> </body></html>
Hello everyone, For two weeks now, I'm trying to get this database connection in my query. Can someone give me a solution and tell me what I've done wrong? Am I overlooking something? <?php class Mysql{ public function connect(){ $mysqli = new mysqli('localhost','root','','login'); } } class Query extends Mysql{ public function runQuery(){ $this->result = parent::connect()->query("select bla bla from bla bla"); } } $query = new Query; $query->runQuery(); ?> I am using mysqli, OO, to connect to MySQL. I have only today started looking at this and am used to: Code: [Select] <?php $con = mysql_connect();//etc mysql_close($connection); ?> Am I right that with mysqli (OO) that I don't need to set a connection variable wither when connecting or closing?? Code: [Select] <?php mysqli::connect();//etc mysqli::close(); ?> What about with multiple databases, does mysqli keep track for me, as I am used to this: Code: [Select] <?php $con1 = mysql_connect();//db1 $con2 = mysql_connect();//db2 ?> //etc I have just started using MySQLi and am clueless it is giving me the follow errors in which i do not understand
Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\Login\connect.php on line 23 Notice: Trying to get property of non-object in C:\xampp\htdocs\Login\connect.php on line 25 Notice: Use of undefined constant mysqli - assumed 'mysqli' in C:\xampp\htdocs\Login\connect.php on line 32 Warning: mysqli_query() expects parameter 1 to be mysqli, string given in C:\xampp\htdocs\Login\connect.php on line 32 Warning: mysql_fetch_assoc() expects parameter 1 to be resource, null given in C:\xampp\htdocs\Login\connect.php on line 33 can someone please explain to me why i am getting these? and my code is $mysqli_db = mysqli_select_db("$db_name"); if($mysqli_db->connect_errno) { printf("Database not found: %s\n", $mysql->connect_error); exit(); } $sql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'"; $result = mysqli_query($sql); $row = mysqli_fetch_assoc($result);I just got rid off most the errors the only ones left are Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\Login\connect.php on line 32 Fatal error: Call to undefined function mysqli_result() in C:\xampp\htdocs\Login\connect.php on line 33 Code Updated: $mysqli_db = mysqli_select_db($mysqli_connect, $db_name); if(!$mysqli_db) { printf("Database not found: %s\n", $mysqli->connect_error); exit(); } $sql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'"; $query = mysqli_query($sql); $result = mysqli_result($query); $row = mysqli_fetch_assoc($result); Edited by Tom8001, 30 November 2014 - 12:43 PM. Ok I am trying to use mysqli instead of the usual mysql. Mysql would be outdated. With mysqli, sgl-injection is impossible if you use the "?" in those codes. I would normally use a function but I've made a simple script to find the error. I use $parameters and $sql because these are the data I need to give as parameters to the function, so I used it here too but without the function actually. Code: [Select] ini_set('display_errors',1); // 1 == aan , 0 == uit error_reporting(E_ALL | E_STRICT); # sql debug define('DEBUG_MODE',true); // true == aan, false == uit $userid = 11; $lang = 1; $newLink = "testing123"; $db_host = "localhost"; $db_gebruiker = "root"; $db_wachtwoord = ''; $db_naam = "projecteasywebsite"; $sql= "INSERT tbl_link(userid,linkcat,linksubid,linklang,linkactive,linktitle) VALUES(?, ?, ?, ?, ?, ?)"; $parameters = '"iiisis", $userid, 1, 0, $lang, 1, $newLink'; echo $parameters; $mysqli = new mysqli($db_host, $db_gebruiker, $db_wachtwoord, $db_naam); $stmt = $mysqli->prepare($sql); $stmt->bind_param($parameters); $stmt->execute(); echo "<br><br>". mysqli_connect_errno(); echo "<br><br>". mysqli_report(MYSQLI_REPORT_ERROR); $stmt->close(); $mysqli->close(); I got Wrong parameter count for mysqli_stmt::bind_param() So naturally a problem when we execute : Warning: mysqli_stmt::execute() [mysqli-stmt.execute]: (HY000/2031): No data supplied for parameters in prepared statement ($stmt->execute() Is someone using mysqli too ? When running the following code i get the error: Call to undefined method mysqli::errno() the code: $conn = new mysqli(HOST, USER, PASSWORD, DATABASE); if ($conn->errno() !== 0) { $msg = $conn->error(); throw new connErrorException($msg, 'Connect'); } I am fairly new to classes but as i understand it this should be correct. I am using mysql 5.1 so mysqli is on by default. I have even checked the php ini and everything looks fine there in respect to this. Any advice? hello , I'm starting to use mysqli and i have few questions. is there a guide for mysqli? and how do i use this functions at mysqli ? mysql_num_rows mysql_query mysql_fetch_assoc mysql_fetch_array thanks , Mor. hi guys i get an error in this code (comment in the code): I Code: [Select] if (checkBd ($sql, $db, $valor, $codePass)){ ($sql = $db->prepare("UPDATE users SET activation = ? WHERE activationLink=?")); $valor="1"; $sql->bind_param('is', $valor, $codePass); $sql->execute(); $sql->bind_result($valor, $codePass); //Warning: mysqli_stmt::bind_result() [mysqli-stmt.bind-result]: Number of bind variables doesn't match number of fields in prepared statement if ($sql->fetch()) { header("location: index.php"); return true; } else { echo "no"; return false; } $sql->close(); $db->close(); } what is the possible problem in the script? an another question, is this way correct to update a boolean? thanks Hi everyone,
I can’t understand what happens… When I try my site in WAMP, I have the follow errors: Deprecated: mysql_query(): The mysql extension is deprecated and will be removed in the futu use mysqli or PDO (…) Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in (…) The same happened with the connect to mysql, but I solved using mysqli extension. But in this case is totally diferente. When I use the mysqli_query or mysqli_num_rows that are the alternatives presented I receive again other error, in PHP Manual says: "function.mysqli-query doesn't exist. Closest matches:" Someone know solve this problem??? When I use MySQL <?php session_start(); if (isset($_SESSION["manager"])){ header("location:index.php"); exit(); } ?> <?php if(isset($_POST["username"])&&isset($_POST["password"])){ $manager=preg_replace('#[^A-Za-z0-9]#i','',$_POST["username"]); $password=preg_replace('#[^A-Za-z0-9]#i','',$_POST["password"]); $cnn= include "../lojascript/connect_mysql.php"; $sql=mysql_query($cnn, "SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1"); $existCount=mysql_num_rows($sql); if ($existCount==1){ while ($row = mysqli_fetch_array($sql)){ $id=$row["id"]; } $_SESSION["id"]=$id; $_SESSION["manager"]=$manager; $_SESSION["password"]=$password; header("location:index.php"); exit(); }else { echo 'Informação incorrecta <a href="index.php"> Click here</a>'; exit(); } } ?>When I use MySQLi <?php session_start(); if (isset($_SESSION["manager"])){ header("location:index.php"); exit(); } ?> <?php if(isset($_POST["username"])&&isset($_POST["password"])){ $manager=preg_replace('#[^A-Za-z0-9]#i','',$_POST["username"]); $password=preg_replace('#[^A-Za-z0-9]#i','',$_POST["password"]); $cnn = include "../lojascript/connect_mysql.php"; $query= "SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1"; $result= mysqli_query($cnn,$query) or die(mysqli_error()); $num_row = mysqli_num_rows($result); if ($num_row==1) { while ($row = mysqli_fetch_array($result)){ $_SESSION["id"]=$row["id"]; } $_SESSION["id"]=$id; $_SESSION["manager"]=$manager; $_SESSION["password"]=$password; header("location:index.php"); exit(); }else { echo 'Informação incorrecta <a href="index.php"> Click here</a>'; exit(); } } ?> I have some code I used to have in mysql and now im trying to convert to mysqli and I cant seem to find out what the problem is.
<?php $username = $_SESSION['username']; // Connect to server and select databse. include "db_connect.php"; include "db_config.php"; // items tables selection $sql = mysqli_query($my_database,"SELECT * FROM items_tbl WHERE level = '$account_info[player_level]' ORDER BY rand()"); //$result = mysqli_query($my_database,$sql); // Put info into array (This Works) while($item = mysqli_fetch_assoc($sql)){ //stats $items_id['itemid'] = $item['itemid']; $items_id['Level'] = $item['Level']; $items_id['name'] = $item['name']; $items_id['min_str'] = $item['min_str']; $items_id['min_int'] = $item['min_int']; $items_id['min_dex'] = $item['min_dex']; $items_id['type'] = $item['type']; $items_id['min_dmg'] = $item['min_dmg']; $items_id['max_dmg'] = $item['max_dmg']; $items_id['phys_defense'] = $item['phys_defense']; $items_id['mag_defense'] = $item['mag_defense']; } ?>here is the error im getting: Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given hi What is the correct way to do a function like: Code: [Select] public function check_($db, $skills) { $arr_tags = array('16', '17', '36', '546'); $z = implode(', ', array_fill(0, count($arr_tags), '?')); $str = implode('', array_fill(0, count($arr_tags),'s')); $par = "'" . implode("','", $arr_tags) . "'"; $c_arr_tags = count($arr_tag); $sql = $db -> prepare(" SELECT offer_id_offer FROM offer_has_tags WHERE tags_id_tags IN ($z) GROUP BY offer_id_offer HAVING COUNT(*) = ? "); $sql -> bind_param("$srt.'i'", $par, $c_arr_tags); $sql -> execute(); $sql -> bind_result($id_offer); return $id_offer; } At the moment i got: Number of elements in type definition string doesn't match number of bind variables Hi everyone, I wanted to some investigating before I label this as a bug, but from what I can see I'm not getting expected results. It appears as if mysqli_stmt_result_metadata does not return the proper object. It should be of mysqli_result type, but yet when I run mysqli_num_rows against it, I get 0, always. If I do a direct mysqli_query and take the resultset back, I can call mysqli_num_rows and it returns the proper value. Example #1(doesn't work): if($this->statement = mysqli_prepare($this->databaseConnection, "SELECT 1 FROM DIGIUSERS WHERE UNAME = ?")) { mysqli_stmt_bind_param($this->statement, 's', $username); mysqli_stmt_execute($this->statement); $this->errorQuery(); $result = mysqli_stmt_result_metadata($this->statement); //Ooops, the username is already taken! exit with status of -7 if(mysql_num_rows($result) > 0) { mysqli_rollback($this->databaseConnection); exit("<STATUS>-7</STATUS></USER>"); } mysqli_stmt_close($this->statement); } Example #2 (works but i cant bind variables): $result = mysqli_query($this->databaseConnection, "SELECT 1 FROM DIGIUSERS WHERE UNAME = $username"); $this->errorQuery(); //Ooops, the username is already taken! exit with status of -7 if(mysqli_num_rows($result) > 0) { mysqli_rollback($this->databaseConnection); exit("<STATUS>-7</STATUS></USER>"); } I have variable binding working just fine elsewhere on the site so I know it's not that. The only thing I can think of is that mysqli_stmt_result_metadata is not returning the proper object. For now i will use #2 but, very begrudgingly.... Hi I'm trying to insert unique info retrieved to my database but seems like I'm doing something wrong with my quary my current setup is as follow
mxit.php
<?php $con=mysqli_connect("*****","*******","*******","******"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } mysqli_close($con); ?> <? define('TIMEZONE', 'Africa/Harare'); date_default_timezone_set(TIMEZONE); $ip = $_SERVER["REMOTE_ADDR"]; $post_time = date("U"); $mxitua = $_SERVER["HTTP_X_DEVICE_USER_AGENT"]; $mxitcont = $_SERVER["HTTP_X_MXIT_CONTACT"]; $mxituid = $_SERVER["HTTP_X_MXIT_USERID_R"]; $mxitid = $_SERVER["HTTP_X_MXIT_ID_R"]; $mxitlogin = $_SERVER["HTTP_X_MXIT_LOGIN"]; $mxitnick = $_SERVER["HTTP_X_MXIT_NICK"]; $mxitloc = $_SERVER["HTTP_X_MXIT_LOCATION"]; $mxitprof = $_SERVER["HTTP_X_MXIT_PROFILE"]; if(!isset($mxitid)) { $mxitid = "DEFAULT"; } mysqli_query($con,"INSERT INTO mxit (ip,time,user_agent,contact,userid,id,login,nick,location,profile) VALUES ($ip,$post_time,$mxitua,$mxitcont,$mxituid,$mxitid,$mxitlogin,$mxitnick,$mxitloc,$mxitprof)"); mysqli_close($con); ?> The following code is supposed to submit everything in the database on a table, Currently its doing the first row in the database. Not sure whats wrong.. function getNews(){ $query = $this->con->query("SELECT * FROM `". $this->prefix ."news`"); while ($result = $query->fetch_assoc()) { if($result['serveradded'] == 1){ $queryy = $this->con->query("SELECT * FROM `". $this->prefix ."news` WHERE serveradded=1"); while ($resultt = $queryy->fetch_assoc()) { return "<tr><td>The Advertisement ". ucfirst($resultt['name']) ." was created</td><td>". $resultt['date'] ."</td></tr>"; } } elseif($result['servupdate'] == 1){ $queryyy = $this->con->query("SELECT * FROM `". $this->prefix ."news` WHERE servupdate=1"); while ($resulttt = $queryyy->fetch_assoc()) { return "<tr><td>". $result['type'] ." ". ucfirst($resulttt['name']) ." was Updated by ". ucfirst($resulttt['updatedby']) ." </td><td>". $resulttt['date'] ." </td></tr>"; } } elseif($result['newuser'] == 1){ $queryyyy = $this->con->query("SELECT * FROM `". $this->prefix ."news` WHERE newuser=1"); while ($resultttt = $queryyyy->fetch_assoc()) { return "<tr><td>Account Created: ". ucfirst($resultttt['name']) ." was created</td><td>". $resultttt['date'] ."</td></tr>"; } } } } I have converted my mysql to mysqli and am working on converting some functions. My question - Can I not just convert the mysql to mysqli? This is the full code: Code: [Select] class zipcode_class { var $last_error = ""; // last error message set by this class var $last_time = 0; // last function execution time (debug info) var $units = _UNIT_MILES; // miles or kilometers var $decimals = 2; // decimal places for returned distance function get_zip_point($zip) { // This function pulls just the lattitude and longitude from the // database for a given zip code. $sql = "SELECT lat, lon from zip_code WHERE zip_code='$zip'"; $r = $mysqli->query($sql); if (!$r) { $this->last_error = mysql_error(); return false; } else { $row = mysql_fetch_array($r); mysql_free_result($r); return $row; } } function calculate_mileage($lat1, $lat2, $lon1, $lon2) { // used internally, this function actually performs that calculation to // determine the mileage between 2 points defined by lattitude and // longitude coordinates. This calculation is based on the code found // at http://www.cryptnet.net/fsp/zipdy/ // Convert lattitude/longitude (degrees) to radians for calculations $lat1 = deg2rad($lat1); $lon1 = deg2rad($lon1); $lat2 = deg2rad($lat2); $lon2 = deg2rad($lon2); // Find the deltas $delta_lat = $lat2 - $lat1; $delta_lon = $lon2 - $lon1; // Find the Great Circle distance $temp = pow(sin($delta_lat/2.0),2) + cos($lat1) * cos($lat2) * pow(sin($delta_lon/2.0),2); $distance = 3956 * 2 * atan2(sqrt($temp),sqrt(1-$temp)); return $distance; } function get_zips_in_range($zip, $range, $sort=1, $include_base) { // returns an array of the zip codes within $range of $zip. Returns // an array with keys as zip codes and values as the distance from // the zipcode defined in $zip. $this->chronometer(); // start the clock $details = $this->get_zip_point($zip); // base zip details if ($details == false) return false; // This portion of the routine calculates the minimum and maximum lat and // long within a given range. This portion of the code was written // by Jeff Bearer (http://www.jeffbearer.com). This significanly decreases // the time it takes to execute a query. My demo took 3.2 seconds in // v1.0.0 and now executes in 0.4 seconds! Greate job Jeff! // Find Max - Min Lat / Long for Radius and zero point and query // only zips in that range. $lat_range = $range/69.172; $lon_range = abs($range/(cos($details[0]) * 69.172)); $min_lat = number_format($details[0] - $lat_range, "4", ".", ""); $max_lat = number_format($details[0] + $lat_range, "4", ".", ""); $min_lon = number_format($details[1] - $lon_range, "4", ".", ""); $max_lon = number_format($details[1] + $lon_range, "4", ".", ""); $return = array(); // declared here for scope $sql = "SELECT zip_code, lat, lon FROM zip_code "; if (!$include_base) $sql .= "WHERE zip_code <> '$zip' AND "; else $sql .= "WHERE "; $sql .= "lat BETWEEN '$min_lat' AND '$max_lat' AND lon BETWEEN '$min_lon' AND '$max_lon'"; $r = mysql_query($sql); if (!$r) { // sql error $this->last_error = mysql_error(); return false; } else { while ($row = mysql_fetch_row($r)) { // loop through all 40 some thousand zip codes and determine whether // or not it's within the specified range. $dist = $this->calculate_mileage($details[0],$row[1],$details[1],$row[2]); if ($this->units == _UNIT_KILOMETERS) $dist = $dist * _M2KM_FACTOR; if ($dist <= $range) { $return[str_pad($row[0], 5, "0", STR_PAD_LEFT)] = round($dist, $this->decimals); } } mysql_free_result($r); } // sort array switch($sort) { case _ZIPS_SORT_BY_DISTANCE_ASC: asort($return); break; case _ZIPS_SORT_BY_DISTANCE_DESC: arsort($return); break; case _ZIPS_SORT_BY_ZIP_ASC: ksort($return); break; case _ZIPS_SORT_BY_ZIP_DESC: krsort($return); break; } $this->last_time = $this->chronometer(); if (empty($return)) return false; return $return; } } Hi,
Im using Mysqli and im trying to limit the results by 10 and order them from last to first from the database.
$sqlhorses = "SELECT Place FROM `*` WHERE `Horse` ='".$db->real_escape_string($row['horse']). "'";the above works but when i added the limit 6 to the end it shows errors. Can anyone help? I was pointed in this direction by a friend so firstly, hello
I'm having some teething problems (basically can't get my head around it) and wondered if anyone would be able to have a look at a script for me (beer money may be provided)
I'm currently using a php script which grabs information from a API with curl (JSON format). I'm limited to a number of requests an hour so my plan was to read the file, insert the data into a mysql table so that I could re-read over and over again with no limitations. Then use a script to run every few hours to grab the data.
The script I created works however it's a bit buggy with regards to what it does if information is already in the table. If there isn't a previous entry then it inserts everything fine.
The JSON data is a multi depth array, and deals with images as well as data so for me, it's rather complex.
What I want the script to do is this. Each item is a property (letting agent website)
Check to see if the property exists in the database and the JSON. If there is no record in the database, then insert in. If there is a record in the database, update that record. If there is a property in the database which isn't in the JSON file, then delete it from the database.
This is basically the same plan for each sub array (pictures, floorplans, etc) however the images are copied from the url given (hosted on amazon) to my own host in order to speed up loading times, etc.
i've added a copy of the code but obviously its going to be stupidly hard to understand.
Is there any way this could be split into different functions to try and sort it out? haha
<?php $ch = curl_init(); /* Section 1 */ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_URL, 'URL'); //prepare the field values being posted to the service $data = array("appkey" => "KEY","account" => "ACCOUNT" ); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //make the request $result = curl_exec($ch); $properties = json_decode($result, true); $properties = $properties['properties']; //pr($parsed_json); foreach($properties as $key => $value) { /* Set the vars */ $microTime = microtime(); $time = time(); $cat_id = $value['category_id']; $price = $value['price']; if ($value['category_id'] == "1") { $price_after = $value['qualifier_name']; } else { $price_after = $value['freq_name']; } $full_address = $value['full_address']; $address_1 = $value['address_1']; $address_2 = $value['address_2']; $address_3 = $value['address_3']; $address_4 = $value['address_4']; $address_5 = $value['address_5']; $bedrooms = $value['bedrooms']; $bathrooms = $value['bathrooms']; $summary = $value['summary']; $description = $value['description']; $type_name = $value['type_name']; $status = $value['status']; $feature_1 = $value['feature_1']; $feature_2 = $value['feature_2']; $feature_3 = $value['feature_3']; $feature_4 = $value['feature_4']; $lat = $value['lat']; $long = $value['lng']; /* Delete the properties from the database which can't be found in the file */ $searchProp = "SELECT property_id FROM props WHERE property_address_full = '$full_address' AND property_catid = '$cat_id'"; if ($result = mysqli_query ($linkq, $searchProp)) { if (!$whereStatement) { $whereStatement = "WHERE property_id != $row[property_id]"; } else { $whereStatement .= " OR property_id != $row[property_id]"; } // Set the whereStatement for deleting properties with no ID $deleteProp = "DELETE FROM props $whereStatement"; if ($result = mysqli_query ($linkq, $deleteProp)) { $totalPropsDeleted++; echo "Properties deleted $deleteProp"; $deleteimg = "DELETE FROM props_images $whereStatement"; if ($result = mysqli_query ($linkq, $deleteimg)) { echo ("Images Deleted Successfully<br />\n"); } else { echo ("Error Deleting"); } $deleteepc = "DELETE FROM props_epcs $whereStatement"; if ($result = mysqli_query ($linkq, $deleteepc)) { echo ("EPCs Deleted Successfully<br />\n"); } else { echo ("Error Deleting"); } $deletepdf = "DELETE FROM props_pdf $whereStatement"; if ($result = mysqli_query ($linkq, $deletepdf)) { echo ("PDFs Deleted Successfully<br />\n"); } else { echo ("Error Deleting"); } $deletefloorplan = "DELETE FROM props_floorplans $whereStatement"; if ($result = mysqli_query ($linkq, $deletefloorplan)) { echo ("Floorplans Deleted Successfully<br />\n"); } else { echo ("Error Deleting"); } } else { echo "Nothing to delete"; } } echo "<br />"; /* Check to see if the property exists currently */ $existCheck = "SELECT * FROM props WHERE property_address_full LIKE '%$full_address%' AND property_catid = '$cat_id'"; if ($result = mysqli_query ($linkq, $existCheck)) { $row_cnt = mysqli_num_rows($result); if ($row_cnt) { while ($row = $result->fetch_array(MYSQLI_ASSOC)) { echo "Property Exists - $full_address"; if (($row[property_price] != $price) || ($row[property_summary] != $summary) || ($row[property_description] != $description)) { $dateUpdated = "property_updated = $microTime,"; } else { $dateUpdated = "property_updated = property_updated,"; } /* Property exists so update the property info */ $updateProp = "UPDATE props SET property_advertised = property_advertised, $dateUpdated property_catid = '$cat_id', property_price = '$price', property_price_after = '$price_after', property_address_full = '$full_address', property_address_1 = '$address_1', property_address_2 = '$address_2', property_address_3 = '$address_3', property_address_4 = '$address_4', property_address_5 = '$address_5', property_bedrooms = '$bedrooms', property_bathrooms = '$bathrooms', property_summary = '$summary', property_description = '$description', property_type = '$type_name', property_status = '$status', property_feature_1 = '$feature_1', property_feature_2 = '$feature_2', property_feature_3 = '$feature_3', property_feature_4 = '$feature_4', property_lat = '$lat', property_long = '$long' WHERE property_id = '$row[property_id]'"; if (mysqli_query ($linkq, $updateProp)) { $totalPropsUpdated++; echo (" & Updated"); } else { echo (" & Error Updating"); } echo ("<br />\n"); /* Delete all the photos for this property as it doesn't matter if they are added again */ $deletePhotos = mysqli_query ($linkq, "DELETE FROM props_images WHERE property_id = $row[property_id] OR property_id = ''"); printf("Images Deleted: %d\n", mysqli_affected_rows($linkq)); printf("<br />\n"); /* Loop the current images and add back to the database and asign the property id */ $primaryimg = 0; $totalimg = count($value['images']); for ($x = 0; $x < $totalimg; $x++) { $imagename = $value['images'][$x]; if (!$primaryimg) { $image_main = "1"; } else { $image_main = "0"; } $insertphoto = "INSERT into props_images VALUES ('', '$row[property_id]', '$imagename', '$image_main', '')"; if (mysqli_query ($linkq, $insertphoto)) { echo ("- Inserted ($row[property_id]) ($imagename) ($image_main)\n"); if (!file_exists('images/props/'. $imagename .'.jpg')) { /* Try and copy the image from the url */ $file = 'https://utili-media.s3-external-3.amazonaws.com/stevemorris/images/' . $imagename . '_1024x1024.jpg'; $newfile = 'images/props/' . $imagename . '.jpg'; if (!copy($file, $newfile)) { echo "- Failed to Copy\n"; } else { echo "- Image Copied"; /* Resize the image and create a thumb nail */ $image = new SimpleImage(); $image->load('images/props/' . $imagename . '.jpg'); $image->resizeToWidth(240); $image->save('images/props/thumb/' . $imagename . '.jpg'); } } else { echo ("- Nothing to upload, image exists"); } echo "<br />\n"; } else { echo ("- Image Insert Error\n"); } $primaryimg++; } /* close the image loop */ /* Delete all the epcs for this property as it doesn't matter if they are added again */ $deleteEpcs = mysqli_query ($linkq, "DELETE FROM props_epcs WHERE property_id = $row[property_id]"); printf("EPCs Deleted: %d\n", mysqli_affected_rows($linkq)); printf("<br />\n"); /* Loop the current EPCs and insert into the database */ $totalepc = count($value['epcs']); for ($y = 0; $y < $totalepc; $y++) { $epcname = $value['epcs'][$y]; $insertepc = "INSERT into props_epcs VALUES ('', '$new_property_id', '$epcname')"; if (mysqli_query ($linkq, $insertepc)) { echo ("- Inserted EPC ($new_property_id) ($epcname)<br />\n"); } else { echo ("- EPC Insert Error\n"); } } /* close the epc loop */ /* Delete all the pdfs for this property as it doesn't matter if they are added again */ $deletePdfs = mysqli_query ($linkq, "DELETE FROM props_pdf WHERE property_id = $row[property_id]"); printf("PDFs Deleted: %d\n", mysqli_affected_rows($linkq)); printf("<br />\n"); /* Loop the current PDFs and insert into the database */ $totalpdf = count($value['pdfs']); for ($v = 0; $v < $totalpdf; $v++) { $pdfname = $value['epcs'][$v]; $insertpdf = "INSERT into props_pdf VALUES ('', '$new_property_id', '$pdfname')"; if (mysqli_query ($linkq, $insertpdf)) { echo ("- Inserted PDF ($new_property_id) ($pdfname)<br />\n"); } else { echo ("- PDF Insert Error\n"); } } /* close the PDF loop */ /* Delete all the pdfs for this property as it doesn't matter if they are added again */ $deleteFloorplan = mysqli_query ($linkq, "DELETE FROM props_floorplans WHERE property_id = $row[property_id]"); printf("Floorplans Deleted: %d\n", mysqli_affected_rows($linkq)); printf("<br />\n"); /* Loop the current Floorplans and insert into the database */ $totalfloorplan = count($value['floorplans']); for ($v = 0; $v < $totalfloorplan; $v++) { $floorplanname = $value['floorplans'][$v]; $insertfloorplan = "INSERT into props_floorplans VALUES ('', '$new_property_id', '$floorplanname')"; if (mysqli_query ($linkq, $insertfloorplan)) { echo ("- Inserted Floorplan ($new_property_id) ($floorplanname)<br />\n"); } else { echo ("- Floorplan Insert Error\n"); } } /* close the Floorplan loop */ } /* close the property while loop */ } else { /* close the if row exists loop */ /* Insert the property as it doesn't exist in the database */ $insert = "INSERT INTO props VALUES ('', '$time', '', '$cat_id', '$price', '$price_after', '$full_address', '$address_1', '$address_2', '$address_3', '$address_4', '$address_5', '$bedrooms', '$bathrooms', '$summary', '$description', '$type_name', '$status', '$feature_1', '$feature_2', '$feature_3', '$feature_4', '$lat', '$long', '', '')"; if (mysqli_query ($linkq, $insert)) { $totalPropsAdded++; echo ("Property Inserted - $value[full_address]<br />"); /* get the property ID from the newly added property */ $getPropID = mysqli_query ($linkq, "SELECT property_id FROM props ORDER BY property_id DESC LIMIT 1"); while ($rowNew = $getPropID->fetch_array(MYSQLI_ASSOC)) { $new_property_id = $rowNew[property_id]; } /* Loop the current images and add to the database and asign the property id */ $primaryimg = 0; $totalimg = count($value['images']); for ($x = 0; $x < $totalimg; $x++) { $imagename = $value['images'][$x]; if (!$primaryimg) { $image_main = "1"; } else { $image_main = "0"; } $insertphoto = "INSERT into props_images VALUES ('', '$new_property_id', '$imagename', '$image_main', '')"; if (mysqli_query ($linkq, $insertphoto)) { echo ("- Inserted Image ($new_property_id) ($imagename) ($image_main)<br />\n"); } else { echo ("- Image Insert Error\n"); } $primaryimg++; } /* close the images loop */ /* Loop the current epcsand add to the database and asign the property id */ $totalepc = count($value['epcs']); for ($y = 0; $y < $totalepc; $y++) { $epcname = $value['epcs'][$y]; $insertepc = "INSERT into props_epcs VALUES ('', '$new_property_id', '$epcname')"; if (mysqli_query ($linkq, $insertepc)) { echo ("- Inserted EPC ($new_property_id) ($epcname)<br />\n"); } else { echo ("- EPC Insert Error\n"); } } /* close the epcs loop */ /* Loop the current pdfs and add to the database and asign the property id */ $totalpdf = count($value['pdfs']); for ($v = 0; $v < $totalpdf; $v++) { $pdfname = $value['epcs'][$v]; $insertpdf = "INSERT into props_pdf VALUES ('', '$new_property_id', '$pdfname')"; if (mysqli_query ($linkq, $insertpdf)) { echo ("- Inserted PDF ($new_property_id) ($pdfname)<br />\n"); } else { echo ("- PDF Insert Error\n"); } } /* close the pdfs loop */ /* Loop the current floorplans and add to the database and asign the property id */ $totalfloorplan = count($value['floorplans']); for ($v = 0; $v < $totalfloorplan; $v++) { $floorplanname = $value['floorplans'][$v]; $insertfloorplan = "INSERT into props_floorplans VALUES ('', '$new_property_id', '$floorplanname')"; if (mysqli_query ($linkq, $insertfloorplan)) { echo ("- Inserted Floorplan ($new_property_id) ($floorplanname)<br />\n"); } else { echo ("- Floorplan Insert Error\n"); } } /* close the floorplans loop */ } else { echo ("Insert Error"); } /* close the insert property */ } /* close the row count loop */ } /* close the property exists loop */ } /* close everything */ curl_close($ch); mysqli_close ($linkq); ?> Edited by Jam0r, 08 December 2014 - 10:51 AM. |