Jump to content

Search the Community

Showing results for tags 'mysqli'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...

Date Created

  • Start


Last Updated

  • Start


Filter by number of...


  • Start





Website URL








Donation Link

  1. Hy I'm trying to execute this query $stmt = $mysqli->prepare("SELECT streamer,content,provider FROM evento,canali WHERE canali.id=evento.idcanale AND evento.titolo LIKE '%?%' OR evento.sottotitolo LIKE '%?%' AND evento.datainizio=2013-02-21;"); $stmt->bind_param('ss',$tok,$tok); $stmt->execute(); $stmt->close(); but I get this error Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement. but to me it seems like the number are the same, you can see how I prepared the statement with 2 arguments to define, and then I passe 2 arguments to add_param, what I'm getting wrong? some has some ideas? thanks daniele New php-forum User Posts: 2 Joined: Fri May 03, 2013 6:48 pm
  2. I'm fairly new to object orientated PHP and I was trying to think of a better way to connect to a MySQLi database within classes and functions, instead of just putting down an include everywhere. So far I came up with this: database.php <?php class database { protected $db_name = 'database'; protected $db_user = 'root'; protected $db_password = 'password'; protected $db_host = 'localhost'; function __construct(){ $this->connect(); } public function connect(){ $this->db = new mysqli($this->db_host, $this->db_user, $this->db_password, $this->db_name); } } $db = new database; ?> test.php class test{ private function getDb(){ include("database.php"); return $db; } public function test1(){ $find = $this->getDb()->db->query("SELECT * FROM user"); $rows = $find->num_rows; return $rows; } } and then just putting echo $test->test1(); on my page. I did have other functions inside the database class, but I've since scrapped those, so it just looks like that atm. It does work... however, I'm not sure how good or bad it is. In particular the first line in the test1() function. I have a feeling its a terrible way to do it... Or is it fine? like efficiency wise etc? before I would just use an include within every function. so I'd just do: $db->query(" "); Eventually I will have a few classes like user, etc, and these would all need to manipulate the database. So I was just thinking of plopping the getDb() function at the top of each of them and just include the database stuff... I tried looking at how phpBB and wordpress handle databases, but theirs are just full of unnecessary stuff for me and its just difficult to decipher. They use a global I think?
  3. This is my first time converting code in php. I really have no idea what I'm doing and can't tell if i'm doing it right or not. I would appreciate it very much if you could help me. Thanks! From process_new_user.php mysqli if ($insert_stmt = $mysqli-> prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) { $insert_stmt-> bind_param('ssss', $username, $email, $password, $random_salt); $insert_stmt-> execute(); // Execute the prepared query. echo "<script>"; echo "alert(\"New User Successfully Added!\");"; echo "window.location = \"users.php#current_user\";"; echo "</script>"; } else { echo "alert(\"Uh Oh! Something went terribly wrong.\");"; echo "</script>"; } pdo (attempt) if ($params = array(':username' => $username, ':email' => $email, ':password' => $password, ':random_salt' => $random_salt); $insert_stmt->prepare("INSERT INTO members (username, email, password, salt) VALUES (:username, :email, :password, :random_salt)")) { $insert_stmt-> execute($params); // Execute the prepared query. echo "<script>"; echo "alert(\"New User Successfully Added!\");"; echo "window.location = \"users.php#current_user\";"; echo "</script>"; } else { echo "alert(\"Uh Oh! Something went terribly wrong.\");"; echo "</script>"; } from process_delete_user.php (i converted as much of this as i could. But the last part I have no idea.) original mysqli foreach($id as $check) { $conn = new mysqli(host, user, password, database); if($conn == false){ echo "connection has failed"; } $sql=("DELETE FROM $table WHERE id ='$check'"); $res=mysqli_query($conn, $sql); if($res == true){ echo "<script>"; echo "alert(\"User Successfully Deleted!\");"; echo "window.location = \"users.php#delete_user\";"; echo "</script>"; } else { echo "<script>"; echo "DELETE failed".mysqli_error($conn); // echo "window.location = \"users.php#delete_user\";"; echo "</script>"; } mysqli_close ($conn); } PDO (attempt) foreach($id as $check) { $conn = new PDO(host, database, user, password); if($conn == false){ echo "connection has failed"; } $sql->prepare("DELETE FROM :table WHERE id = :check"); $sql->exectute(array(':username' => $table, ':check' => $check); $res=mysqli_query($conn, $sql); if($res == true){ echo "<script>"; echo "alert(\"User Successfully Deleted!\");"; echo "window.location = \"users.php#delete_user\";"; echo "</script>"; } else { echo "<script>"; echo "DELETE failed".mysqli_error($conn); // echo "window.location = \"users.php#delete_user\";"; echo "</script>"; } mysqli_close ($conn); }
  4. Hi Everyone, I am using the bind_param() function and am building a function around it. I need an automated way of inserting a uncertain (unlimited) amount of parameters into this function. ie have the php code able to insert parameters into the bind_param() function on its own. So if it is given 3 parameters put them in as bind_param($param1,$param2,$param3) or if given 5 parameters bind_param($param1,$param2,$param3,$param4,$param5) I need a way of having the script insert them in for me. What I was thinking was having all of these parameters giving to a function above this as an array. I would then use a foreach loop to determine what type of value each value in this array is and create a string with the appropriate letters to have as the first parameter in the bind_param($value_types ... Then I need a way of cycling through this array and adding how ever many values it has, as individual parameters, to the bind_param() function. Thanks in advance, Timothy
  5. Hello, I am new to mysqli and have a little question. I have tried to find an alternative for a while now but nothing seems to work... maybe somebody could help. So my old code is this function ($email) { $query = mysql_query("SELECT COUNT(`user_id`) FROM users WHERE email = '$email'")or die (mysql_error()); return (mysql_result($query, 0) == 1) ? true : false; } after that the function is used like this : if (login_email_exists($mysqli,$_POST['email']) === true) { $errors[] = 'Sorry this email adress is already in use.'; } And my new code is this function ($mysqli,$email) { $query = $mysqli->query("SELECT COUNT(`user_id`) FROM users WHERE email = '$email'")or die (mysql_error()); return ($query == 1) ? true : false; } Now it seems to always go wrong when I want to check the result and return if it's true or false. If anybody can find an answer or alternative to my problem I would be very happy.
  6. Im new to prepared statement and after a lot of research and reading, i still cant get it right. I have created a small database with user_id auto, name, lastname, and tried to make an insert with prepared statement. I have tried it several ways but still cant spot the error. Here is my 1 code. <?php $mysqli = new mysqli ('localhost', 'root', '','lr') or die ('there is a problem'); if (!($stmt = $mysqli->prepare("INSERT INTO pps(name) VALUES (?)"))) { echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error; } /* Prepared statement, stage 2: bind and execute */ $username = "john"; if (!$stmt->bind_param($username)) { echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error; } if (!$stmt->execute()) { echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error; } $stmt->close(); ?> This above code, gives me Warning: Wrong parameter count for mysqli_stmt::bind_param() in line 9. Binding parameters failed: (0) Execute failed: (2031) No data supplied for parameters in prepared statement. Note: Line 9 is this : $username = "john"; Then i tried this code which also fails. <?php $mysqli = new mysqli ('localhost', 'root', '','lr') or die ('there is a problem'); $query = "INSERT INTO pps (name, lastname) VALUES (?,?,)"; $stmt = $mysqli->prepare($query); $val1 = 'John'; $val2 = 'Lastname'; $stmt->bind_param("ss", $val1, $val2); /* Execute the statement */ $stmt->execute(); $val1 = 'Mark'; $val2 = 'Lastnamel'; /* Execute the statement */ $stmt->execute(); /* close statement */ $stmt->close(); $mysqli->close(); ?> This code results in Fatal error: Call to a member function bind_param() on a non-object in C:\xampp\htdocs\PreparedStatement\test.php on line 9. How can i correct this ?
  7. Hello, I'm trying to create a script which searchs through several columns in a table, using a keyword to search. I use mysqli and a query with MATCH AGAINST. I have got a code but it does not work and I do not know why. It does not give any error, but it basicly returns nothing. Here is my code: <?php if (isset($_POST['submit'])) { $tag = $_POST['tag']; include("database/database.php"); $query = ("SELECT Tutorialid, Title, Author FROM tutorials WHERE MATCH (Title, Body1, Body2, Body3, Body4, Author) AGAINST (?)"); if ($stmt = $connection->prepare($query)){ $stmt->bind_param("s",$tag); $stmt->execute(); $stmt->bind_result($id, $title, $author); $html_table = '</br></br><table class="cats" cellpadding="10" cellspacing="0"> <tr> <th class="cath">Title</th> <th class="cath">Author</th> <th class="cath">Link</th> </tr>'; while ($stmt->fetch()) { $link = "<a href='http://everytutorial.net/tutorials/".$id."'>Click here to open</a>"; $html_table .= '<tr><td class="catd">' .$title. '</td><td class="catd">' .$author.'</td><td class="catd">'.$link.'</td></tr>'; } $html_table .='</table></br></br></br>'; if (empty($id)) { echo "<p>No tutorials found milord.</p>"; } else { echo $html_table; $stmt->free_result(); $connection->close(); } } } I'm not sure what's wrong with it - any help could be great, thanks!
  8. I have extensively searched the web for this but haven't found anything that can help! At the moment I have three loops: // loop 1 finds the answers if(isset($_POST['qanswer'])){ ($question = $_POST['qanswer']); for($i=0; $i < count($question); $i++) { echo "POSTED ANSWERS" . $question[$i] . "<br/>"; } } else { echo '<p style="color: Red">No Answers POSTED!</p>'; } // loop 2 finds the comments if(isset($_POST['canswer'])){ ($comment = $_POST['canswer']); for($i=0; $i < count($comment); $i++) { echo "POSTED COMMENTS" . $comment[$i] . "<br/>"; } } else { echo '<p style="color: Red">No Comments POSTED!</p>'; } // loop 3 combines the answers and comments for($x = 0; $x < count($comment); $x++){ if(isset($question[$x])){ $question[$x] = $question[$x] . ' ' . $comment[$x]; } } $result = $question; // saves the answers and comments as a string ($result) Each comment[$i] is the same key and $question[$i]. Inserting into the table i have: $query = "INSERT INTO audit_data (Q4101, Q4102, Q4103, Q4104, etc...) VALUES '$result[0]','$result[1]','$result[2]','$result[3]','$result[4]', etc...)"; mysqli_query($link, $query) or die(mysqli_error($link)." Q=".$query); 1) is this the best way to go about this? 2) It is nearly working, i can get the $question and $comment into the first columns for instance: $result[0] to result[10] but if i try to insert further on in the table say $result[40] to $result[50] i only get the $question values and no $comment values. I have looked at array_map and preg_match on the manual but not sure how or which one to use. I don't want the table normalized and i am aware of injection problems.
  9. Hello, I´m trying to insert data from a form into a mysql table using mysqli and php. I use the code below to connect to the database: $host = "myhost"; $db = "a5066994_tutors"; $user = "a5066994_tutors"; $pass = "mypassword"; $connection = mysqli_connect("$host", "$user", "$pass", "$db"); if ($connection->errno) { printf("Connect failed: %s\n", $connection->error); exit(); and the code below to insert: $stmt = $connection->prepare("INSERT INTO tutorials (Author, Website, Title, Body1, Body2, Body3, Body4, Subtitle1, Subtitle2, Subtitle3, Subtitle4, Category, WTitle, Userid) VALUES ('$author','$website', '$title', '$text1', '$text2', '$text3', '$text4', '$s1', '$s2', '$s3', '$s4', '$cat', '$wtitle', '$userid') "); And it results in this error: Call to a member function execute() on a non-object I have also tried doing a var dump of the connection, which results in: object(mysqli)#1 (0) { } and a var dump of the statement, which results in: bool(false) Any help would be great, thank you!
  10. Having trouble submitting a dynamically generated form. I am getting no errors on submit, and nothing written to my table, just an indicator that I have landed on my "submit.php". The form is generated by checkboxes with action="../auditsys/submit.php" the checkbox form is echoed in php with variables as the values ie. $iso40 is the first form etc. which is reflected in the issets below. All the columns in "audit_data" table correspond to the $_POST values and subsequently to the input field "name " attribute. I can show the html form if requested, i haven't because it's long and embarrassingly messy at the moment. submit.php:<?php ini_set('display_errors',1); error_reporting(E_ALL); echo "landing at form indicator <br>"; $host = "localhost"; $username = "XXX"; $password = "XXX!"; $database = "XXX"; $link = mysqli_connect("$host", "$username", "$password", "$database"); if ($_SERVER['REQUEST_METHOD'] == 'POST') { if(isset($value, $iso40, $iso42, $iso50, $iso54, $iso55, $iso56, $iso60, $iso70, $iso73, $iso74, $iso75, $iso76, $iso80, $iso84, $iso85)) { $query = "INSERT INTO audit_data VALUES ('','{$_POST[auditor]}','{$_POST[auditee]}','{$_POST[datum]}','{$_POST[department]}','{$_POST[func]}','{$_POST[proc]}','{$_POST[audit_type]}', '{$_POST[copy_to]}','{$_POST[comments]}','{$_POST[Q4101]}','{$_POST[Q4102]}','{$_POST[Q4103]}','{$_POST[Q4104]}','{$_POST[Q4105]}','{$_POST[Q4106]}', '{$_POST[Q4107]}','{$_POST[Q4108]}','{$_POST[Q4109]}','{$_POST[Q4110]}','{$_POST[Q4211]}','{$_POST[Q4212]}','{$_POST[Q4213]}','{$_POST[Q4214]}', '{$_POST[Q4221]}','{$_POST[Q4222]}','{$_POST[Q4223]}','{$_POST[Q4231]}','{$_POST[Q4232]}','{$_POST[Q4233]}','{$_POST[Q4234]}','{$_POST[Q4235]}', '{$_POST[Q4236]}','{$_POST[Q4237]}','{$_POST[Q4238]}','{$_POST[Q4239]}','{$_POST[Q4241]}','{$_POST[Q4242]}','{$_POST[Q4243]}','{$_POST[Q4244]}', '{$_POST[Q4245]}','{$_POST[Q4246]}','{$_POST[Q4247]}','{$_POST[Q4248]}','{$_POST[Q5101]}','{$_POST[Q5102]}','{$_POST[Q5103]}','{$_POST[Q5104]}', '{$_POST[Q5105]}','{$_POST[Q5201]}','{$_POST[Q5301]}','{$_POST[Q5302]}','{$_POST[Q5303]}','{$_POST[Q5304]}','{$_POST[Q5411]}','{$_POST[Q5312]}', '{$_POST[Q5313]}','{$_POST[Q5421]}','{$_POST[Q5422]}','{$_POST[Q5423]}','{$_POST[Q5511]}','{$_POST[Q5521]}','{$_POST[Q5522]}','{$_POST[Q5523]}', '{$_POST[Q5531]}','{$_POST[Q5532]}','{$_POST[Q5611]}','{$_POST[Q5612]}','{$_POST[Q5613]}','{$_POST[Q5621]}','{$_POST[Q5622]}','{$_POST[Q5623]}', '{$_POST[Q5624]}','{$_POST[Q5625]}','{$_POST[Q5626]}','{$_POST[Q5627]}','{$_POST[Q5631]}','{$_POST[Q5632]}','{$_POST[Q5633]}','{$_POST[Q6101]}', '{$_POST[Q6102]}','{$_POST[Q6211]}','{$_POST[Q6221]}','{$_POST[Q6222]}','{$_POST[Q6223]}','{$_POST[Q6224]}','{$_POST[Q6225]}','{$_POST[Q6301]}', '{$_POST[Q6302]}','{$_POST[Q6303]}','{$_POST[Q6401]}','{$_POST[Q7101]}','{$_POST[Q7102]}','{$_POST[Q7103]}','{$_POST[Q7104]}','{$_POST[Q7105]}', '{$_POST[Q7106]}','{$_POST[Q7201]}','{$_POST[Q7202]}','{$_POST[Q7203]}','{$_POST[Q7204]}','{$_POST[Q7221]}','{$_POST[Q7222]}','{$_POST[Q7223]}', '{$_POST[Q7224]}','{$_POST[Q7225]}','{$_POST[Q7226]}','{$_POST[Q7231]}','{$_POST[Q7232]}','{$_POST[Q7233]}','{$_POST[Q7311]}','{$_POST[Q7312]}', '{$_POST[Q7313]}','{$_POST[Q7314]}','{$_POST[Q7315]}','{$_POST[Q7316]}','{$_POST[Q7321]}','{$_POST[Q7322]}','{$_POST[Q7323]}','{$_POST[Q7324]}', '{$_POST[Q7325]}','{$_POST[Q7326]}','{$_POST[Q7327]}','{$_POST[Q7331]}','{$_POST[Q7332]}','{$_POST[Q7333]}','{$_POST[Q7334]}','{$_POST[Q7335]}', '{$_POST[Q7336]}','{$_POST[Q7341]}','{$_POST[Q7342]}','{$_POST[Q7343]}','{$_POST[Q7344]}','{$_POST[Q7345]}','{$_POST[Q7351]}','{$_POST[Q7352]}', '{$_POST[Q7361]}','{$_POST[Q7362]}','{$_POST[Q7363]}','{$_POST[Q7364]}','{$_POST[Q7371]}','{$_POST[Q7372]}','{$_POST[Q7373]}','{$_POST[Q7374]}', '{$_POST[Q7411]}','{$_POST[Q7412]}','{$_POST[Q7413]}','{$_POST[Q7415]}','{$_POST[Q7421]}','{$_POST[Q7422]}','{$_POST[Q7423]}','{$_POST[Q7424]}', '{$_POST[Q7431]}','{$_POST[Q7432]}','{$_POST[Q7511]}','{$_POST[Q7512]}','{$_POST[Q7513]}','{$_POST[Q7514]}','{$_POST[Q7515]}','{$_POST[Q7516]}', '{$_POST[Q7521]}','{$_POST[Q7522]}','{$_POST[Q7523]}','{$_POST[Q7524]}','{$_POST[Q7525]}','{$_POST[Q7526]}','{$_POST[Q7527]}','{$_POST[Q7531]}', '{$_POST[Q7532]}','{$_POST[Q7533]}','{$_POST[Q7534]}','{$_POST[Q7541]}','{$_POST[Q7542]}','{$_POST[Q7543]}','{$_POST[Q7551]}','{$_POST[Q7552]}', '{$_POST[Q7553]}','{$_POST[Q7554]}','{$_POST[Q7555]}','{$_POST[Q7556]}','{$_POST[Q7557]}','{$_POST[Q7601]}','{$_POST[Q7602]}','{$_POST[Q7603]}', '{$_POST[Q7604]}','{$_POST[Q7605]}','{$_POST[Q7606]}','{$_POST[Q7607]}','{$_POST[Q7608]}','{$_POST[Q7609]}','{$_POST[Q7610]}','{$_POST[Q7611]}', '{$_POST[Q811]}','{$_POST[Q812]}','{$_POST[Q813]}','{$_POST[Q814]}','{$_POST[Q8211]}','{$_POST[Q8211]}','{$_POST[Q8211]}','{$_POST[Q8212]}', '{$_POST[Q8221]}','{$_POST[Q8222]}','{$_POST[Q8223]}','{$_POST[Q8224]}','{$_POST[Q8225]}','{$_POST[Q8226]}','{$_POST[Q8227]}','{$_POST[Q8228]}', '{$_POST[Q8229]}','{$_POST[Q8231]}','{$_POST[Q8232]}','{$_POST[Q8233]}','{$_POST[Q8241]}','{$_POST[Q8242]}','{$_POST[Q8243]}','{$_POST[Q8244]}', '{$_POST[Q8245]}','{$_POST[Q8401]}','{$_POST[Q8402]}','{$_POST[Q8403]}','{$_POST[Q8404]}','{$_POST[Q8405]}','{$_POST[Q8406]}','{$_POST[Q8511]}', '{$_POST[Q8512]}','{$_POST[Q8521]}','{$_POST[Q8522]}','{$_POST[Q8523]}','{$_POST[Q8524]}','{$_POST[Q8525]}','{$_POST[Q8526]}','{$_POST[Q8527]}', '{$_POST[Q8528]}','{$_POST[Q8531]}','{$_POST[Q8532]}','{$_POST[Q8533]}','{$_POST[Q8534]}','{$_POST[Q8535]}','{$_POST[Q8536]}','{$_POST[Q8537]}')"; echo $query; mysqli_query($link, $query) or die(mysqli_error($link)." Q=".$query); print_r($_POST); // ============ END ============== // } // if POST > END mysqli_close($link); } ?> I have checked and changed and checked my syntax but to no avail. Im using textpattern CMS if it's any use. I used the below to try and get an error code. Refs: PHP: Simple form to posts to database
  11. Hi php friends, I'll be very thankful to hear your opinion my php problem: I have a php website with mysql database with 1 table with about 20,000 rows. My code looks like this: $mysqli = new mysqli($mysql_hostname, $mysql_user, $mysql_password, $mysql_database); if ($mysqli->connect_errno) { exit(); } if ($stmt = $mysqli->prepare('SELECT title, description, content FROM '.$tableName.' WHERE slug=?')) { $stmt->bind_param("s", $slug); $stmt->execute(); $stmt->bind_result($title, $description, $content); $stmt->fetch(); $stmt->close(); } $mysqli->close(); ... /* just visualize the read variable above */ <h1><?php echo $title; ?></h1> <?php echo $content; ?> The problem is that in the hosting statistic, there's really huge php CPU usage, i.e. for yesterday the statistic is: PHP CPU usage is 144 min. MySQL CPU usage is 2 min. I try to find the problem for more than a week, I'll be very, very thankful for your help Thanks in advance for any reply!
  12. Hi All; I am trying to get some extensions to load in php 5.3.23. This was installed over 5.2.3 because 5.3 does not have an php5apache2_2.dll file. When I do a phpinfo mysql and mysqli do not show up. I have check the error logs and have seen the following, My OS is Win 7 64 bit. [22-Mar-2013 12:06:07] PHP Warning: PHP Startup: mysql: Unable to initialize module Module compiled with module API=20090626, debug=0, thread-safety=0 PHP compiled with module API=20060613, debug=0, thread-safety=1 These options need to match in Unknown on line 0 [22-Mar-2013 12:06:07] PHP Warning: PHP Startup: mysqli: Unable to initialize module Module compiled with module API=20090626, debug=0, thread-safety=0 PHP compiled with module API=20060613, debug=0, thread-safety=1 These options need to match in Unknown on line 0 Then in apache error.log file I noticed this: PHP Warning: PHP Startup: Unable to load dynamic library 'C:\\PHP523\\ext\\php_mcrypt.dll' - The specified module could not be found.\r\n in Unknown on line 0 PHP Warning: PHP Startup: Unable to load dynamic library 'C:\\PHP523\\ext\\php_mhash.dll' - The specified module could not be found.\r\n in Unknown on line 0 PHP Warning: PHP Startup: Unable to load dynamic library 'C:\\PHP523\\ext\\php_mysql.dll' - The specified module could not be found.\r\n in Unknown on line 0 PHP Warning: PHP Startup: Unable to load dynamic library 'C:\\PHP523\\ext\\php_mysqli.dll' - The specified module could not be found.\r\n in Unknown on line 0 PHP Warning: PHP Startup: Unable to load dynamic library 'C:\\PHP523\\ext\\php_pdo_mysql.dll' - The specified module could not be found.\r\n in Unknown on line 0 To me it looks like the double slashes might be the problem, but I don't know where to go to get rid of them, so am I on the right track, or is there something else wrong?
  13. I have the following code the lookup data from a database. It runs okay on my llocal machine but it give me "Fatal error: Allowed memory size of 33554432 bytes exhausted" whenit runs on hosting server. It indicates fatal error at line of $r[field3]); I googled the error and found the response for similar situation is to re-code to prevent memory leak. Can anyone point out how the following can be improve to prevent the error from happening. Thanks a lot. $stmt = $database_connection->stmt_init(); if ($stmt->prepare("SELECT keyA, field1, field2, field3 FROM tableA JOIN tableB ON tableA.field1 = tableB.keyB JOIN tableC ON tableA.field2 = tableC.keyC WHERE field3 LIKE ?")) { $stmt->bind_param('s', $likeString); $stmt->bind_result($r['keyA'], $r['field1'], $r['field2'], $r['field3']); if (!$stmt->execute()) { echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error; exit(); } while($stmt->fetch()){ foreach( $r as $key=>$value ) { $row_tmb[ $key ] = $value; } $r[] = $row_tmb; } return $r;
  14. Hi all. I'm pretty new to PHP and am trying to write a simple CMS using procedual PHP and MySQLi. Thought I'd build a CMS just to get a basic understanding of how things work. I know this would be better done with OOPHP and using PDO for databases interaction, however would appreciate any advice on how what I've done could be improved. The main areas I'm unsure on is..... Am I using mysqli_real_escape_string(); ok? When updating and deleteing users, is using the GET method ok as it seems a little unsafe when deleting users? Is the sanitization ok? Could I be making more use of functions, say for the session? If so how would you advise. Anything else that need improving? register.php - this is where I'm unsure on sanitization. Functions page is below this block of code. <?php require ('db-connection.php'); require ( 'functions.php' ); $pageTitle = 'Register'; if ( isset( $_POST['submitForm'] ) ) { $errors = array(); // puts errors into array if ( empty( $_POST['name']) ) { $errors['name'] = 'Please enter a name'; } else { $name = sanitize( $_POST['name'] ); $name = mysqli_real_escape_string( $dbc, $name ); } if ( empty ( $_POST['email'] ) ) { $errors['email'] = 'Please enter an email address'; } else { $email = sanitize( $_POST['email'] ); $email = mysqli_real_escape_string( $dbc, $email ); } if ( empty( $_POST['username']) ) { $errors['username'] = 'Please enter a username'; } else { $username = sanitize( $_POST['username'] ); $username = mysqli_real_escape_string( $dbc, $username ); } if ( empty( $_POST['password'] ) ) { $errors['password'] = 'Please enter a password'; } elseif ( $_POST['password'] !== $_POST['confirm_password'] ) { $errors['password'] = 'Passwords do not match'; } else { $salt = generateSalt( $_POST['username'] ); $password = generateHash( $salt, $_POST['password'] ); } $telephone = sanitize( $_POST['telephone'] ); $telephone = mysqli_real_escape_string( $dbc, $telephone ); $postcode = sanitize( $_POST['postcode'] ); $postcode = mysqli_real_escape_string( $dbc, $postcode ); if ( empty( $errors ) ) { $db_insert = "INSERT INTO users VALUES ( NULL, '$name', '$email', '$username', '$password', '$telephone', '$postcode' )"; mysqli_query( $dbc, $db_insert ); // performs query on db header( 'Location: login.php' ); } } require( 'header.php' ); ?> <h1>Register</h1> <form action="register.php" method="post" class="form-horizontal"> <?php if ( !empty ( $errors ) ) : ?> <div class="alert alert-error"> <button type="button" class="close" data-dismiss="alert">×</button> <p> <?php foreach ( $errors as $msg ) { echo $msg .'<br />'; } ?> </p> </div> <?php elseif ( empty( $errors ) && isset( $_POST['submitForm'] ) ) : ?> <p>Thank you for completing the form.</p> <?php endif; ?> <div class="control-group"> <label class="control-label" for="name">Name *</label> <div class="controls"> <input type="text" id="name" name="name" placeholder="Email" value="<?php echo isset($_POST['name']) ? $_POST['name'] : ""; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="email">Email *</label> <div class="controls"> <input type="text" id="email" name="email" placeholder="Email" value="<?php echo isset($_POST['email']) ? $_POST['email'] : ""; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="username">Username *</label> <div class="controls"> <input type="text" id="username" name="username" placeholder="Username" value="<?php echo isset($_POST['username']) ? $_POST['username'] : ""; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="username">Password *</label> <div class="controls"> <input type="password" id="password" name="password" placeholder="Password" value="<?php echo isset($_POST['password']) ? $_POST['password'] : ""; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="confirm_password">Confirm Password *</label> <div class="controls"> <input type="password" id="cofirm_password" name="confirm_password" placeholder="Confirm Password" value="<?php echo isset($_POST['confirm_password']) ? $_POST['confirm_password'] : ""; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="telephone">Telephone</label> <div class="controls"> <input type="text" id="telephone" name="telephone" placeholder="Telephone" value="<?php echo isset($_POST['telephone']) ? $_POST['telephone'] : ""; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="postcode">Postcode</label> <div class="controls"> <input type="text" id="postcode" name="postcode" placeholder="Postcode" value="<?php echo isset($_POST['postcode']) ? $_POST['postcode'] : ""; ?>"> </div> </div> <div class="control-group"> <div class="controls"> <button type="submit" class="btn btn-large btn-primary" name="submitForm">Register</button> </div> </div> </form> <?php require( 'footer.php' ); ?> functions.php <?php function generateSalt( $username ) { $salt = '$2a$10$'; $salt = $salt . md5(strtolower( $username )); return $salt; } function generateHash( $salt, $password ) { $hash = crypt( $password, $salt ); $hash = substr($hash, 29); return $hash; } function sanitize( $input ) { return htmlspecialchars(trim( $input )); } view-users.php - when displaying data from the database, do I need to run it through mysqli_real_escape_string(); before outputting to the user? How would that be done, just on the $result variable? Also with the delete user, I'm using the GET method, is this ok? This is opening the page which I've put the code below this block. <?php session_start(); if ( !isset( $_SESSION['username'] ) ) { header ( 'Location: login.php' ); } else { // set time-out period (in seconds) $inactive = 300; if (isset($_SESSION["timeout"])) { // calculate the session's "time to live" $sessionTTL = time() - $_SESSION["timeout"]; if ($sessionTTL > $inactive) { session_destroy(); header( 'Location: logout.php' ); } } $_SESSION["timeout"] = time(); } require( 'db-connection.php' ); require( 'functions.php' ); // $query = "SELECT * FROM users"; $query = "SELECT id, name, email, username, telephone, postcode FROM users"; $result = mysqli_query( $dbc, $query ); require( 'header.php' ); ?> <p><a href="logout.php">Logout</a></p> <table class="table table-striped"> <tr> <th>ID</th> <th>Name</th> <th>Email</th> <th>Username</th> <th>Telephone</th> <th>Postcode</th> <th>Edit User</th> </tr> <?php while ( $row = mysqli_fetch_array( $result, MYSQLI_ASSOC ) ) : ?> <?php $username = $row['username']; ?> <tr> <td><?php echo $row['id']; ?></td> <td><?php echo $row['name']; ?></td> <td><?php echo $row['email']; ?></td> <td><?php echo $row['username']; ?></td> <td><?php echo $row['telephone']; ?></td> <td><?php echo $row['postcode']; ?></td>> <td> <div class="btn-group"> <a class="btn" href="edit-user.php?username=<?php echo $username; ?>"><i class="icon icon-edit"></i></a> <a class="btn" href="delete-user.php?username=<?php echo $username; ?>"><i class="icon icon-trash"></i></a> </div> </td> </tr> <?php endwhile; ?> </table> <p><?php printf("Select returned %d rows.\n", mysqli_num_rows($result)); ?></p> <?php require( 'footer.php' ); ?> delete-user.php <?php session_start(); if ( !isset( $_SESSION['username'] ) ) { header ( 'Location: login.php' ); } require( 'db-connection.php' ); require( 'functions.php' ); if ( isset( $_GET['username'] ) ) { $username = $_GET['username']; $query = "DELETE FROM users WHERE username = '$username'"; $result = mysqli_query( $dbc, $query ); header( 'Location: view-users.php' ); } mysql_close( $dbc ); Thanks in advance.
  15. How does one go about converting an SQL query such as: SELECT * FROM members WHERE userid='$userid' AND code=$code' into a prepared statement for PHP. I understand how to use prepared statements however I'm having trouble with the * part of the query and I'd rather not have to write out all the table coulmns because I have about 20. EDIT: I'm using mysqli procedural
  16. HI, I am building a PHP and Mysqli based shopping cart for my UNI project. I have been using prepared statements for everything so far and they work great. However I have hit my first problem. I cannot seem to insert data into the database using a prepared statement. I have written a function that first checks to see if a product already exists. this works well and if that product does not exist it should run the prepared stmt and insert the data. However it is skipping over the insert part and going straight to the 'else' section of the 'if' stating that a product could not be uploaded. Here is the function that is not working. As before the first part works well, just have a problem when it actually comes to add the product. function addProduct($productName, $productPrice, $productCategory, $productShortDesc, $productLongDesc, $productShipping, $productQTY) { //Check if item already exists $qry = "Select id FROM products WHERE name = ? LIMIT 1"; if ($stmt = $this->conn->prepare($qry)) { $stmt->bind_param('s', $productName); $stmt->execute(); $stmt->bind_result($p_id); if($stmt->fetch()) { echo "Sorry. That product already exists."; exit(); } else { $qry2 = ("INSERT INTO products (name, short_desc, long_desc, category, price, shipping, qty) VALUES('$productName', '$productShortDesc', '$productLongDesc', '$productCategory', '$productPrice','$productShipping', '$productQTY'"); if ($stmt = $this->conn->prepare($qry2)) { //Add item to DB $stmt->execute(); $stmt->insert_id; //Place image in folder $newname = "$pid.jpg"; move_uploaded_file($FILES['fileField']['tmp_name'], "../product_images/$newname"); } else { echo "Error adding new product, Please check all details and try again."; } } } } Regards Chris
  17. I have the following to update database but somehow it is doing so. Anyone has an idea? I added break point inside this function to check the parms passed in and they are correct. function edit_book($book_id, $book_title) { $conn = mysqli_connect('localhost', 'user', 'pwd', 'db') or die('Could Not Connect' . mysql_error()); $book_id = (int)$book_id; $book_title = $conn->real_escape_string($book_title); $stmt = $conn->stmt_init(); //***************** Break point - examine the value of book_id and book_title if ($stmt->prepare("UPDATE book SET book_title=? WHERE book_id=?")) { $stmt->bind_param('si', $parm_book_id, $parm_book_title); $parm_book_id = $book_id; $parm_book_title = $book_title; $stmt->execute(); $stmt->close(); } mysqli_close($conn); }
  18. I have problem to fetch data into an array. The following code was original written in mysql and I need to convert it to use mysqli. Question 1: Do I need to have $stmt->bind_result ? Question 2: How do I convert from mysqli_fetch_assoc to mysqli_ ? Thanks for any help. if ($func_num_args > 1) { unset($func_get_args[0]); $fields = implode (', ', $func_get_args) ; $stmt = $database_connection->stmt_init(); if ($stmt->prepare("SELECT $fields FROM category WHERE book_id=?")) { $stmt->bind_param('i', $parm_book_id); $parm_book_idt = $book_id; $stmt->execute(); } // the following needs to be changed to use mysqli $data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM user WHERE id_user = $id_user")); return $data; }
  19. my code doesnt seem to work.. the radio buttons appear but nothing beside them .. what i know already: mysql_fetch_row is working - i have tested this using mysqli_num_rows() mysqli_query is working - testing in phpmyadmin and also proven above the problem seems to be with $a ..... $e .. i have tried to echo these variables outside teh form but they dont work. i have also tried to echo them directly ie. $retrieve['question']; and this doesnt work either. could someone please advise what is wrong? cheers ps. i am new at this. this is my code. <?php include 'dbyear2.php'; $qnumber = ($_REQUEST['uqn']); // obtain question number from URL $find = mysqli_query($condbyear2, "SELECT * FROM Renal WHERE UQN='$qnumber'"); while($retrieve=mysqli_fetch_row($find)); { $question = $retrieve['question']; $a = $retrieve['MCQ_A']; $b = $retrieve['MCQ_B']; $c = $retrieve['MCQ_C']; $d = $retrieve['MCQ_D']; $e = $retrieve['MCQ_E']; $answer = $retrieve['answer']; $correct = $retrieve['MCQ_correct']; } ?> <form action='check.php' method='POST'> <table> <tr><td></td><td></td></tr> <tr></tr> <tr><td><input type='radio' name='group1' value='A' /></td><td> <?php echo $a; ?></td></tr> <tr><td><input type='radio' name='group1' value='B' /></td><td> <?php echo $b; ?></td></tr> <tr><td><input type='radio' name='group1' value='C' /></td><td> <?php echo $c; ?></td></tr> <tr><td><input type='radio' name='group1' value='D' /></td><td> <?php echo $d; ?></td></tr> <tr><td><input type='radio' name='group1' value='E' /></td><td> <?php echo $e; ?></td></tr> <tr> <?php // sending the retrieved information from MYSQL via POST for use in check.php file $qnumber; $a; $b; $c; $d; $e; $answer; $correct; ?></tr> <tr><td><input type="submit" value="Submit"></td></tr> </table> </form>
  20. Hi all, I have a most strange problem, and I am not sure if it is because of a long overdue move to mysqli from mysql or something else that is ludicrously simply wrong with what I am doing. I am doing a select on name from users where the userid = the sessions userid. From there I want to set the $personsname variable from the name column - simple. The query below runs fine without error and I can print out the name, but what I cannot do is set the variable up: $query1 = "SELECT name FROM `users` WHERE `userid`=$userid"; $result = $mysqli->query($query1) or die($mysqli->error.__LINE__); // GOING THROUGH THE DATA if($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo stripslashes($row['name']); $personsname=stripslashes ($row['$name']); = FRED BLOGS - correct echo "<p>name=$personsname</p>"; = EMPTY?!?!?!?! I am sure the answer is embarrassingly simple, but I just cant get my head around this.. Thanks, G
  21. Hello, I want to switch from mysql to mysqli. but i have some questions. Are there an advantage to use object oriented style:$mysqli=new mysqli(...) or procedural style : $link=mysqli_connect(.....) ? My actual website, use mysql and all are procedural style : mysql_connect, mysql_query, mysql_num_rows.......... after doing a query, i close the connection mysql_close($link)... and reopen it if i have another query, such as in a function or further in the same script.... so it means that i can open and close the connection a lot in a same script...... I read that i can create an object like ::$mysqli=new mysqli(...) and nerver close it, and if i call a function, i just send $mysqli to the function: callThisFunction($mysqli) and the connection will be automaticly close when the script finish Is that better to open,close,open,close........ and so??? or open once and never close it I want to use the best way for the persomance of entire website! Thanks for your help!!
  22. My question is in the title, does anyone know any good tutorials to upload images to the server and send the path to the database. I did post a question about a piece of my code where you can upload images to the server but it wasn't associated with the database. I would love to hear back about this.
  23. I have been working on an application for a university project and I have somehow managed to break my code and I have no idea what I have done to break it. I have created a registration and log in script which used to work but I can no longer login with the registered details. I could really use some help on this so I don't spend hours ripping my hair out. I have attached an image of my user database. Code for registration <?php include 'PasswordHash.php'; $sql = new mysqli('localhost', '****', '****', '****'); // Create an array to catch any errors in the registration form. $errors = array(); /** * Make sure the form has been submitted before trying to process it. This is * single most common cause of 'undefined index' notices. */ if (!empty($_POST)) { // First check that required fields have been filled in. if (empty($_POST['username'])) { $errors['username'] = "Username cannot be empty."; } // Restrict usernames to alphanumeric plus space, dot, dash, and underscore. /* if (preg_match('/[^a-zA-Z0-9 .-_]/', $_POST['username'])) { $errors['username'] = "Username contains illegal characters."; } */ if (empty($_POST['firstname'])) { $errors['firstname'] = "First Name cannot be empty."; } if (empty($_POST['surname'])) { $errors['surname'] = "Surname cannot be empty."; } if (empty($_POST['password'])) { $errors['password'] = "Password cannot be empty."; } if (strlen($_POST['password']) < { $errors['password'] = "Password must be at least 8 charcaters."; } // Force passwords to contain at least one number and one special character. /* if (!preg_match('/[0-9]/', $_POST['password'])) { $errors['password'] = "Password must contain at least one number."; } if (!preg_match('/[\W]/', $_POST['password'])) { $errors['password'] = "Password must contain at least one special character."; } */ if (empty($_POST['password_confirm'])) { $errors['password_confirm'] = "Please confirm password."; } if ($_POST['password'] != $_POST['password_confirm']) { $errors['password'] = "Passwords do not match."; } $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL); if (!$email) { $errors['email'] = "Not a valid email address."; } /** * Escape the data we're going to use in our query. Never trust user input. */ $username = $sql->real_escape_string($_POST['username']); $email = $sql->real_escape_string($email); $firstname = $sql->real_escape_string($_POST['firstname']); $surname = $sql->real_escape_string($_POST['surname']); $addressline1 = $sql->real_escape_string($_POST['addressline1']); $addressline2 = $sql->real_escape_string($_POST['addressline2']); $city = $sql->real_escape_string($_POST['city']); $county = $sql->real_escape_string($_POST['county']); $postcode = $sql->real_escape_string($_POST['postcode']); /** * Check that the username and email aren't already in our database. * * Note also the absence of SELECT * */ $query = "SELECT username, email FROM users WHERE username = '{$username}' OR email = '{$email}'"; $result = $sql->query($query); /** * There may well be more than one point of failure, but all we really need * is the first one. */ $existing = $result->fetch_object(); if ($existing) { if ($existing->username == $_POST['username']) { $errors['username'] = "That username is already in use."; } if ($existing->email == $email) { $errors['email'] = "That email address is already in use."; } } } if (!empty($_POST) && empty($errors)) { /** * Hash password before storing in database */ $hasher = new PasswordHash(8, FALSE); $password = $hasher->HashPassword($_POST['password']); $query = "INSERT INTO users (firstname, surname, username, email, password, addressline1, addressline2, city, county, postcode, created) VALUES ('{$firstname}','{$surname}','{$username}','{$email}', '{$password}','{$addressline1}','{$addressline2}','{$city}','{$county}','{$postcode}', NOW())"; $success = $sql->query($query); if ($success) { $message = "Account created."; } else { $errors['registration'] = "Account could not be created. Please try again later."; } } ?> Login Code <?php session_start(); // If the user is already logged in then redirect them to homepage if (isset($_SESSION['user_id'])) { exit(); } include 'PasswordHash.php'; $sql = new mysqli('localhost', '****', '****', '****'); $hasher = new PasswordHash(8, FALSE); if (!empty($_POST)) { // Again, never trust user input! $user = $sql->real_escape_string($_POST['username']); $query = "SELECT id, password, username, UNIX_TIMESTAMP(created) AS salt FROM users WHERE username = '{$username}'"; $user = $sql->query($query)->fetch_object(); /** * Check that the query returned a result (otherwise user doesn't exist) * and that provided password is correct. */ if ($user && $user->password == $hasher->CheckPassword($_POST['password'], $user->password)) { /** * Set cookies here if/as needed. * Set session data as needed. DO NOT store user's password in * cookies or sessions! * Redirect the user if/as required. */ session_regenerate_id(); $_SESSION['user_id'] = $user->id; $_SESSION['username'] = $user->username; $_SESSION['authenticated'] = TRUE; $_SESSION['signature'] = md5($user->id . $_SERVER['HTTP_USER_AGENT'] . $user->salt); header('Location:../login.php'); } /** * Don't provide specific details as to whether username or password was * incorrect. If an attacker knows they've found a valid username, you've * just made their life easier. */ else { $error = "Login failed."; } } ?> Thank you in advance and I'm sorry for the amount of code. Some of the code I used was from tutorials, as I am new to php.
  24. I am still really new to php so I am sorry if I don't make much sense but what I want to be able to achieve is to retrieve images from a file directory that will be referenced in the database. Here is my code for submitting the images <?php $allowedExts = array("jpg", "jpeg", "gif", "png"); $extension = end(explode(".", $_FILES["file"]["name"])); if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000) && in_array($extension, $allowedExts)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br>"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br>"; echo "Type: " . $_FILES["file"]["type"] . "<br>"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?> Here is my sql for the created table CREATE TABLE `recipes` ( `recipeid` INT(11) UNSIGNED ZEROFILL PRIMARY KEY AUTO_INCREMENT, `recipename` VARCHAR(50) NOT NULL, `ingredients` VARCHAR(50) NOT NULL, `instructions` VARCHAR(50) NOT NULL, `imagename` VARCHAR(50) NOT NULL, `created` DATETIME NOT NULL ) Thank you in advance.
  25. I'm using PHP 5.3.13. I am just using a very simple query to grab one column of results from a table. I would like to fetch them and then iteratively add them to a dropdown menu. I am trying to understand these methods/functions and seem to be missing something. My research on Google didn't give me any indication of what I'm doing wrong. I start with one of the simplest queries possible, which I know will return a data set as I have tested it in mysqladmin. The problem arises when I try to call the method on the mysqli_result object. $query = "SELECT `artist` FROM `bands`;"; $result = $mysqli->query($query); $bandArr = $result->fetch_all(); The error I'm getting from the above code is: Fatal error: "Call to undefined method mysqli_result::fetch_all()..." I researched this error and read somewhere that you need mysqlnd. Is that true? Do I need to look into my PHP configuration to get this to work? Is it worth it for this task? Then I tried fetch_array... $query = "SELECT `artist` FROM `bands`;"; $result = $mysqli->query($query); $bandArr = $result->fetch_array(MYSQLI_NUM); printf("%s\n%s", $bandArr[0], $bandArr[1]); And the above code for some reason returns an array with only one item, and this error: "Notice: Undefined offset: 1 in..." What am I missing here? Again, all I want is a small result set from one column which can be iterated and each value added to a drop down menu. Thoughts? Suggestions? Thanks in advance for any help you can offer...
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.