PHP - Can Anyone Help (php, Json And Mysqli)
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. Similar TutorialsI 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
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 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. 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? 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. 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> 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. 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 ? 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 This line of PHP mysqli::__construct($CFG->dbhost, $CFG->dbuser, $CFG->dbpass, $CFG->dbname); returns Quote Fatal error: Non-static method mysqli::mysqli() cannot be called statically in Why does it do this? I want to use the OOP MySQLi methods in PHP and NO procedural PHP 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,
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? Here is my code so far... I can't login using this php, i am new to php and am trying my hardest to figure this out... i have been on this for 4 days and am about to pull all of my hair out... can anyone please help me... //******** start of login.php ******** <?php require_once('connectvars.php'); // Start the session session_start(); // Clear the error message // $error_msg = ""; // If the user isn't logged in, try to log them in if (!isset($_SESSION['user_id'])) { if (isset($_POST['submit'])) { // Connect to the database $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); if (!$dbc) { die('Could not connect: ' . mysqli_error()); } echo 'Connected successfully'; // Grab the user-entered log-in data $user_email = mysqli_real_escape_string($dbc, trim($_POST['email'])); $user_pass = mysqli_real_escape_string($dbc, trim($_POST['password'])); if (!empty($user_email) && !empty($user_password)) { // Look up the username and password in the database $query = "SELECT tb_user_id, tb_user_email FROM tb_users WHERE tb_user_email = '$user_email' AND tb_user_password = SHA('$user_pass')"; $data = mysqli_query($dbc, $query); if (mysqli_num_rows($data) == 1) { // The log-in is OK so set the user ID and username session vars (and cookies), and redirect to the home page $row = mysqli_fetch_array($data); $_SESSION['user_id'] = $row['tb_user_id']; $_SESSION['email'] = $row['tb_user_email']; setcookie('user_id', $row['tb_user_id'], time() + (60 * 60 * 24 * 30)); // expires in 30 days setcookie('email', $row['tb_user_email'], time() + (60 * 60 * 24 * 30)); // expires in 30 days $home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/index.php'; header('Location: ' . $home_url); } else { // The username/password are incorrect so set an error message $error_msg = 'Sorry, you must enter a valid username and password to log in1.'; } } else { //*********** This is the error i keep getting // The username/password weren't entered so set an error message $error_msg = 'Sorry, you must enter your username and password to log in2.'; } } } // Insert the page header $page_title = 'Log In'; require_once('header.php'); // If the session var is empty, show any error message and the log-in form; otherwise confirm the log-in if (empty($_SESSION['user_id'])) { echo '<p class="error">' . $error_msg . '</p>'; ?> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <fieldset> <legend>Log In</legend> <label for="email">Email Address:</label> <input type="text" name="email" value="<?php if (!empty($user_email)) echo $user_email; ?>" /><br /> <label for="password">Password:</label> <input type="password" name="password"/> </fieldset> <input type="submit" value="Log In" name="submit" /> </form> <?php } else { // Confirm the successful log-in echo('<p class="login">You are logged in as ' . $_SESSION['email'] . '.</p>'); } ?> <?php // Insert the page footer require_once('footer.php'); ?> Greeting all. I am brand new to the forum and I would like to ask a question regarding mysqli. I am not certain why the following code works: Code: [Select] ... $sqlCmd = "select * from usrdata"; $rs = $mysqli->query($sqlCmd); ... and the following code gives me a 500 internal error: Code: [Select] ... $sqlCmd = "select * from usrdata"; $result= dbQuery($sqlCmd); ... function dbQuery($sqlCmd){ $rt = array(); $rs = $mysqli->query($sqlCmd); while($row = $rs->fetch_assoc ()){ $rt[] = $row; } return 'records: ' . json_encode($rt); } The error occurs on the mysqli->query. Thanks for any help. Cheers! 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; } } Hey. I was writing my class object for a database connection and while I was writing the query part, I came to wonder whether I should use mysql_real_escape_string or mysqli_real_escape_string to make the query mysql friendly, what's the difference? 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. Hi, I am having problems returning values from a select statement. When I query directly in the databse, I get back the information I am looking for. I use an includes file for the database connection and my page shows that the connection was successful. Here is my code: Code: [Select] <?php $search = $_GET['searchFor']; $words = explode(" ", $search); $phrase = implode("%' AND articlename LIKE '%", $words); $sql ="SELECT * FROM articles WHERE articlename LIKE '%phrase%'"; $result =$conn->query($sql) or die('Sorry, could not get any articles at this time'); $row =($result->fetch_all()) or die('No records found'); $numRows =$result->num_rows; If($numRows==0) { echo "<h2>Sorry, no articles were found with '$search' in them.</h2>"; } else { While($row=$result->fetch_assoc()) { $articleid = $row['articleid']; $title = $row['articlename']; $shortdesc = $row['shortdesc']; echo "<h2>Search Results</h2><br><br>\n"; echo "<a href=\"index.php?content=showarticle&id=$articleid\">$title</a><br>\n"; echo "$shortdesc<br><br>\n"; } } ?> The search term is coming from a search form in the navigation. I have used "echo" statements to check and make sure that the sesrch word is coming through to tghe page containing the above code. I have tried mysqli_error() statements in several places and don't see where the problem is. When I try the search the message that comes back is "No records found" Does not makee sense because I know it is there, can find it, and even have the same syntax as the SELECT statement I use when I ask for the php code. Going crazy trying to sort this out. Any suggestions, help etc are greatly appreciated. Thank youi. |