Jump to content

Search the Community

Showing results for tags 'mysqli'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • 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

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. Hi Guys I am fairly new to php, I am trying to build a registration form but I am struggling with encrypting the password (I will also be salting the password at a later stage to make it more secure). The below line of code encrypts the password but saves the values as the values states in the code e.g password saves as 'pass' $q = "INSERT INTO users (first_name,last_name,email,pass,registration_date) VALUES ('first_name','last_name','email', SHA1('pass'), NOW())"; The below code saves all the values that the user inputs xcept the password which is blank and the message 'Undefined index: SHA1('pass')' is returned $q = "INSERT INTO users (first_name,last_name,email,pass,registration_date) VALUES ('".$_POST["first_name"]."','".$_POST["last_name"]."','".$_POST["email"]."','".$_POST["SHA1('pass')"]."', NOW())"; I am hoping someone may be able to help me as I have no idea how to fix this. Thank you in advance
  2. I am updating all my code from mysql to mysqli. Currently using PHP 5.4 but will update to 5.5 once all this updating is done. Anyway, I have this old function for making data safe for inserting into mysql database. I changed all instances of "mysql" to "mysqli"... function mysqli_prep($value) { $magic_quotes_active = get_magic_quotes_gpc(); $new_enough_php = function_exists("mysqli_real_escape_string") ; //i.e. PHP >= v4.3.0 if($new_enough_php) { //PHP v4.3.0 or higher //undo any magic quote effects so mysqli_real_escape_string can do the work if($magic_quotes_active) { $value = stripslashes($value) ;} $value = mysqli_real_escape_string($connection, $value); } else { //before php v4.3.0 // if magic quotes aren;t already on then add slashes manually if(!magic_quotes_active) { $value = addslashes($value); } // if magic quotes are active, then the slashes already exist } return $value; } When I load that page that calls this function, I get... Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in (mypath) This is my $connection by the way, which works fine on other pages that need it... $connection = mysqli_connect('localhost', 'myusername', 'mypassword', 'mytable'); if (!$connection) { die("database connection failed: " . mysqli_error()); } Any ideas what I'm doing wrong?
  3. Hello Happy Campers. Wonder if someone can point me in the right direction if it's not too much trouble. I have a script that allows an EU to edit a database entry. The users edits the information and hits submit which then edits the content and it all works spiffingly. My problem however arises when I go to upload a new image. The "Add" function uploads images to a directory and the location is saved in the database. When editing the image however, it unlinks it but it does not allow me to upload a new image. The code is as follows: ini_set('display_errors',1); error_reporting(E_ALL); $conn = mysqli_connect("HOST","DB","PWRD","DBTBL") or die('Cannot Connect to the database'); $i = mysqli_real_escape_string($conn,$_POST['newsid']); $t = mysqli_real_escape_string($conn,$_POST['title']); $st = mysqli_real_escape_string($conn,$_POST['stat']); $sn = mysqli_real_escape_string($conn,$_POST['snip']); $s = mysqli_real_escape_string($conn,$_POST['stry']); $c = mysqli_real_escape_string($conn,$_POST['cap']); $f = $_POST['oldim']; $s = nl2br($s); if(!is_uploaded_file($_FILES['file']['tmp_name'])) { $naquery = "UPDATE news SET newstitle='$t',newssnip='$sn',newsarticle='$s',newsstatus='$st' WHERE newsid=$i"; } else { if ($_FILES['file']['type'] != "image/gif" && $_FILES['file']['type'] != "image/jpeg" && $_FILES['file']['type'] != "image/jpg" && $_FILES['file']['type'] != "image/x-png" && $_FILES['file']['type'] != "image/png") { $naquery = "UPDATE news SET newstitle='$t',newssnip='$sn',newsarticle='$s',newsstatus='$st' WHERE newsid=$i"; } else { $finame = $_FILES["file"]["name"]; $result = move_uploaded_file($_FILES['file']['tmp_name'], "../news/$finame"); if ($result == 1) { $naquery = "UPDATE news SET newstitle='$t',newssnip='$sn',newsarticle='$s',newsimage='$finame' newscaption='$c',newsstatus='$st' WHERE newsid=$i"; $d = "../news/"; unlink("$d$f"); } else { $naquery = "UPDATE news SET newstitle='$t',newssnip='$sn',newsarticle='$s',newsstatus='$st' WHERE newsid=$i"; } } } $result = mysqli_query($conn, $naquery); if($result){ header('Location: ../news.php'); } else { echo "Oh No! Something has gone wrong and the data could not be uploaded"; echo "<br />"; echo "click <a href='Link'>here</a> to return to News"; } mysqli_close($conn); I am not getting an error message from PHP, I am just getting the generic "Something has gone wrong" that I have coded in myself. Is there anyone who can point me in the right direction please? Cheers
  4. Hello, I'm Paul Ryan. I am 23 years old and have around 8 years experience in programming with the following languages: - PHP - MySQLi - HTML - CSS - JavasScript (jQuery, AJAX) I have worked on many project over the years, including the following: - BoxSelect.com - Taccd.com - FTA.ie - BelfastCookerySchool.com - Dittnyebad.no - MassasjeShop.no - Project: Universe (Personal Project) I have worked on many other smaller jobs, updating outdated code, database and code optimizations etc. You can contact me via the following methods: - PHP Freaks Personal Message - Skype: paulryanmc91 - E-mail: [email protected] I am available to start work immediately whether the job be big or small, don't hesitate to contact me. Thanks for your time, look forward to hearing from you. Kind Regards, Paul Ryan
  5. Hi, I am trying to migrate my project from mysql to mysqli but with little knowledge of the later. Among the noticeable errors is that the code is no longer fetching data from the database, and I am also getting UNDEFINED VARIABLE errors on the in the mysqli statement that should be binding results to variables. Here is the code if you can help: //set connection variables $host = "localhost"; $username = "root"; $password = "password"; $db_name = "mydb"; //database name //connect to mysql server $mysqli = new mysqli($host, $username, $password, $db_name); //check if any connection error was encountered if(mysqli_connect_errno()) { echo "Error: Could not connect to database."; exit; } //Just counting ...required for pagination... $query = "SELECT COUNT(*) FROM t_persons"; $result = mysqli_query($mysqli,$query) or die(mysqli_connect_errno()); $num_rows = mysqli_fetch_row($result); $pages = new Paginator; $pages->items_total = $num_rows[0]; $pages->mid_range = 9; // Number of pages to display. Must be odd and > 3 $pages->paginate(); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } if ($stmt = $mysqli->prepare("SELECT p.PersonID, p.ImagePath, p.FamilyName, p.FirstName, p.OtherNames, p.Gender, p.CountryID, p.StatusID, i.IncidentDate, i.IncidentCountryID, i.AgencyID, i.KeywordID FROM t_incidents i INNER JOIN t_incident_persons ip ON ip.IncidentID = i.IncidentID INNER JOIN t_persons p ON ip.PersonID = p.PersonID WHERE p.PersonID>0" . $likes . " ORDER BY p.PersonID DESC $pages->limit")) { /* Execute the prepared Statement */ $stmt->execute(); /* Bind results to variables */ $stmt->bind_result($PersonID,$ImagePath,$FamilyName,$FirstName,$OtherNames,$Gender,$CountryID,$StatusID,$IncidentDate,$IncidentCountryID,$AgencyID,$KeywordID); /* fetch values */ while ($rows = $stmt->fetch()) { // display records in a table // $PersonID=$row[0]; ?> <div class="thumbnail"> <a href=details.php?PersonID=<?php echo $PersonID ?> target=gallery><img src="./Persons_Images/<?php echo $row[1]; ?>" width="100" height="130" alt="" /></a><br> <a href="details.php?PersonID=<?php echo $PersonID; ?>"> <?php echo $row[2]; ?> <?php echo $row[3]; ?></a> </div> <?php }?> <?php } /* Close the statement */ $stmt->close(); /* close our connection */ $mysqli->close(); ?> I will appreciate. Joseph
  6. Hi I'm trying to insert unique info retrieved to my database but seems like I'm doing something wrong with my quary my current setup is as follow mxit.php <?php $con=mysqli_connect("*****","*******","*******","******"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } mysqli_close($con); ?> <? define('TIMEZONE', 'Africa/Harare'); date_default_timezone_set(TIMEZONE); $ip = $_SERVER["REMOTE_ADDR"]; $post_time = date("U"); $mxitua = $_SERVER["HTTP_X_DEVICE_USER_AGENT"]; $mxitcont = $_SERVER["HTTP_X_MXIT_CONTACT"]; $mxituid = $_SERVER["HTTP_X_MXIT_USERID_R"]; $mxitid = $_SERVER["HTTP_X_MXIT_ID_R"]; $mxitlogin = $_SERVER["HTTP_X_MXIT_LOGIN"]; $mxitnick = $_SERVER["HTTP_X_MXIT_NICK"]; $mxitloc = $_SERVER["HTTP_X_MXIT_LOCATION"]; $mxitprof = $_SERVER["HTTP_X_MXIT_PROFILE"]; if(!isset($mxitid)) { $mxitid = "DEFAULT"; } mysqli_query($con,"INSERT INTO mxit (ip,time,user_agent,contact,userid,id,login,nick,location,profile) VALUES ($ip,$post_time,$mxitua,$mxitcont,$mxituid,$mxitid,$mxitlogin,$mxitnick,$mxitloc,$mxitprof)"); mysqli_close($con); ?> and ive included the above file on my index.php <?PHP include "mxit.php"; ?> but after I've opened up my index page I get an error And another question is how can I check the field contact in my databases and if the name already exists not to add the record to my database? Since I don't want duplicate records...
  7. I have this 3 tables users (id_user) music_styles (id_style, style) ex. (1) - (Blues) user_styles (id_user, id_style) I'm trying to create a form in which the user ($user = $_SESSION['id_user']) chooses through a multiple select the styles of preference to store them in the database using mysqli statements. If the styles prefered are selected they should be displayed in the select input later, how can i accomplish this? Thanks.
  8. Hi guys, I've been around here for a few years, but for some reason my other account doesn't seem to 'exist' anymore which was real annoying. I also noticed the captcha here was kind of buggy has anyone else been getting that? I'd enter it in case sensative 9-10 times before it would finally work. Anyways, I've been looking through a lot of research in upgrading my server from Mysql to Mysqli funtions. What I am curious about though is other peoples opinions and thoughts on how to make user input safer. For the time being I've just been using mysql_real_escape_string and htmlspecialchars. I've done quite a bit of research on this and there really isn't much for any guides on how to keep your data clean and safe. I've seen a lot of posts that anymore these two functions are not enough to secure your data. So I'm curious what people in this community are doing (annonomysly) to keep your user input safe. I'm also looking into prepared statements as well with Mysqli. Anyways any responses are much appreciated, would love to chat with you guys about this! Does anyone know if there was some deal with why I can't access my origional account? I entered in all of the only 5 email addresses I use. It said it sent an email to the one, but it never appeared in junk/inbox.
  9. Hi, I can I include a date range criteria to query with in the following code? The date field in the table (t_persons) is IncidentDate. $criteria = array('FamilyName', 'FirstName', 'OtherNames', 'NRCNo', 'PassportNo', 'Gender', 'IncidenceCountryID', 'Status', 'OffenceKeyword', 'AgencyID', 'CountryID', 'IncidenceCountryID' ); $likes = ""; $url_criteria = ''; foreach ( $criteria AS $criterion ) { if ( ! empty($_POST[$criterion]) ) { $value = ($_POST[$criterion]); $likes .= " AND `$criterion` LIKE '%$value%'"; $url_criteria .= '&'.$criterion.'='.htmlentities($_POST[$criterion]); } elseif ( ! empty($_GET[$criterion]) ) { $value = mysql_real_escape_string($_GET[$criterion]); $likes .= " AND `$criterion` LIKE '%$value%'"; $url_criteria .= '&'.$criterion.'='.htmlentities($_GET[$criterion]); } //var_dump($likes); } $sql = "SELECT * FROM t_persons WHERE PersonID>0" . $likes . " ORDER BY PersonID DESC"; Kind regards.
  10. I don't know why it won't work.. as the topic titles says that I am trying to pass a mysqli object to a property in another class but it keeps me getting an error. here's the code for the mysqli object that i want to pass to another class class ConnectMe2Db { public $dbname = 'somedatabase'; public $dbuname = 'root'; public $dbpass = ''; public $dbhost = 'localhost'; function __construct() { $mysqli = new mysqli($this->dbhost,$this->dbuname,$this->dbpass,$this->dbname) or die ('ERROR: '.$mysqli->connect_errno); return $mysqli; } # OTHER CODES... } and here is the class that i want the Mysqli object to pass to: class DatabaseUsers { private $dbconnection; function __construct() { $this->dbconnection = new ConnectMe2Db();#mysqli object will be passed to this attribute '$dbconnection' } public function session($username, $password) { $UserName = mysqli_real_escape_string($this->dbconnection,$username); $Password = mysqli_real_escape_string($this->dbconnection,md5($password)); $querry = "SELECT * FROM trakingsystem.login WHERE username='$username' and password='$password'"; $result = mysqli_query($this->dbconnection,$querry) or die (mysqli_error($this->dbconnection)); $count = mysqli_num_rows($result); $row = mysqli_fetch_array($result); if ($count > 0) { #some code here } } #some other code here } and this outputs 4 errors: #outputs 2 of these: Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli and some mysqli_query() expects parameter 1 to be mysqli mysqli_error() expects parameter 1 to be mysqli is there something wrong with the logic that I've made? please help thanks
  11. So basically I am still starting off when it comes to learning PHP/MySQLi... I am looking to make a script that can do the following: If I update say my homepage by just my normal cPanel editor plus another page named "News" but through an Admin section on my site (so basically inserting a new row into the database instead of manually doing it through my cPanel) - I would like it to display in a section on my homepage that days date along with the list of pages that were updated underneath it within that date, but with names I give the pages so instead of just saying index.php updated, I want it do say "Home Page Updated." I did have an attempt at this but just couldn't get it right. I would like to set a limit on how many different dates can be shown also. Example: July 12, 2014 Home Page Updated. News Headlines Updated. Staff Members Updated. July 11, 2014 Home Page Updated. July 10, 2014 Home Page Updated. Contact Us Updated. and so on... Thank you to anyone who replies with some input, I have been going crazy trying to get this right and I just can't get it but badly want it..
  12. I'm storing website files online and each user can upload their own files and admin can upload files for that user specifically. How would I go about making sure nobody else can download their PDF file? Would it be a case of assigning a folder for each user's documents and not allowing access to any other user to that folder? Thanks in advance.
  13. I am creating a simple social network, and i want the post visible only on its circle of friends but the problem is... let say user_a, user_b, user_c already registered and user_a and user_c connected/friends already and all their posts and comments are visible on their circle but when user_b write a post oh his wall, it's also visible to user_a and user_c which i dont want to happen. I dont know what was wrong on codes below. CREATE TABLE IF NOT EXISTS `user`( `uid` INT(11) AUTO_INCREMENT PRIMARY KEY NOT NULL, `uname` VARCHAR(25) NOT NULL, `pword` CHAR(60) NOT NULL, `fullname` VARCHAR(30) NOT NULL, INDEX(`uname`) ) Engine = InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci; CREATE TABLE IF NOT EXISTS `friend`( `fid` INT(11) AUTO_INCREMENT PRIMARY KEY NOT NULL, `friend_id` INT(11) NOT NULL, `my_id` INT(11) NOT NULL, `stat` ENUM('0','1') NOT NULL, INDEX(`friend_id`, `my_id`), FOREIGN KEY(`friend_id`) REFERENCES `user`(`uid`) ON UPDATE CASCADE ON DELETE CASCADE ) Engine = InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci; public function viewFriendIfExistOnTbl($uid) { $query = $this->mysqli->query("SELECT `friend_id` FROM `friend` WHERE `my_id` = '$uid' LIMIT 1"); if ($query->num_rows > 0) { return true; } }
  14. Hello guys, i'm currently building my own cms, a personal project, and now im stucked on an error "Call to a member function query() on a non-object in.. please help after creating this function.. I know the db connection and everything else worked out because i have a similar function that works just without the switch or the numrow if statement. protected function _pageStatus($option, $id){ //check if page exists, if it does return the status, or return 404 switch($option){ case 'alpha' : $sql = "SELECT status FROM pages WHERE nick = '$id'"; break; case 'num' : $sql = "SELECT status FROM pages WHERE id = '$id'"; break; } if($result = $this->_db->query($sql)){ //<--- THE ERROR WAS ON THIS LINE. if($result->num_rows > 0){ while ($status = $result->fetch_object()) { return $status; } return $status; $result->close(); } else { return 404; } } }
  15. hey guys so im trying to display data into text boxes that are fetched from database according to checkbox with value id. processing is located before <!DOCTYPE html>: if(isset($_POST['edit_event']) && isset($_POST['check'])) { require "connection.php"; foreach ($_POST['check'] as $edit_id) { $edit_id = intval($GET['event_id']); //i tried (int)$edit_id; $sqls = "SELECT event_name,start_date,start_time,end_date,end_time,event_venue FROM event WHERE event_id IN $edit_id "; $sqlsr = mysqli_query($con, $sqls); $z = mysqli_fetch_array($sqlsr); { } button and form opens: <form method="post" action="event.php"> <input type="submit" name="edit_event" value="Edit Event"> this is the html where the data will be echoed: <div id="doverlay" class="doverlay"></div> <div id="ddialog" class="ddialog"> <table class="cevent"> <thead><tr><th>Update Event</th></tr></thead> <tbody> <tr> <td> <input type="text" name="en_" value="<?php echo $z['event_name']; ?>"> </td> </tr> <tr> <td> <input type="text" name="dates_" value="<?php echo $z['start_date']; ?>"> <input type="text" name="times_" value="<?php echo $z['start_time']; ?>"> </td> </tr> <tr> <td><input type="text" name="datee_" value="<?php echo $z['end_date']; ?>"> <input type="text" name="time_" value="<?php echo $z['end_time']; ?>"> </td> </tr> <tr> <td><input type="text" name="ev_" value="<?php echo $z['event_venue']; ?>"> </td> </tr> <tr> <td><input type="submit" name="update" value="Update Event" id="update"> <input type="submit" id="cancelupdate" name="cancel" value="Cancel" > </td> </tr> </tbody> </table> </div> this is the part which is populated by data from database where isset($_POST['check']) gets the 'check' from: echo "<tr> <td><input type='checkbox' name='check[]' value='$id'>$name </td> </tr>"; </form> thanks in advance!
  16. I'm working on this quiz. Something has gone wrong with my form though. The page displays a random question but instead of showing 4 different answer options, it repeats one option 4 times. How do should I go about fixing this? <?php SESSION_START(); //Connect to MySQL: $con = new mysqli("localhost", "root", "", "quizproject"); ?> <html> <body> <h1>Hello, <?php echo $_SESSION["fname"]; " " ?> <?php echo $_SESSION["lname"]; ?>.</h1> <p><h2>Quiz Time! Please answer each of the following questions:</h2><br> <?php //retrieve question list: $get_questions = $con->prepare("SELECT question_ID, question FROM questions"); $get_questions->execute(); $get_questions->bind_result($question_ID, $question); $questions = array(); while ($get_questions->fetch()) { $questions[$question_ID] = array($question_ID, $question, array()); } // retrieve answer list: $get_answers = $con->prepare("SELECT id, question_ID, answers, correct FROM answers"); $get_answers->execute(); $get_answers->bind_result($id, $question_ID, $answers, $correct); while ($get_answers->fetch()) { $questions[$question_ID][2][$id] = array($id, $answers, $correct); } // Scramble the array and print: shuffle($questions); ?> <form method="get" action="result.php"> <div class="question"> <label><h2><?php echo $question ?></h2></label> <br> <input type="hidden" name="question<?php echo $question_ID ?>_id" value="<?php echo $question_ID; ?>" id="question<?php echo $question_ID; ?>_id"/> <input name="answer<?php echo $id ?>" id="q<?php echo $id ?>_a1" value="1" type="radio"/> <label for="q<?php echo $id ?>_a1"> <?php echo $answers ?></label><br> <input name="answer<?php echo $id?>" id="q<?php echo $id ?>_a2" value="2" type="radio"/> <label for="q<?php echo $id ?>_a2"> <?php echo $answers ?></label><br> <input name="answer<?php echo $answers ?>" id="q<?php echo $id ?>_a3" value="3" type="radio"/> <label for="q<?php echo $id ?>_a3"> <?php echo $answers ?></label><br> <input name="answer<?php echo $id ?>" id="q<?php echo $id ?>_a4" value="4" type="radio"/> <label for="q<?php echo $id ?>_a4"> <?php echo $answers ?></label><br> </div> <?php echo "<br><input name=\"submit\" type=\"submit\" value=\"Submit\">"; echo "</form></body></html>"; ?> </form> </html> </body>
  17. Hi everyone, I'm studying ICT in Belgium and we have the task to design a website. So I'm working on a website for like parties, events and stuff. So I wrote the following code : <?php $link = mysqli_connect("localhost","root","","partyguide") or die ('Er ging iets mis: ' . mysqli_connect_error($link)); $sql = "SELECT * FROM evenementen"; if(!empty($_POST)) { $sql.="WHERE id='" .$_POST["evenement_datum"]."'"; } $result = mysqli_query($link,$sql); ?> <html> <head> <title>Evenementen</title> </head> <body> <?php if(empty($_POST)) { $link = mysqli_connect("localhost","root","","partyguide") or die ('Er ging iets mis: ' . mysqli_connect_error($link)); ?> <form name="form1" action="<?php echo($_SERVER["PHP_SELF"]);?>" method="post"> Kies een datum : <select name="evenement_datum"> <?php while($rij = mysqli_fetch_array($result)){ echo("<option value=\"".$rij['datum']."\">".$rij['datum']."</option>\n"); }?> </select> <input type="Submit" value="Toon evenementen!"> </form> <?php }else{ ?> <table width="1000" height="500" align="center" border="1" bordercolor="blue"> <?php while($rij = mysqli_fetch_array($result)){ ?> <tr> <td><?php echo $rij['datum']; ?></td> <td><?php echo $rij['plaats']; ?></td> <td><?php echo $rij['tijdstip']; ?></td> <td><?php echo $rij['naam'] ?></td> </tr> <?php } ?> </table> <?php } ?> </body> </html> So I'm trying to have an option box which displays the date's of events in my database, If i click a date, it has to display all the events in a table, but whenever I click one, following error pops up : Catchable fatal error: Object of class mysqli_result could not be converted to string in D:\www\evenementen.php on line 11 Can anyone help me with this? My teacher doesn't know how to solve this so I hope anyone of you could...
  18. Downloaded XAMPP and created MySQL database and table using phpMyAdmin. Inserted rows into table from input form in browser using mysqli. Confirmed data was inserted using browse function in phpMyAdmin. All good. Trouble comes when I try to retrieve data using mysqli and SELECT statement: Here is my code: ********************************************************************************* <?php $con = new MySQLi("localhost", "xxx", "xxx", "xxx"); if ($con === false) { die("ERROR no connexion " . mysqli_connect_error()); } else { echo "<p> Connect was a success </p>"; }; $sql = "SELECT lastName, firstName, email, gender from tab1"; echo "<p>" . $sql ."</p>"; $result = $con -> query($sql); $x = var_export($result, TRUE); echo "<br /><pre>" . $x . "</pre><br />"; echo "hi" . "<br />"; echo "<p>Try to see error" . $con -> error . "</p>"; $con -> close(); ?> ****************************************************************************************************** And here is what I see in the browser *********************************************************************************************************** Connect was a success [so it connected] SELECT lastName, firstName, email, gender from tab1 [the $sql statement] mysqli_result::__set_state(array( 'current_field' => NULL, 'field_count' => NULL, 'lengths' => NULL, 'num_rows' => NULL, 'type' => NULL, )) hi Try to see error [No error apparently] ************************************************************************************************************ Nothing in result Works fine with INSERT Fails with SELECT All tips, suggestions welcome.
  19. Hi I'm Steven, 68 yo from Melbourne, Australia. Very - and I mean VERY - new to PHP. Need to retrain for a new career. Posted a query elsewhere
  20. im using the following to get get the followers of currently viewing user, but when i run this code , it gives me over 20000 times same username which is the only one who following that user ; really need help my head is not working ,,, i have tried to use inner join but not working (or i don't know how to make it work). code : <?php $stmt = $mysqli->prepare("SELECT follow_id from follow_user WHERE id= ?"); $stmt->bind_param('s', $viewuser); // Bind "$user_id" to parameter. $stmt->execute(); // Execute the prepared query. $stmt->store_result(); $stmt->bind_result($follow_id); // get variables from result. while($stmt->fetch()) { $stmt = $mysqli->prepare("SELECT id,username,profilepic from members WHERE id= ? LIMIT 1"); $stmt->bind_param('s', $follow_id); // Bind "$user_id" to parameter. $stmt->execute(); // Execute the prepared query. $stmt->store_result(); if($stmt->num_rows == 1) { $stmt->bind_result($id,$followusername,$followpic); // get variables from result. } ?> <?php echo $followusername; ?> <?php } ?>
  21. so what im doing is ; im trying to get the rows from database with my following php code , and display them like ; <?php echo $col;?> , but its not working and giving me a blank result , a help would be greate thanks : <?php $stmt = $mysqli->prepare("SELECT * FROM `movies` ORDER BY `date` DESC LIMIT 0, 4"); $stmt->execute(); // Execute the prepared query. $stmt->store_result(); if($stmt->num_rows == 1) { $stmt->bind_result($id,$title,$poster,$date); // get variables from result. $stmt -> fetch(); } ?>
  22. Hey, Wrote I quick script to filter results from database. It kinda works but not sure if this is best or even secure way to do it. I know mysqli has function 'bind_params', but failed to make it work. <form action="" method="get"> <input type="checkbox" name="data" value="3" /> <input type="submit" /> <?php if( empty($_GET['data']) ) { die("GET empty"); } $mysqli = new mysqli('localhost', 'user', 'password', 'database'); $statement = "SELECT * FROM table1 WHERE id=" . $_GET['data']; $result = $mysqli->query($statement); while( $row = $result->fetch_assoc() ) { echo $row['id']; echo "<br/>"; echo $row['text']; if ($row['img'] != NULL) echo "<img src=" . $row['img'] . " > "; } ?> So just basic checkbox interface, when selected one of checkboxes and submitted, script queries database with matching ID from GET, returns results and loops through them. Inside loop checks for associated image src, if not present ignores field. I want to use this fucntions logic in my project but not sure if secure nor best/easiest way to do this. Obviously will improve interface, naming of variables etc.
  23. Hello Forumites!! I would like to ask a bit of advice please. I am currently writing a peice of code where my user can add content to their database and retreive it from the database when they view it live on the website. I want them to be able to edit their content and this my friends is wherein the problem lies. This is my Edit code: <?php function editnews($i) { $conn = mysqli_connect("Connection Stringy Stuff"); $enquery = "SELECT * FROM news WHERE newsid=$i"; $enresult = mysqli_query($conn, $enquery) or trigger_error("Query Failed! SQL: $conn - Error: ".mysqli_error(), E_USER_ERROR); while ($enrow = mysqli_fetch_array($enresult)) { echo " <form enctype='multipart/form-data' action='newsedit.php' method='post'> <table> <tr> <td>News Ref:</td> <td>" . $i . "<input type='hidden' name='newsid' value='" . $i . "' /><input type='hidden' name='oldim' value='" . $enrow['newsimage'] . "' /></td> </tr> <tr> <td>Title:</td> <td><input type='text' name='title' value='" . $enrow['newstitle'] . "' size='100' /></td> </tr> <tr> <td>Author:</td> <td><input type='text' name='author' value='" . $enrow['newsauthor'] . "' size='100' /></td> </tr> <tr> <td>Status:</td> <td><select name='stat'><option value='enabled' "; if ($enrow['newstatus'] == "enabled") { echo "selected='selected' "; } echo ">Enabled</option><option value='disabled' "; if ($enrow['newsstatus'] == "disabled") { echo "selected='selected' "; } echo "}>Disabled</option></select> </td> </tr> <tr> <td>Snippettext:</td> <td><textarea name='snip' rows='6' cols='80'>" . $enrow['newssnippet'] . "</textarea></td> </tr> <tr> <td>News story:</td> <td><textarea name='stry' rows='20' cols='80'>" . $enrow['newsarticle'] . "</textarea></td> </tr> <tr> <td>Current image:</td> <td>" . $enrow['newsimage'] . " - <a href='news/" . $enrow['newsimage'] . "' target='_blank'>View Image</a></td> </tr> <tr> <td>Change Image:</td> <td><input type='file' name='file'></td> </tr> <tr> <td colspan='2'><input type='submit' name='submit' value='Edit' /></td> </tr> </table> </form> "; } } ?> This code displays on the 'Edit' page using the following above the DOC type: <?php include('functions/newseditform.php'); $i = $_GET['i']; ?> AND the following in the HTML: <?php editnews($i) ?> The problem I have however is that the code at the top, does not actually display anything on the html page I have debugged the code in my IDE and received these error messages: Notice: Undefined index: i in pathway on Line 3 (This is the bit at the top of the 'Edit' page) AND Catchable fatal error: Object of class mysqli could not be converted to string in 'pathway' on line 8 this being this line of the edit code: $enresult = mysqli_query($conn, $enquery) or trigger_error("Query Failed! SQL: $conn - Error: ".mysqli_error(), E_USER_ERROR); Before I added the 'trigger_error' bit, it was displaying the "Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given" error. If anyone can help point out where I went wrong I would be very appreciative. Thanks!!!
  24. I've been banging my head on a wall for 30 hours over this! What I am trying to do seems so simple. I have a couple of views, a profile overview type of page and an edit profile page. After verifying your account with an email link my site brings you to a blank-ish profile page and you have to follow another link from there to update your profile. It's just not as slick as I'd like it to be before launch and allows other functionality to be available before your profile has any content. I don't like it. I created a specific "Create Your Profile" view that I want to include only if a user_id hasn't been included in the profilemaster table. All that I have left to do is check to see if my session user_id exists in my profilemaster table and if it does include the old profile page and if it doesn't include the new "Create Your Profile" page. I have tried everything over and over and then got beat up by the people at stack on top of it. I need some direction. I might just be tired, I've been working on the site for a solid week. All of my other functions are working, data can be inserted and updated, my emails are flowing when they need to, my log in is safe. I'm befuddled. Thanks if you have any suggestions! Justin
  25. i want to retrieve username from database table and display it where i put the code $username , i'm using the following code to make it work but its giving me an error : <?php require_once("models/config.php"); if (!securePage($_SERVER['PHP_SELF'])){die();} require("models/db-settings.php"); $mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name); $result = $mysqli->query("SELECT user_name FROM upl_users"); // This will move the internal pointer and skip the first row, we don't want that. //$row = mysql_fetch_assoc($result); //echo $row['user_name']; while ( $row = $result->fetch_assoc() ) { $username = $row['user_name'];} $dir = 'uploads/$username/'; if (file_exists($UploadedDirectory)) { mkdir('uploads/$username/', 0777, true); } if(isset($_FILES['FileInput']) && $_FILES['FileInput']['error']== UPLOAD_ERR_OK) { ############ Edit settings ############## $UploadDirectory = 'uploads/$username/'; //specify upload directory ends with / (slash) ########################################## /* Note : You will run into errors or blank page if "memory_limit" or "upload_max_filesize" is set to low in "php.ini". Open "php.ini" file, and search for "memory_limit" or "upload_max_filesize" limit and set them adequately, also check "post_max_size". */ //check if this is an ajax request if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){ die(); } //Is file size is less than allowed size. if ($_FILES["FileInput"]["size"] > 5242880) { die("File size is too big!"); } //allowed file type Server side check switch(strtolower($_FILES['FileInput']['type'])) { //allowed file types case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg': case 'text/plain': case 'text/html': //html file case 'application/x-zip-compressed': case 'application/pdf': case 'application/msword': case 'application/vnd.ms-excel': case 'video/mp4': case 'audio/mp3'; break; default: die('Unsupported File!'); //output error } $File_Name = strtolower($_FILES['FileInput']['name']); $File_Ext = substr($File_Name, strrpos($File_Name, '.')); //get file extention $Random_Number = uniqid(); //Random number to be added to name. $NewFileName = $Random_Number.$File_Ext; //new file name if(move_uploaded_file($_FILES['FileInput']['tmp_name'], $UploadDirectory.$NewFileName )) { die(' Success! File Uploaded.'); }else{ die('error uploading File!'); } } else { die('Something wrong with upload! Is "upload_max_filesize" set correctly?'); } ?> error: it creates the folder named : $username and not retirieves it from database , if i'm logged in and i upload a file then script need to create a folder with my name : admin ; uploads/admin/file.jpg but it makes ; uploads/$username/file.jpg any help thanks in advance
×
×
  • 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.