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. can someone assistance me with converting this code over to mysqli. I know that mysqli requires 2 parameters instead of one... i tried $user = mysqli_real_escape_string($g_link, $en['user']); but no connection was passed. $user = mysql_real_escape_string($en['user']); $pass = mysql_real_escape_string($en['pass']); $sql = "SELECT m_id, m_user, m_pass, m_email, m_del FROM $membtable WHERE m_user='".$user."' AND m_pass='".$pass."' AND m_del!=1"; $result = mysql_query($sql); $line = mysql_fetch_assoc($result); Db Connection $g_link = false; function GetDbConn() { global $g_link; if( $g_link ) return $g_link; $g_link = mysqli_connect($db_server, $db_user, $db_pass) or die("Error " . mysqli_error($g_link)); mysqli_select_db($g_link, 'cialdb') or die('Could not select database.'); return $g_link; }
  2. Hello I'm trying to check if 2 values exist in the database using php, Google didn't help... I need something like this : if($stmt = mysqli_prepare($db_connect,'QUERY TO CHECK IF USERNAME AND EMAIL EXIST')){ mysqli_stmt_bind_param($stmt, "ss", $user,$email); mysqli_stmt_execute($stmt); /* if username exist echo username exist if email exist echo email exist */ } else{/*error*/} thanks !
  3. Im having trouble on my php script. it is working on my computer but when I put it in x10hosting it fails and gives an error 500. I tried tracing the problem and I found out that it happens if I call get_result. Here is the part code: $username = strtolower(filter_input(INPUT_POST, 'username')); $password = filter_input(INPUT_POST, "password"); $remember = filter_input(INPUT_POST, "remember"); $result = array(); include 'Connection.php'; $query = "SELECT Number, Username, Password, Alias, Level FROM user WHERE Username = ?;"; $stmt = $conn->prepare($query); if(!$stmt->prepare($query)) { die( "Failed to prepare statement."); } $stmt->bind_param("s", $username); $stmt->execute(); echo $stmt->error; //error hapens here $selectResult = $stmt->get_result();
  4. Hi, I am making a CMS and I can't get the search page to work right. The CMS is for a new local DJI store and I can't get anything to show up when I search for those who have paid for insurance on their drones. And when I enter a first or last name that multiple people have in common, like Mike or Smith, the info doesn't display correctly, The first customer is displayed correctly, but no one else is. searchcodefirst.php searchcodeinsurance.php searchcodelast.php
  5. I am trying to add a query to my script that updates a value in my database by subtracting "1". When I run the query, I get "Fatal error: Call to a member function free() on boolean in ../path/to/my/script" $sql = "UPDATE table_5 SET chairs = chairs - 1 WHERE chairs > 0 AND chair_model = 'model_33'"; Any idea what I'm doing wrong? Table 5: Chairs | Model Number | 22 | model_33 44 | model_44
  6. Hi all. I don't know why this is happening. I have a scrip that backs up database. It works fine on database1 but when i use it on database2, it throws an error? Fatal error: Call to a member function fetch_row() on a non-object in $tableshema = $shema->fetch_row() ; both databases are on same domain. ps: even with another backup script still throws an error in database2 thanks ##################### //CONFIGURATIONS ##################### // Define the name of the backup directory define('BACKUP_DIR', 'cashBackup' ) ; // Define Database Credentials define('HOST', 'localhost' ) ; define('USER', 'username' ) ; define('PASSWORD', 'password' ) ; define('DB_NAME', 'database2' ) ; /* Define the filename for the Archive If you plan to upload the file to Amazon's S3 service , use only lower-case letters . Watever follows the "&" character should be kept as is , it designates a timestamp , which will be used by the script . */ $archiveName = 'mysqlbackup--' . date('d-m-Y') . '@'.date('h.i.s').'&'.microtime(true) . '.sql' ; // Set execution time limit if(function_exists('max_execution_time')) { if( ini_get('max_execution_time') > 0 ) set_time_limit(0) ; } //END OF CONFIGURATIONS /* Create backupDir (if it's not yet created ) , with proper permissions . Create a ".htaccess" file to restrict web-access */ if (!file_exists(BACKUP_DIR)) mkdir(BACKUP_DIR , 0700) ; if (!is_writable(BACKUP_DIR)) chmod(BACKUP_DIR , 0700) ; // Create an ".htaccess" file , it will restrict direct access to the backup-directory . $content = 'deny from all' ; $file = new SplFileObject(BACKUP_DIR . '/.htaccess', "w") ; $written = $file->fwrite($content) ; // Verify that ".htaccess" is written , if not , die the script if($written <13) die("Could not create a \".htaccess\" file , Backup task canceled") ; // Check timestamp of the latest Archive . If older than 24Hour , Create a new Archive $lastArchive = getNameOfLastArchieve(BACKUP_DIR) ; $timestampOfLatestArchive = substr(ltrim((stristr($lastArchive , '&')) , '&') , 0 , - ; if (allowCreateNewArchive($timestampOfLatestArchive)) { // Create a new Archive createNewArchive($archiveName) ; } else { echo '<p>'.'Sorry the latest Backup is not older than 24Hours , try a few hours later' .'</p>' ; } ########################### // DEFINING THE FOUR FUNCTIONS // 1) createNewArchive : Creates an archive of a Mysql database // 2) getFileSizeUnit : gets an integer value and returns a proper Unit (Bytes , KB , MB) // 3) getNameOfLastArchieve : Scans the "BackupDir" and returns the name of last created Archive // 4) allowCreateNewArchive : Compares two timestamps (Yesterday , lastArchive) . Returns "TRUE" , If the latest Archive is onlder than 24Hours . ########################### // Function createNewArchive function createNewArchive($archiveName){ $mysqli = new mysqli(HOST , USER , PASSWORD , DB_NAME) ; if (mysqli_connect_errno()) { printf("Connect failed: %s", mysqli_connect_error()); exit(); } // Introduction information $return = "--\n"; $return .= "-- A Mysql Backup System \n"; $return .= "--\n"; $return .= '-- Export created: ' . date("Y/m/d") . ' on ' . date("h:i") . "\n\n\n"; $return .= "--\n"; $return .= "-- Database : " . DB_NAME . "\n"; $return .= "--\n"; $return .= "-- --------------------------------------------------\n"; $return .= "-- ---------------------------------------------------\n"; $return .= 'SET AUTOCOMMIT = 0 ;' ."\n" ; $return .= 'SET FOREIGN_KEY_CHECKS=0 ;' ."\n" ; $tables = array() ; // Exploring what tables this database has $result = $mysqli->query('SHOW TABLES' ) ; // Cycle through "$result" and put content into an array while ($row = $result->fetch_row()) { $tables[] = $row[0] ; } // Cycle through each table foreach($tables as $table) { // Get content of each table $result = $mysqli->query('SELECT * FROM '. $table) ; // Get number of fields (columns) of each table $num_fields = $mysqli->field_count ; // Add table information $return .= "--\n" ; $return .= '-- Tabel structure for table `' . $table . '`' . "\n" ; $return .= "--\n" ; $return.= 'DROP TABLE IF EXISTS `'.$table.'`;' . "\n" ; // Get the table-shema $shema = $mysqli->query('SHOW CREATE TABLE '.$table) ; // Extract table shema $tableshema = $shema->fetch_row() ; // Append table-shema into code $return.= $tableshema[1].";" . "\n\n" ; // Cycle through each table-row while($rowdata = $result->fetch_row()) { // Prepare code that will insert data into table $return .= 'INSERT INTO `'.$table .'` VALUES ( ' ; // Extract data of each row for($i=0; $i<$num_fields; $i++) { $return .= '"'.$rowdata[$i] . "\"," ; } // Let's remove the last comma $return = substr("$return", 0, -1) ; $return .= ");" ."\n" ; } $return .= "\n\n" ; } // Close the connection $mysqli->close() ; $return .= 'SET FOREIGN_KEY_CHECKS = 1 ; ' . "\n" ; $return .= 'COMMIT ; ' . "\n" ; $return .= 'SET AUTOCOMMIT = 1 ; ' . "\n" ; //$file = file_put_contents($archiveName , $return) ; $zip = new ZipArchive() ; $resOpen = $zip->open(BACKUP_DIR . '/' .$archiveName.".zip" , ZIPARCHIVE::CREATE) ; if( $resOpen ){ $zip->addFromString( $archiveName , "$return" ) ; } $zip->close() ; $fileSize = getFileSizeUnit(filesize(BACKUP_DIR . "/". $archiveName . '.zip')) ; $message = <<<msg <h4>BACKUP completed ,</h4> <p> The backup file has the name of : <strong> $archiveName </strong> and it's file-size is : $fileSize. </p> <p> This zip archive can't be accessed via a web browser , as it's stored into a protected directory.<br> It's highly recomended to transfer this backup to another filesystem , use your favorite FTP client to download the file . </p> msg; echo $message ; } // End of function creatNewArchive // Function to append proper Unit after a file-size . function getFileSizeUnit($file_size){ switch (true) { case ($file_size/1024 < 1) : return intval($file_size ) ." Bytes" ; break; case ($file_size/1024 >= 1 && $file_size/(1024*1024) < 1) : return round(($file_size/1024) , 2) ." KB" ; break; default: return round($file_size/(1024*1024) , 2) ." MB" ; } } // End of Function getFileSizeUnit // Funciton getNameOfLastArchieve function getNameOfLastArchieve($backupDir) { $allArchieves = array() ; $iterator = new DirectoryIterator($backupDir) ; foreach ($iterator as $fileInfo) { if (!$fileInfo->isDir() && $fileInfo->getExtension() === 'zip') { $allArchieves[] = $fileInfo->getFilename() ; } } return end($allArchieves) ; } // End of Function getNameOfLastArchieve // Function allowCreateNewArchive function allowCreateNewArchive($timestampOfLatestArchive , $timestamp = 24) { $yesterday = time() - $timestamp*3600 ; return ($yesterday >= $timestampOfLatestArchive) ? true : false ; } // End of Function allowCreateNewArchive
  7. Hi, Is that possible to connect to microsoft sql server by using mysqli? Currently i connected by using sqlsrv. For example, $serverName = "servername.com"; //serverName\instanceName $connectionInfo = array("Database" => "DB1", "UID" => "user99", "PWD" => "12345"); $conn = sqlsrv_connect($serverName, $connectionInfo); i have try quite some time to use mysqli to connect. But I keep getting errors.. Thank You
  8. I need urgent help! For two days I've been trying to find the source code to upload image to database and display, after trying all the codes I kept getting all sorts of errors. I'm using phpmyadmin. Fatal error: Call to undefined function finfo_open() in C:\xampp\htdocs\geology\file_insert.php on line 51 Second help needed is to display or restrict 3 latest posts only. I want to display only 3 latest posts sort by latest date posted. I'm not sure how to loop this through. Another thing is, when the user clicks on the title of a specific article, a new window will appear to display only the data that belong to it (Title, Publisher, Content...) For example, there are 3 articles (rock, mineral, salt) user clicks on Rocks, a new window appear showing all Rocks info. <?php $sql = "select * from article ORDER by article_postdate DESC"; $result = mysqli_query($conn, $sql); while($row = mysqli_fetch_assoc($result)) { ?> <h3><a href="#"><?php echo $row["article_title"]; ?></a></h3> <p class="byline"><span><?php echo $row["article_postdate"]; ?><br> Published By:<?php echo $row["author_id"]; ?></p></a></span></p> <p><?php echo $row["article_details"]; ?></p> <td><a href = "edit.php?article_id=<?php echo $row['article_id']; ?>">More...</a></td> <?php } ?>
  9. I am building a site that requires users to register and login to view and use certain parts of the site. When a user registers, an email is sent to them with a link that they need to click to activate their account. The link in the email contains the users email and an activation code and takes them to a page named 'activate' and checks the following conditions... If the email in the url exists in the database (This works) If the activation code in the url exists in the database (This works) If both of the previous conditions are true and the account active state is N then UPDATE `active` in database to Y thus allowing the user to login. (This works but not correctly) What I want to happen is... User registers > User gets email > *** (Anything before this point users cannot login. They will get a message telling them that their account has not been activated) *** > User clicks link > Users account is activated (`active` is changed from N to Y) > User can log in What I have is... User registers > *** (If the user logs in anytime after registration they can log in and the account is activated without clicking on the link in the email) > *** User gets email and clicks on the link > Goes to page and gets a message saying the account has already been activated. I have tested the conditions and if the email does or does't exist I get the correct messages and the same goes for the activation code, but the third seems to happen as soon as the email is sent to the user allowing them to log in before they click the link. Here is the where the email is sent... if ($OK) { // If OK insert data to database mysqli_query($db_connect, "INSERT INTO `users` (`uname`, `password`, `email`, `fname`, `lname`, `contact`, `house`, `street` `postcode`, `regdate`, `activationCode`, `active`) VALUES ('".$uname."', '".$passHash."', '".$email."', '".$fname."', '".$lname."', '".$contact."', '".$house."', '".$street."', '".$postcode."', '".$regdate."', '".$activationCode."', 'N')") or die(mysqli_connect_error()); // Set up email to send function email($to, $subject, $body) { @mail($to, $subject, $body, 'From: Example <info@example.com>'); } // Send email to user for account activation email($email, 'Activate your account', "Hello ".$uname."\nYou have recently created an account using the credentials...\n\nUsername - ".$uname."\nPassword - ".$password."\n\nPlease click the link below to activate your account.\nhttp://www.example.com/activate?email=".$email."&activationCode=".$activationCode."\n\nThank You.\n\n"); echo "<p>A message has been sent to ".$email.", please check your emails to activate your account.<p>"; echo "<p>If you do not receive the message in your inbox please be sure to check your junk mail too.</p>"; session_destroy(); } else { back(); exit(); } Here is the ACTIVATE page... if (isset($_GET['email'], $_GET['activationCode']) === true) { // If email and email code exist in URL $email = mysqli_real_escape_string($db_connect, trim($_GET['email'])); $activationCode = mysqli_real_escape_string($db_connect, trim($_GET['activationCode'])); $query = mysqli_query($db_connect, "SELECT * FROM `users` WHERE `email` = '".$email."' ") or die(mysqli_connect_error()); $result = (mysqli_num_rows($query) > 0); if ($result) { // Check email exists in database while($row = mysqli_fetch_assoc($query)) { if ($row['activationCode'] == $activationCode) { // Check activation code exists in database // THIS IS THE PART NOT WORKING CORRECTLY ----------------------------------------------------------------------------------------------------------------------------------------------------- if ($row['active'] == 'Y') { // Account is active echo $failed."<p>Your account has already been activated. You may <a href='/login'>Log In</a></p>"; } else { // Account not active mysqli_query($db_connect, "UPDATE `users` SET `active` = 'Y' WHERE `email` = '".$email."' LIMIT 1"); // Activate account echo $success."<p>Your account is now activated. You may <a href='/login'>Log In</a></p>"; } // -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- } else { // Activation code is invalid echo $failed."<p>Hmmm, the activation code seems to be invalid!</p>"; } } } else { // Email does not exist echo $failed."<p>Hmmm, ".$email." does not seem to exist in our records!</p>"; } } else { header("Location: /login"); exit(); } Here is the LOGIN page... if (isset($_POST['login'])) { // Create variables from submitted data $uname = mysqli_real_escape_string($db_connect, $_POST['uname']); $password = mysqli_real_escape_string($db_connect, $_POST['loginPassword']); $password = md5($password); // Encrypt password $query = mysqli_query($db_connect, "SELECT * FROM `users` WHERE `uname` = '".$uname."' AND `password` = '".$password."' ") or die(mysqli_connect_error()); // Check if uname and password match $result = (mysqli_num_rows($query) > 0); if ($result) { // If uname and password match while($row = mysqli_fetch_assoc($query)) { if ($row['active'] == 'N') { // Account is not active echo "<p>Your account has not been activated! Please check your email inbox.</p><br />"; } else if ($row['active'] == 'Y') { // Account is active $_SESSION['uname'] = $_POST['uname']; header("Location: /profile"); } } } else { // If uname and password do not match echo "<p>The combination of username and password is incorrect!</p><br />"; } } else { // Default login(); register(); exit(); } Why it is not working correctly or what I am doing wrong? All help appreciated in advance.
  10. Hi All, I get the following message when running a multiline query through mysqli. Here is my simplified code : $sql='SELECT CURRENT_USER();'; $sql.='SELECT CURRENT_time();'; $rs = @mysqli_multi_query($link,$sql); if (!$rs) { } else { do { if ($rs = mysqli_store_result($link)) { while ($row = mysqli_fetch_row($rs)) { echo "<br/> ". $row[0]; } mysqli_free_result($rs); } if (mysqli_more_results($link)) { echo "<br/>-----------------<br/>"; } } while (mysqli_next_result($link)); } If I use "while (mysqli_next_result($link) && mysqli_more_results($link));" instead of "while (mysqli_next_result($link))", I get no error message, but the current time (returned by the second query) won't display. Thanks for your help!
  11. Me again.. I've struggled for the past 2 hours to insert article comments and link them to an existent article on the page. Now, the function that is displaying both comments and articles looks like this: function list_articles() { include('core/db/db_connection.php'); $sql = "SELECT blog.content_id, blog.title, blog.content, blog.posted_by, blog.date, article_comments.comments, article_comments.comment_by FROM blog LEFT OUTER JOIN article_comments ON blog.content_id = article_comments.blog_id WHERE blog.content != '' ORDER BY blog.content_id DESC"; $result = mysqli_query($dbCon, $sql); $previous_blog_id = 0; while ($row = mysqli_fetch_array($result)) { if ($previous_blog_id != $row['content_id']) { echo "<h5 class='posted_by'>Posted by {$row['posted_by']} on {$row['date']}</h5> <h1 class='content_headers'>{$row['title']}</h1> <article>{$row['content']}</article> <hr class='artline'>"; $previous_blog_id = $row['content_id']; } if (!empty($row['comment_by']) && !empty($row['comments'])) { echo "<div class='commented_by'>Posted by: {$row['comment_by']} </div> <div class='comments'>Comments: {$row['comments']}</div> <hr class='artline2'>"; } } } The function I'm running to insert comments into article_comments table function insert_comments($comments, $comment_by, $blog_id) { include('core/db/db_connection.php'); $comment_by = sanitize($comment_by); $comments = sanitize($comments); $sql = "INSERT INTO article_comments (comments, comment_by, blog_id) VALUES ('$comments', '$comment_by', '$blog_id')"; mysqli_query($dbCon, $sql); } This works - it does the insertion, however I have no clue on how I could target the $blog_id variable when the user submits the post... The below is the form I use <?php echo list_articles(); if (!empty($_POST)) { insert_comments($_POST['comments'], $_POST['username'], 11); } ?> <form method='post' action='' class='comments_form'> <input type='text' name='username' placeholder='your name... *' id='name'> <textarea name='comments' id='textarea' placeholder='your comment... *' cols='30' rows='6'></textarea> <input type='submit' name='submit' id='post' value='post'> </form> I bet you noticed that I've manually inserted 11 as a param for the last variable. This links to blog_id 11 (the foreign key) in my article_comments table. It is displaying the comment just fine. Is there any way to target $blog_id without having to insert a number manually? Something like how I am targeting the $comments variable using $_POST['comments'] ? Also, even if I can target that, how do I know which post is the user commenting to? Should I give them the option to choose in a drop-down list ? That seems awkward.. but it's the only solution I can think of.
  12. Is it possible to link column_id from table A with column_id from table B? For example: If column_id A has a value of 6, column_id B should not be able allow entries if the column_id B is more than the value of column id A. I am running the below function to extract data from these tables: function list_articles() { include('core/db/db_connection.php'); $sql = "SELECT blog.title, blog.content, blog.posted_by, blog.date, article_comments.comments, article_comments.comment_by FROM blog LEFT OUTER JOIN article_comments ON blog.content_id = article_comments.comment_id WHERE blog.content != '' ORDER BY blog.content_id DESC"; $result = mysqli_query($dbCon, $sql); while ($row = mysqli_fetch_array($result)) { echo "<h5 class='posted_by'>Posted by " . $posted_by = $row['posted_by'] . " on " . $row['date'] . "</h5>" . "<h1 class='content_headers'>" . $title = $row['title'] . "</h1>" . "<article>" . $content = $row['content'] . "</article>" . "<hr class='artline'>" . "<div class='commented_by'>" . $row['comment_by'] . "</div>" . "<div class='comments'>" . $row['comments'] . "</div>"; } } Thanks.
  13. hey guys i have a few questions regarding my website that has the use of multiple databases....at the moment my site is ran off one mysqli connection and before executing a query i change the database depending on if its my authentication script, geoip, framework etc. what i'm worried about is performance issues....i could have a new connection for each database or continue to have one connection for the whole site and change database when needed...what is the best practice please? thank you.
  14. Hello, I have inserted a user into my database table through phpMyAdmin using the predefined MD5 function. (I know md5 is not secure and I should use bcrypt istead, but I don't need that type of security, my only purpose is not to store the passwords in plain text) Now my problem is that whenever I try to log the user in, I can never read the hashed password back. This is my code: The function that is testing for the username and password: function login($username, $password) { include('core/db/db_connection.php'); $sql = "SELECT COUNT(user_id) FROM `_users` WHERE username = '$username' AND password = '$password'"; $query = mysqli_query($dbCon, $sql); $user_id = get_user_id($username); $username = sanitize($username); $password = md5($password); // issue return (mysqli_result($query, 0) == 1) ? $user_id : false; // possible issue } The logging processing code: if (empty($_POST) === false) { $username = $_POST['username']; $password = $_POST['password']; if (empty($username) === true || empty($password) === true) { $errors[] = 'Username and/or password fields must not be left blank'; } else if (user_exists($username) === false) { $errors[] = 'Username does not exist! Please register before logging in.'; } else if (user_active($username) === false) { $errors[] = 'You haven\'t activated your account yet'; } else { $login = login($username, $password); if ($login === false) { $errors[] = 'Username/password incorrect'; } else { echo 'ok' . '<br/>'; //set user session //redirect user } } print_r($errors); } How can I read the stored MD5 password to allow my registered users access? Many thanks.
  15. I've written a script to store images in my database. The images have a caption that is also uploaded and stored. This was fairly easy to get working. I have a jquery function setup to add a new file input and caption input every time I click a button. This also works. What is not working is my PHP is not uploading multiple files for some reason. Could someone tell me what I have done wrong? Thanks HTML: <form id="uploadMultiple" method="post" action="/scripts/php/imageUploadTest" enctype="multipart/form-data"> <table class="fileUploadTable" id="uploadArea" cellspacing="0"> <tr> <td> <label for="imageFile">Image:</label> <input type="file" name="imageFile" accept=".jpg,.jpeg,.png,.gif"> </td> <td> <label for="imageCaption">Image Caption:</label> <input type="text" name="imageCaption"> </td> <td width="150px"> </td> </tr> <tr id="uploadSubmission"> <td> <input type="submit" value="Upload More" id="uploadMore"> </td> <td> <input type="submit" value="Submit" name="addImage"> </td> <td width="150px"> </td> </tr> </table> </form> JQuery for adding new elements: $(function() { var scntDiv = $('#uploadArea'); var i = $('#p_scents tr td').size() + 1; $('#uploadMore').live('click', function() { $('<tr><td><label for="imageFile">Image:</label> <input type="file" name="imageFile" accept=".jpg,.jpeg,.png,.gif"></td><td><label for="imageCaption">Image Caption:</label> <input type="text" name="imageCaption"></td><td><a href="#" class="removeUpload" width="150px" style="text-align: center">Remove</a></td></tr>').insertBefore( $('#uploadSubmission') ); i++; return false; }); $('.removeUpload').live('click', function() { if( i > 1 ) { $(this).parents('tr').remove(); i--; } return false; }); }); And finally the PHP: require($_SERVER['DOCUMENT_ROOT'].'/settings/globalVariables.php'); require($_SERVER['DOCUMENT_ROOT'].'/settings/mysqli_connect.php'); $db_name = 'imageUploads'; $tbl_name = 'gallery'; if(!$conn) { die('Could not connect: ' . mysqli_error()); } mysqli_select_db($conn, "$db_name")or die("cannot select DB"); foreach($_FILES['imageFile'] as $file){ $caption = $_POST['imageCaption']; $uploadDir = 'http://www.example.com/images/'.'gallery/'; $fileName = $_FILES['imageFile']['name']; $filePath = $uploadDir . $fileName; if(move_uploaded_file($_FILES["imageFile"]["tmp_name"],$_SERVER['DOCUMENT_ROOT']."/images/gallery/".$_FILES["imageFile"]["name"])) { $query_image = "INSERT INTO $tbl_name(filename,path,caption) VALUES ('$fileName','$uploadDir','$caption')"; if(mysqli_query($conn, $query_image)) { echo "Stored in: " . "gallery/" . $_FILES["imageFile"]["name"]; } else { echo 'File name not stored in database'; } } } I was hoping I had it working properly for multiple images with my `foreach` loop but it only uploads one image even if I have 4 selected. EDIT: I've tried modifying my code to this and it's not working either but looking at tutorials this seems to be more on the right track than my previous code: r equire($_SERVER['DOCUMENT_ROOT'].'/settings/globalVariables.php'); require($_SERVER['DOCUMENT_ROOT'].'/settings/mysqli_connect.php'); $db_name = 'imageUploads'; $tbl_name = 'gallery'; if(!$conn) { die('Could not connect: ' . mysqli_error()); } mysqli_select_db($conn, "$db_name")or die("cannot select DB"); foreach($_FILES['imageFile'] as $key => $name){ $caption = $_POST['imageCaption']; $uploadDir = 'http://www.example.com/images/'.'gallery/'; $fileName = $key.$_FILES['imageFile']['name'][$key]; $file_size = $_FILES['files']['size'][$key]; $file_tmp = $_FILES['files']['tmp_name'][$key]; $file_type= $_FILES['files']['type'][$key]; $filePath = $uploadDir . $fileName; if(move_uploaded_file($file_tmp,$_SERVER['DOCUMENT_ROOT']."/images/gallery/".$fileName)) { $query_image = "INSERT INTO $tbl_name(filename,path,caption) VALUES ('$fileName','$uploadDir','$caption')"; if(mysqli_query($conn, $query_image)) { echo "Stored in: " . "gallery/" . $_FILES["imageFile"]["name"]; } else { echo 'File name not stored in database'; } } } I've also added `[]` in the names of the HTML input elements that needed them.
  16. $results = mysql_query("$select", $link_id); while ($query_data = mysql_fetch_row($results)) { $link_id = mysqli_connect("$db_host","$db_user","$db_password","$db_database"); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; } $link_id = mysql_connect("$db_host","$db_user","$db_password"); if (mysql_select_db("$db_database", $link_id)); else { echo "connection failed."; } I am having to update MySQL to mysqli as my host is upgrading to PHP5.6 I have managed to convert and connect to the database converted to I cannot get the fetch results to work, can anyone help me convert the following code Many Thanks
  17. Hello, I am new to PHP, so I decided the best way to learn is to build a CMS, that I can build and adapt as time progresses. I am wanting to create a setup/install wizard for when a user first uploads the website and then visits the website. I attempted to do this on my own, but it did not work, but hey I still included the code in-case I was close to getting it working. (See below). I am wanting to have a HTML form that will contain the input fields, where the user will enter their database host, username, and password. And all of the details in the form will replace the mysqli connection in the config.php file, which is seperate from the install file. That is all I really need help with at the moment, as creating users, etc is pretty easy (even though I am new to PHP). My "attempted" code: - Install.php: <?php /* Config required to replace the database strings */ require('config/config.php'); /* HTML Form to be echoed for the user */ $form = " <form name='form' action='' method='get'> <input type='text' name='host' placeholder='Database host' /> <input type='text' name='database' placeholder='Database name' /> <input type='text' name='username' placeholder='Database username' /> <input type='password' name='password' placeholder='Database password' /> <input type='submit' name='submit' value='Change values' /> </form> "; /* Echo the form so I can see it */ echo $form; /* Get the results from the HTML Form */ $gethost = $_GET['host']; $getdb = $_GET['database']; $getuser = $_GET['username']; $getpass = $_GET['password']; /* Replace the database connections in config.php */ /* However, does not work :/ */ if (isset($_GET['submit'])) { str_replace($gethost,$host); } ?> - Config.php: <?php $host = "localhost"; $username = "root"; $password = ""; $database = "website"; /* Change this line in the HTML Form in setup.php */ $dbc = mysqli_connect($host, $username, $password, $database); ?> Thanks in advanced, Unique
  18. Is there a way to get the count of rows like this? $count = somefunctionthatreturnscount(mysqli_query($mysqli, "SELECT COUNT(*) FROM table")); Instead of... $count = mysqli_num_rows(mysqli_query($mysqli, "SELECT id FROM table")); //or even... $count = mysqli_fetch_array(mysqli_query($mysqli, "SELECT COUNT(*) as count FROM table")); Ultimately, I want the method that will get the count the quickest and if can be done similarly to the first code and still have good performance. Thanks in advance! Update: Reported post as duplicate. Need moderate to delete duplicates as that option is not appearing for me.
  19. Hello guys. I got a problem that whenever you register on my page, the registration is successful, no errors, successful redirection to login page, but the registration does not write the information into database and I have no idea why... I'm sure that i'm connecting correctly, to the correct table, with the correct commands, but it kinda does not work... BTW (This registration and login and all worked a few weeks ago, but I got an sudden internal server error, so I had to delete and reupload all files, and I had to change database. I changed the database, created the same table with the same columns, also I overwrote ALL old database information to the new (password, dbname,name) and, so page works fine, but that registration does not...I'm including my code for registration and registration form) Registration process CODE: <?php include_once 'db_connect.php'; include_once 'psl-config.php'; $error_msg = ""; if (isset($_POST['username'], $_POST['email'], $_POST['p'])) { // Sanitize and validate the data passed in $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING); $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL); $email = filter_var($email, FILTER_VALIDATE_EMAIL); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // Not a valid email $error_msg .= '<p class="error">The email address you entered is not valid</p>'; } $password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING); // Username validity and password validity have been checked client side. // This should should be adequate as nobody gains any advantage from // breaking these rules. // $prep_stmt = "SELECT id FROM members WHERE email = ? LIMIT 1"; $stmt = $mysqli->prepare($prep_stmt); // check existing email if ($stmt) { $stmt->bind_param('s', $email); $stmt->execute(); $stmt->store_result(); if ($stmt->num_rows == 1) { $error_msg .= '<p class="error">A user with this email address already exists.</p>'; } $stmt->close(); } // check existing username $prep_stmt = "SELECT id FROM members WHERE username = ? LIMIT 1"; $stmt = $mysqli->prepare($prep_stmt); if ($stmt) { $stmt->bind_param('s', $username); $stmt->execute(); $stmt->store_result(); if ($stmt->num_rows == 1) { $error_msg .= '<p class="error">A user with this username already exists.</p>'; } $stmt->close(); } // TODO: // We'll also have to account for the situation where the user doesn't have // rights to do registration, by checking what type of user is attempting to // perform the operation. if (empty($error_msg)) { // Create salted password $passwordHash = password_hash($password, PASSWORD_BCRYPT); // Insert the new user into the database if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password) VALUES (?, ?, ?)")) { $insert_stmt->bind_param('sss', $username, $email, $passwordHash); // Execute the prepared query. if (! $insert_stmt->execute()) { header('Location: ../error.php?err=Registration failure: INSERT'); } } header('Location: ./continue.php'); } } and Registration form : <div class="register-form"> <center><h2>Registration</h2></center> <form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>" method="post" name="registration_form"> <center><p></p><input type='text' name='username' placeholder="Username" id='username' /><br></center> <center><p></p><input type="text" name="email" id="email" placeholder="Email" /><br></center> <center><p></p><input type="password" name="password" placeholder="Insert Password" id="password"/><br></center> <center><p></p><input type="password" name="confirmpwd" placeholder="Repeat Password" id="confirmpwd" /><br></center> <center><p></p><input type="submit" class="button" value="Register" onclick="return regformhash(this.form, this.form.username, this.form.email, this.form.password, this.form.confirmpwd);" /> </center> </form> </div> Anybody know where is problem?
  20. I have the following general mySQL query: $query = sprintf( "SELECT a.A, a.B, ..., a.C, FROM a WHERE a.A = %s ORDER by a.A;", implode(" OR a.A = ", $_SESSION['values'])); for some records, B has a value, and for others, B is NULL. That is what I want. I extract the query with the following PHP: for ($i = 0; $i < $nrows; $i++){ $row = mysqli_fetch_assoc($result);//fetches data stored within each row extract($row); echo "<tr>"; foreach($row as $column => $field){ if($field == $...){ ... } elseif($field == $C){ echo"<td> <input type='text' name='C+[]' value='$C'> </td>"; } echo "</tr>" } In the resulting html table, records containing not null B fields are presented accurately, while records with null B fields incur a duplication of field C. This offset occurs at the beginning of the record, pushing the final field in the record outside the table boundaries. I think I've narrowed down the problem to the extract() function, as r_print readouts of every other variable in the script returns the accurate field names and values. But, running print_r on $row after extract() provides an identical printout to other variables in the script. What are some possible ways I can stop the duplication of field C from occurring? Happy to provide more information upon request.
  21. Not sure what is going on I tried everything (well, that I could think of) . . . any ideas are welcome (hopefully new ones - getting frustrated :/) if ($mysqli->prepare("INSERT INTO solcontest_entries (title, image,content, user, contest) VALUES ($title, $image, $content, $userid, $contest")) { $stmt2 = $mysqli->prepare("INSERT INTO `solcontest_entries` (title, image, content, user, contest) VALUES (?, ?, ?, ?, ?)"); $stmt2->bind_param('sssss', $title, $image, $content, $userid, $contest); $stmt2->execute(); $stmt2->store_result(); $stmt2->fetch(); $stmt2->close(); } else { die(mysqli_error($mysqli)); } Error I get from die mysqli_error: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' of the site's lead ad, user_61609201, contest_1' at line 1" I have also tried $mysqli->query no change occured. I added the "if else die" statement because it was giving no errors, but not adding it to the database. It gives the error where $content is supposed to be inserted. Various combos and singles I tried for the variable: //$content = cleansafely($_POST['content']); //$content = mysqli_real_escape_string ($mysqli, $_POST['content']); //$content = cleansafely($content); $content = $_POST['content']; If any more information is needed please let me know.
  22. Hello guys, I have a question about how to insert a multiple query into database i have the following html form <div class="input_fields_wrap"> <button id="remove_field">x</button> <?php $query = mysql_query("SELECT * FROM producten"); ?> <select name="Producten[]" id="Producten"> <div><?php while($row = mysql_fetch_array($query)){ echo "<option>" . $row['Producten'] . "</option>"; }?> </div><input type="text" name="ProdOms[]"> <input type="text" size="3" name="Aantal[]"> <input type="text" size="3" name="Prijs[]"> <a href="javascript:void(0)" onclick="toggle_visibility('popup-box1');"><img src="../img/icons/info.png" height="16" width="16"></a> </select> </div> So this is the html form what I'm using i have 15 of these. It deppents how much the user would like too use for example he/she want to use 2 form like this fill it in and insert into the database.
  23. Hi guys, i am creating my change password site for my website and i have some problems with the code... For some reason i have difficulties with the passwords being compared and replaced in the db after crypting them. I wanted this: Either get the current users password and compare it to the input value of $oldpass or compare the input value of $oldpass with the password stored in the database for the current user. After checking if the $oldpass and the password from the database match and IF they match then take the input value of $newpass and $repeatpass, compare them and if they match, then crypt() $newpass and update the database with the new password. I am not even sure if the passwords are even crypted. Also in the code i am comparing $oldpass with $_SESSION['password'] which is not the password from the db, i can't figure out how to call the password from the db. Thanks in advance! <?php include 'check_login_status.php'; $u=""; $oldpass=md5($_POST['oldpass']); //stripping both strings of white spaces $newpass = preg_replace('#[^a-z0-9]#i', '', $_POST['newpass']); $repeatpass = preg_replace('#[^a-z0-9]#i', '', $_POST['repeatpass']); //get the username from the header if(isset($_GET["u"])){ $u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']); } else { header("location: compare_pass.php?u=".$_SESSION["username"]); exit(); } // Select the member from the users table $sql = "SELECT password FROM users WHERE username='$u' LIMIT 1"; mysqli_query($db_conx, $sql); $user_query = mysqli_query($db_conx, $sql); // Now make sure that user exists in the table $numrows = mysqli_num_rows($user_query); if($numrows < 1){ echo "That user does not exist or is not yet activated, press back"; exit(); } if ($oldpass == $_SESSION['password']) { echo "session and oldpass are matching"; } else { echo "Session and oldpass do not match!"; } $isOwner = "no"; //check if user is logged in owner of account if($u == $log_username && $user_ok == true){ $isOwner = "yes"; } $passhash = ""; if (isset($_POST["submit"]) && ($isOwner == "yes") && ($user_ok == true) && ($newpass == $repeatpass)) { $passhash = crypt_sha256("$newpass", "B-Pz=0%5mI~SAOcW0pMUdgKQh1_B7H6sbKAl+9~O98E9MBPrpGOtE65ro~8R"); $sql = "UPDATE users SET `password`='$passhash' WHERE username='$u' LIMIT 1"; } if (mysqli_query($db_conx, $sql)) { echo "Record updated successfully"; } else { echo "Error updating record: " . mysqli_error($db_conx); } ?> <h3>Create new password</h3> <form action="" method="post"> <div>Current Password</div> <input type="text" class="form-control" id="password" name="oldpass" > <div>New Password</div> <input type="text" class="form-control" id="password" name="newpass" > <div>Repeat Password</div> <input type="text" class="form-control" id="password" name="repeatpass" > <br /><br /> <input type="submit" name="submit" value="Submit"> <p id="status" ></p> </form><?php echo "{$oldpass}, {$_SESSION['password']}"; ?> <pre> <?php var_dump($_SESSION); var_dump($oldpass); var_dump($passhash); var_dump($newpass); var_dump($repeatpass); ?> </pre>
  24. I am trying to create a "login" webpage. The PHP codes for the login (login100.php) are called by another file (index100.php). Whenever I run index100.php on XAMPP, I get two errors: Warning: mysqli_error() expects exactly 1 parameter, 0 given in C:\xampp\htdocs\login100.php on line 24 Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\login100.php on line 26 My codes for index.php are: <?php include('login100.php'); // Includes Login Script if(isset($_SESSION['login_user'])){ header("location: profile100.php"); } ?> <!DOCTYPE html> <html> <head> <title>Login Form in PHP with Session</title> <link href="style100.css" rel="stylesheet" type="text/css"> </head> <body> <div id="main"> <h1>PHP Login Session Example</h1> <div id="login"> <h2>Login Form</h2> <form action="" method="post"> <label>UserName :</label> <input id="name" name="username" placeholder="username" type="text"> <label>Password :</label> <input id="password" name="password" placeholder="**********" type="password"> <input name="submit" type="submit" value=" Login "> <span><?php echo $error; ?></span> </form> </div> </div> </body> </html> My codes for login.php are: <?php session_start(); // Starting Session $error=''; // Variable To Store Error Message if (isset($_POST['submit'])) { if (empty($_POST['username']) || empty($_POST['password'])) { $error = "Username or Password is invalid"; } else { // Define $username and $password $username=$_POST['username']; $password=$_POST['password']; // Establishing Connection with Server by passing server_name, user_id and password as a parameter $connection = mysqli_connect("localhost", "root", "", "Company"); // To protect MySQL injection for Security purpose $username = stripslashes($username); $password = stripslashes($password); $username = mysqli_real_escape_string($connection, $username); $password = mysqli_real_escape_string($connection, $password); // SQL query to fetch information of registerd users and finds user match. $sql = "SELECT * FROM login where password='$password' AND username='$username'"; $query = mysqli_query($connection, $sql); if (false === $query) { echo mysqli_error(); } $rows = mysqli_num_rows($query); if ($rows == 1) { $_SESSION['login_user']=$username; // Initializing Session header("location: profile100.php"); // Redirecting To Other Page } else { $error = "Username or Password is invalid"; } mysqli_close($connection); // Closing Connection } } ?> I have worked on this for the past FIVE days and I cannot resolve this issue. All I want is a code which fetches a user's username and password from the database, and no such username or password exist, a message saying "invalid password" is generated. For some reason, I'm getting the two error messages above. Can someone help?
  25. Hi everyone, I'm having troubles with query from database. I want to select all from one table and select sum from second table in the same time. Is this possible? Here is my script: $conn = mysqli_connect('localhost', 'root', '', 'test'); if (!mysqli_set_charset($conn, "utf8")) { printf("Error loading character set utf8: %s\n", mysqli_error($conn)); } $sql = "SELECT first_id, first_name FROM first"; $sql = "SELECT sum(total) as SumTotal FROM second"; $result = mysqli_query($conn, $sql); while ($data = mysqli_fetch_array($result)) { echo '<tr>'; echo '<th>'.$data['first_id'].'</th>'; echo '<th>'.$data['first_name'].'</th>'; echo '<th>'.$data['SumTotal'].'</th>'; echo '</tr>'; } mysqli_close($conn); Thanks!
  • 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.