PHP - Mysqli Help
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. Similar TutorialsWhen 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?
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>
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 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 ? 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. 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(); ?> 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 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. Dear Sir/Madame I am making a website where user can insert data and wait for the admin to approve/reject the form. Now i am stuck with the update status where an admin can submit with a click pending to approval or reject with comments. I am new to PHP programming. Can somebody help me with the issue. Part 1 is inserting the data and part two is fetching the data but i am unable to solve the status approve/reject and comment at the same time on the view.php? page. Kindly help. Thank you. <?php $host="localhost"; $username="root"; $pass=""; $db="ems1"; $conn=mysqli_connect($host,$username,$pass,$db); if(!$conn){ die("Database connection error"); } // insert query for register page if(isset($_REQUEST['proposal'])) { $details=$_POST['details']; $location=$_POST['location']; $date=$_POST['date']; $time=$_POST['time']; $status="Pending"; $comment=$_POST['comment']; $query="INSERT INTO `proposal` (`details`,`location`,`date`,`time`,`status`,`comment`) VALUES ('$details','$location','$date','$time','$status','$comment')"; $res=mysqli_query($conn,$query); if($res){ $_SESSION['success']="Not Inserted successfully!"; header('Location:'); }else{ echo "Leave not Applied, please try again!"; } } ?> <div class="col-xs-6 col-xs-push-3 well"> <form class="form-horizontal" method="post" action="" > <input type="hidden" name="proposal" value=""> <fieldset> <legend>New Proposals </legend> <!----left box-----------> <!----right box-----------> <div class="col-xs-9"> <div class="form-group"> <label for="inputEmail" class="col-lg-3"><b>Details:</b></label> <div class="col-lg-9"> <input type="text" name="details" class="form-control"> </div> </div> <div class="form-group"> <label for="inputEmail" class="col-lg-3"><b>Location:</b></label> <div class="col-lg-9"> <input type="text" name="location" class="form-control" > </div> </div> <div class="form-group"> <label for="inputEmail" class="col-lg-3"><b>Date:</b></label> <div class="col-lg-9"> <input type="date" name="date" class="form-control"> </div> </div> <div class="form-group"> <label for="inputEmail" class="col-lg-3"><b>Time:</b></label> <div class="col-lg-9"> <input type="time" name="time" class="form-control" > </div> </div> <div class="col-lg-9"> <input type="hidden" name="status" class="form-control" > </div> </div> <div class="form-group"> <label for="inputEmail" class="col-lg-3"><b></b></label> <div class="col-lg-9"> <input type="hidden" name="comment" class="form-control"> </div> </div> </div> <div class="form-group"> <div class="col-lg-12"> <button type="reset" class="btn btn-default">Cancel</button> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </fieldset> </form> </div> </div> <body> <h2 style="text-align:center; color:orangered;"> DASHBOARD </h2> <table> <h3> <tr style="background-color:#E4EBC5; color:orangered;"> <th>ID</th> <th>Details</th> <th>Location</th> <th>Status</th> <th>Comment</th> </tr> </h3> </table> <?Php //////////////////////////////////////////// require "dbconfig.php"; // MySQL connection string $count="SELECT id,details,location,time,status,comment FROM proposal"; if($stmt = $connection->query($count)){ while ($nt = $stmt->fetch_assoc()) { echo " <body> <table> <tr> <td><a href=view.php?id=$nt[id]>$nt[id]</a></td> <td>$nt[details]</td> <td>$nt[location]</td> <td>$nt[status]</td> <td>$nt[comment]</td> </tr> </table> </body> "; } }else{ echo $connection->error; } ?>
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'); ?> 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? 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); ?> 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.... 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; } } 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! 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 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 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. Hi,
I'm trying to write a better PHP code to create and manage my website.
I would like to start a MVC approach with PHP, using OOP. So I can manage the updates in a better way. For example, to begin my project, I would try with the shipping cost of our products, using a Class without merge the PHP and HTML code.
Something like this:
$shippingcost=new ShippingCost(); $shippingcost->state="Italy"; $shippingcost->get(); // here I have an array with cost, discount, time ecc.And If I need it in JSON, I write: $shippingcost->get("JSON"); // here I have the JSON with cost, discount, time ecc.I wrote the Class in this way: class ShippingCost { public $state; private $arrayReturned; public function __construct() { $this->stato="Italy"; // the default state } public function __destruct() { } public function get($format="array") { $this->arrayReturned=array( "cost" => 3.99, "costDiscounted" => 7.99, "discount" => "50%" ); if (strtolower($formato)=="json") { $this->arrayReturned=json_encode($this->arrayReturned); } return $this->arrayReturned; } }It works well, but I need to get the values from a MySQL db. How can pass the MySQL connection to the Class? I'm not able to do this. Thanks in advance and have a great 2015. Rob. |