Jump to content

Search the Community

Showing results for tags 'mysqli'.

More search options

  • 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 (Dreamweaver, Zend, 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

Found 47 results

  1. HI All Not sure how best to describe what i am trying to do so here goes. People use my system to order food from a menu - this is not for a restaurant where you order one starter main and desert, they will be ordering 00's of meals. The table layout is as follows: ssm_menu menu_id | menu_name | menu_price ssm_menu_connection menu_id | menu_item_id | surrogate_id ssm_menu_items menu_item_id | menu_item_name | menu_item_category ssm_menu_order job_id | menu_id | menu_item_id | menu_item_qty Menu items can appear on more than one menu. If a user orders 100 of menu_item_id 1, 2 & 3 these appear on menu_id 1& 2 Menu_id 1 only contains item_id 1, 2, 3 Menu_id 2 contains menu_item 1,2,3,4,5,6,7,8,910 when querying the database, i would like the menu_id to comeback as 1 as all of the items appear on this menu and out of all available menu items the higher percentage have been picked from this menu than menu_id 2. So on menu_id 1 = 100% of the available menu_item_id have been given a menu_item_qty but on menu_id 2, only 30% of the available menu_item_id have been selected. the sql that i have started with is the following: select menu_name from ssm_menu a inner join ssm_menu_connection b on a.menu_id = b.menu_id inner join ssm_menu_items c on b.menu_item_id = c.menu_item_id inner join ssm_menu_order d on c.menu_item_id = d.menu_item_id where job_id = 27 The result of this is: Menu One, Menu One, Menu One, Menu Two, Menu Two, Menu Two I hope this is enough information to shed some light on what i am trying to achieve and appreciate any feedback in advance. Kind Regards Adam
  2. I have 3 staff members that need to pick vacation in a certain order. Each have X weeks vacation and can pick off a calendar their choice 1-3 weeks per round. I'm trying to loop through the DB to find who is next to pick with weeks left ~~~~~~First round of picking~~~~~~ STAFF 1 - PICK ORDER 1 - 3 weeks available STAFF 2 - PICK ORDER 2 - 5 weeks available STAFF 3 - PICK ORDER 3 - 3 weeks available Staff 1 takes 2 Weeks Staff 2 takes 1 Weeks Staff 3 takes 3 Weeks ~~~~~~Second round of picking~~~~~~ STAFF 1 - PICK ORDER 1 - 1 weeks available STAFF 2 - PICK ORDER 2 - 4 weeks available STAFF 3 - PICK ORDER 3 - No weeks left Staff 1 takes 1 Weeks Staff 2 takes 3 Weeks Staff 3 Skipped ~~~~~~Third round of picking~~~~~~ STAFF 1 - PICK ORDER 1 - No weeks left STAFF 2 - PICK ORDER 2 - 1 weeks available STAFF 3 - PICK ORDER 3 - No weeks left Staff 1 Skipped Staff 2 takes 1 Weeks Staff 3 Skipped ~~~~~~~~~~~~ All staff 0 weeks left end --calendar.php-- $year=2020; $sql = "SELECT * FROM vac_admin WHERE pick_year='$year'; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { $row_admin = mysqli_fetch_assoc($result); } $current_pick_staff = $row_admin['current_pick_staff']; $sql = "SELECT * FROM vac_pick_order WHERE pick_year='$year' && pick_order = '$current_pick_staff'"; $result = mysqli_query($conn, $sql); $row = mysqli_fetch_assoc($result); if($row['vac_c_counter'] < 0){ $emp_num = $row['emp_num']; }ELSE{ ?????????????????? goto next staff with weeks > 0 ?????Somthing like if ($current_pick_staff == 3){ $current_pick_staff = 1; }ELSE{ $current_pick_staff++; } ?????????????????? } ~<FORM>~~~~~~~~~~~~~~~~~~~~~ Staff with $emp_num can now pick ~~~~~~ $_POST -> $date = XXXX-XX-XX; $num_weeks = X; $emp_num; ~</FORM>~~~~~~~~~~~~~~~~~~~~~ --process.php-- $year = 2020; $date = $_POST['date']; $num_weeks = $_POST['num_weeks']; $emp_num = $_POST['emp_num']; $sql = "INSERT INTO vac_picks (pick_year,emp_num,date) VALUES ($year,$emp_num,$date)"; $sql = "UPDATE vac_pick_order SET vac_c_counter=vac_c_counter - $num_weeks WHERE emp_num='$emp_num'; $sql = "UPDATE vac_admin SET pick_order=pick_order +1 WHERE pick_year='$year' ; Then back to calendar.php until all weeks gone.
  3. Hello everyone, I am trying to submit a comment in a comment box and send it to the DB but is not happening. The connection is good as I am logging in and all but no data is sent to the DB when I post the comment. It doesn't show in my comment section either. Form <!--comment section--> <?php if(isset($_SESSION['id'])) { echo "<form method='POST' action='" . setComments($conn) . "'> <input type='hidden' name='uidUsers' value='".$_SESSION['id']."'> <input type='hidden' name='posted' value='" . date('Y-m-d H:i:s') . "'> Comments: <textarea rows = '5' cols = '15' name='body'></textarea><br><br> <button name='commentSubmit' type='submit'>Comment</button> </form>"; }else { echo "Log in to comment!"; } getComments($conn); Function to set and get comments function setComments($conn) { if (isset($_POST['commentSubmit'])){ $user_id = $_POST['uidUsers']; $body = $_POST['body']; $posted = $_POST['posted']; $sql = "INSERT INTO comments (uidUsers, posted, body) VALUES ('$user_id', '$posted', '$body')"; $result = mysqli_query($conn, $sql); } } function getComments($conn) { $sql = "SELECT * FROM comments"; $result = mysqli_query($conn, $sql); while ($row = $result->fetch_assoc()){ $id = $row['uidUsers']; $sql2 ="SELECT * FROM users WHERE uidUsers='$id'"; $result2 = mysqli_query($conn, $sql2); if($row2 = $result2->fetch_assoc()){ echo "<div class='comment-box'><p>"; echo $row2['uidUsers'] . "<br>"; echo $row['posted'] . "<br>"; echo nl2br($row['body']); echo "</p></div>"; } } }
  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. 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!
  6. If anyone could help, I'm not getting an error message and I've tried changing the code around a few times and outputting errors. The database does not update and i'm getting no error message output on submit, I assume i'm missing something? <?php session_start(); include_once 'dbconnect.php'; if (!isset($_SESSION['userSession'])) { header("Location: index.php"); } $query = $DBcon->query("SELECT * FROM tbl_users WHERE user_id=".$_SESSION['userSession']); $userRow=$query->fetch_array(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Welcome - <?php echo $userRow['email']; ?></title> <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen"> <link href="bootstrap/css/bootstrap-theme.min.css" rel="stylesheet" media="screen"> <link rel="stylesheet" href="style.css" type="text/css" /> </head> <?php include_once 'header.php'; ?> <html> <head></head> <body> <h1>Send Message:</h1> <form action='message.php' method='POST'> <table> <tbody> <tr> <td>To: </td><td><input type='text' name='to' /></td> </tr> <tr> <td>From: </td><td><input type='text' name='from' /></td> </tr> <tr> <td>Message: </td><td><input type='text' name='message' /></td> </tr> <tr> <td></td><td><input type='submit' value='Create Task' name='sendMessage' /></td> </tr> </tbody> </table> </form> </body> </html> <?php if (isSet($_POST['sendMessage'])) { if (isSet($_POST['to']) && $_POST['to'] != '' && isSet($_POST['from']) && $_POST['from'] != '' && isSet($_POST['message']) && $_POST['message'] != '') { $to = $_POST['to']; $from = $userRow['email']; $message = $_POST['message']; $q = "INSERT INTO tbl_messages(id,message,to,from) VALUES('', '$message', '$to', '$from')"; if ($DBcon->query($q)) { $msg = "<div class='alert alert-success'> <span class='glyphicon glyphicon-info-sign'></span> Message Sent ! </div>"; }else { $msg = "<div class='alert alert-danger'> <span class='glyphicon glyphicon-info-sign'></span> Message not Sent! ! </div>"; } } } $DBcon->close();?> <?php php include_once 'footer.php'; ?> </html>
  7. Hi! I'm new at php and I need a help with this code I need to Search an employee from a Database that I already have I have the Search Form and I write the name and the lastname and the details of the employee appear, But I need help. I already have the search, but I tells me when I call the query that I have a fatal error Trying to get property of non-object in in this part of the code $count = $query -> num_rows;and this Fatal error: Call to undefined method EmployeeModel::searchEmployees() in here $employees = $this->model->searchE($_GET['str']); require_once('views/search.php'); where I need to call this function in search.php I'm gonna leave my search.php I need a big help here I'm gonna be really thankfull <form method="get" action="index.php" name="searchform" id="searchform"> <input type="text" name="str" id="str"> <input type="submit" name="submit" id="submit" value="Search"> </form> <?php /*class SearchE {*/ $user = "root"; $password = ""; $host = "localhost"; $dbase = "employees_assign"; $table = "tbl_employees"; $search_term= isset($_GET['str']) ? $_GET['str'] : ''; /*mysqli_connect($host,$user,$password); @mysqli_select_db($dbase) or die("Unable to select database");*/ $connect = mysqli_connect('localhost','root','','employees_assign'); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $sql = "SELECT * FROM tbl_employees WHERE emp_fname LIKE '%$search_term%' OR emp_lnames LIKE '%$search_term%'"; //$query = mysqli_query($connect,$sql); $query = $connect ->query($sql); //$count= mysqli_num_rows(mysqli_result $query); $count = $query -> num_rows; //$count=$query->num_rows; /*if ($query === false) { error_log($connect->error); die("something failed."); }*/ if ($count == 0) { echo "<fieldset><b>No Results Found for Search Query '$search_term'</b></fieldset>"; } else { print "<table border=1>\n"; while ($row = mysqli_fetch_array($query)){ $emp_fname= $row['emp_fname']; $emp_lname= $row['emp_lname']; print "<tr>\n"; print "</td>\n"; print "\t<td>\n"; print "<font face=arial size=4/><div align=center>$emp_fname</div></font>"; print "</td>\n"; print "\t<td>\n"; echo "<font face=arial size=4/>$emp_lname</font>"; print "</td>\n"; print "</tr>\n"; } print "</table>\n"; } /*}*/ ?>
  8. 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?
  9. 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();
  10. 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.
  11. Hi guys, I am trying to display data to a user who submitted it. So, user A submits data to the db and also user B. I want it so that user A cannot see user B's data but only the data they have submitted. Hope that makes sense. Here is the code along with the table of data to be displayed. <div class="panel-body"> <div class="table-responsive"> <table class="table table-striped table-bordered table-hover" id="bookings_table"> <thead> <tr> <th class="text-center">Issue ID</th> <th class="text-center">Driver Name</th> <th class="text-center">Date Submitted</th> <th class="text-center">Fleet Number</th> <th class="text-center">Issue</th> <th class="text-center">Description</th> <th class="text-center">Priority</th> <th class="text-center">Status</th> </tr> </thead> <tbody> <?php $check = isset($_SESSION['username']); if($stmt = $link -> prepare("SELECT issue_id, driver_name, submit_date, fleet_number, issue_name, issue_description, issue_priority, issue_status FROM maintenance_requests WHERE username = ?")) { $stmt -> execute(); $stmt -> bind_result($issue_id, $driver_name, $submit_date, $fleet_number, $issue_name, $issue_description, $issue_priority, $issue_status); while($stmt->fetch()) { ?> <tr class="odd gradeX"> <td class="text-center"><?php echo $issue_id; ?></td> <td class="text-center"><?php echo $driver_name; ?></td> <td class="text-center"><?php echo $submit_date; ?></td> <td class="text-center"><?php echo $fleet_number; ?></td> <td class="text-center"><?php echo $issue_name; ?></td> <td class="text-center"><?php echo $issue_description; ?></td> <td class="text-center"><?php echo $issue_priority; ?></td> <?php if($issue_status == "Pending") { ?> <td class="text-center warning"><?php echo $issue_status;?></td> <?php }else if($issue_status == "Open"){ ?> <td class="text-center danger"><?php echo $issue_status; ?></td> <?php }else if($issue_status == "Repaired"){ ?> <td class="text-center success"><?php echo $issue_status ;} ?></td> </tr> <?php } $stmt -> close(); } mysqli_close($link); ?> If I remove the WHERE clause, it displays data from both users. Placing the WHERE clause shows no data. Can someone have a look and see where I am going wrong and maybe point me in the right direction? Many thanks in advance.
  12. $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
  13. 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?
  14. 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.
  15. 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.
  16. 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!
  17. 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
  18. Hello my good people I'm doing a content manager system in PHP and mySQLi, following a serie of video tutorials. But in my project I am using a tree menu. In the front office all works smoothly (the tree menu displays all results - menu and submenus - and each button carries the information of the respective page). The problem is in the back office. The menu is there, in the url appears its id page but the CRUD, I can not put it to work. ======= CODE START ======= <!-- Gestor de Conteúdos Start --> <div class="container-fluid"> <!-- Conteúdo Fluido Start --> <div class="row-fluid row-offcanvas row-offcanvas-left"> <?php // INSERT QUERY if(isset($_POST['enviado']) == 1) { $header = mysqli_real_escape_string($dbc, $_POST['header']); $url = mysqli_real_escape_string($dbc, $_POST['url']); $user = $_POST['user']; $idPai = $_POST['idPai']; $menuNomePT = mysqli_real_escape_string($dbc, $_POST['menuNomePT']); $conteudo_pagina_PT = mysqli_real_escape_string($dbc, $_POST['conteudo_pagina_PT']); $menuNomeEN = mysqli_real_escape_string($dbc, $_POST['menuNomeEN']); $conteudo_pagina_EN = mysqli_real_escape_string($dbc, $_POST['conteudo_pagina_EN']); $q = "INSERT INTO menuCAL (header, url, user, idPai, menuNomePT, conteudo_pagina_PT, menuNomeEN, conteudo_pagina_EN) VALUES ('$header', '$_POST[url]', $_POST[user], '$_POST[idPai], '$menuNomePT, '$conteudo_pagina_PT', '$menuNomeEN', '$conteudo_pagina_EN'"; $r = mysqli_query($dbc, $q); ?> <div> <?php if($r) { $message = '<p>A página foi adicionada!</p>'; } else { $message = '<p>A página não foi adicionada, devido ao seguinte erro: '.mysqli_error($dbc); $message .= '<p>' .$q.'</p>'; } ?> </div> <?php } ?> <!-- Menu CAL Start --> <div class="col-sm-3 sidebar-offcanvas"> <?php //call the recursive function to print category listing category_tree(0); //Recursive php function function category_tree($menuPai){ global $dbc; $q = "SELECT * FROM menuCAL WHERE idPai ='".$menuPai."'"; $r = mysqli_query($dbc, $q); while($btnMenu = mysqli_fetch_assoc($r)): $i = 0; if ($i == 0) echo '<ul class="menuCAL">'; echo '<li><a href="?page='.$btnMenu['id'],'">' . $btnMenu['GlyPrincipal'] . $btnMenu['GlySecundario'] . $btnMenu['menuNomePT'], '</a>'; category_tree($btnMenu['id']); echo '</li>'; $i++; if ($i > 0) echo '</ul>'; endwhile; } ?> </div> <!-- Menu CAL End --> <!-- Conteúdo Start --> <div class="span10"> <div class="col-sm-12"> <!-- Título Start --> <h1 class="page-header"> <i class="fa fa-file"></i> Adicionar Página </h1> <ol class="breadcrumb"> <li> <a href="#"><i class="fa fa-pencil"></i> Conteúdos</a> </li> <li class="active"> <i class="fa fa-file"></i> Nova página </li> </ol> <!-- Título End --> </div> <!-- Textos & Formulários Start --> <div class="row"> <div class="col-lg-12"> <p><?php if(isset($message)) { echo $message; } ?></p> <?php // SELECT QUERY if(isset($_GET['id'])) { $q = "SELECT * FROM menuCAL WHERE id = $_GET[id]"; $r = mysqli_query($dbc, $q); $opened = mysqli_fetch_assoc($r); } ?> <!-- Formulário Start --> <form action="adicionar_pagina.php" method="post" role="form"> <!-- Campo header Start --> <div class="form-group"> <label for="header">Header:</label> <input type="text" class="form-control" name="header" id="header" value="<?php echo $opened['header']; ?>" placeholder="Texto descritivo a colocar no topo do website"> </div> <!-- Campo header End --> <!-- Campo Label Start --> <div class="form-group"> <label for="url">URL:</label> <input type="text" class="form-control" name="url" id="url" value="<?php echo $opened['url']; ?>" placeholder="Texto a colocar na URL (SEO)"> </div> <!-- Campo Label End --> <!-- Campo User Start --> <div class="form-group"> <label for="user">Administrador:</label> <select class="form-control" name="user" id="user"> <option value="0">›› Nenhum administrador</option> <?php $q = "SELECT id FROM users ORDER BY first ASC"; $r = mysqli_query ($dbc, $q); while ($user_list = mysqli_fetch_assoc($r)) { $user_data = data_user($dbc, $user_list['id']); ?> <option value="<?php echo $user_data['id'] ?>" <?php if($user_data['id'] == $opened['id']) { echo 'selected';} ?>><?php echo $user_data['fullname']; ?></option> <?php } ?> </select> </div> <!-- Campo User Start --> <!-- Campo ID Menu Pai Start --> <div class="form-group"> <label for="idPai">Adicionar a:</label> <select class="form-control" name="idPai" id="idPai"> <option value="0">›› Seleccione onde adicionar a nova página:</option> <?php $q = "SELECT menuNomePT FROM menuCAL WHERE idPai = 0"; $r = mysqli_query ($dbc, $q); while ($submenus = mysqli_fetch_assoc($r)) { ?> <option value="<?php echo $submenus['idPai']; ?>"><?php echo $submenus['menuNomePT']; ?></option> <?php } ?> </select> </div> <!-- Campo ID Menu Pai Start --> <!-- Campo menuNomePT Start --> <div class="form-group"> <label for="menuNomePT">Título PT:</label> <input type="text" class="form-control" name="menuNomePT" id="menuNomePT" value="<?php echo $opened['menuNomePT']; ?>" placeholder="Insira o título em Português"> </div> <!-- Campo menuNomePT End --> <!-- Campo conteudo_pagina_PT Start --> <div class="form-group"> <label for="conteudo_pagina_EN">Conteúdos PT:</label> <textarea class="form-control" name="conteudo_pagina_PT" rows="12" id="conteudo_pagina_PT" placeholder="Insira os textos em Português"><?php echo $opened['conteudo_pagina_PT']; ?></textarea> </div> <!-- Campo conteudo_pagina_PT End --> <!-- Campo menuNomeEN Start --> <div class="form-group"> <label for="menuNomeEN">Título EN:</label> <input type="text" class="form-control" name="menuNomeEN" id="menuNomeEN" value="<?php echo $opened['menuNomePT']; ?>" placeholder="Insira o título em Inglês"> </div> <!-- Campo menuNomeEN End --> <!-- Campo conteudo_pagina_EN Start --> <div class="form-group"> <label for="conteudo_pagina_EN">Conteúdos EN:</label> <textarea class="form-control" name="conteudo_pagina_EN" rows="12" id="conteudo_pagina_EN" placeholder="Insira os textos em Inglês"><?php echo $opened['conteudo_pagina_PT']; ?></textarea> </div> <!-- Campo conteudo_pagina_EN End --> <button type="submit" class="btn btn-default adic_concluir">Gravar</button> <input type="hidden" name="enviado" value="1"> </div> </form> <!-- Formulário End --> </div> <!-- Debug Panel Start --> <?php if($debug == 1) { include('widgets/debug.php'); } ?> <!-- Debug Panel End --> </div> <!-- Textos & Formulários End --> </div> <!-- Conteúdo End --> </div> <!-- Conteúdo Fluido Start --> </div> <!-- Gestor de Conteúdos End --> ======= CODE END ======= I can not do the INSERT or UPDATE query, using the form so that the "user" and the "idPai" (a category id), can be created or changed in the database. I tried to echo the database result, but nothing append And in the second query (in red in the code), gives me an error (Undefined variable: opened in …). Obviously something is wrong, but i can't see what! :/ The database: Can Someone help me? Please !! Thank U
  19. Hi guys and Gals, This has my head wrecked to be honest. I am trying to upload an image to a directory, which is working. However, I also want to put the file name into MySQL. This will work if the image upload script is removed. With the script enabled, the file uploads but I get "Undefined index: userPic" from the following line: $userPic = mysqli_real_escape_string($mysqli, $_POST['userPic']); Here is the complete code: if(isset($_POST['Submit'])){//if the submit button is clicked $company_name = mysqli_real_escape_string($mysqli, $_POST['company_name']); $company_abn = mysqli_real_escape_string($mysqli, $_POST['company_abn']); $company_email = mysqli_real_escape_string($mysqli, $_POST['company_email']); $address = mysqli_real_escape_string($mysqli, $_POST['address']); $company_phone = mysqli_real_escape_string($mysqli, $_POST['company_phone']); $company_slogan = mysqli_real_escape_string($mysqli, $_POST['company_slogan']); $userPic = mysqli_real_escape_string($mysqli, $_POST['userPic']); // Upload Image if (isset($_FILES["userPic"]["name"])) { $name = $_FILES["userPic"]["name"]; $tmp_name = $_FILES['userPic']['tmp_name']; $error = $_FILES['userPic']['error']; if (!empty($name)) { $location = 'uploads/'; if (move_uploaded_file($tmp_name, $location.$name)){ echo 'Uploaded'; } } else { echo 'please choose a file'; } } $sql="UPDATE company_settings SET company_name='$company_name', company_slogan='$company_slogan', company_abn='$company_abn', company_email='$company_email', address='$address', company_phone='$company_phone', userPic='$userPic'"; $mysqli->query($sql) or die("Cannot update");//update or error } Has anyone got any ideas where I am going wrong (besides not using PDO) and how I can solve it? Thanks in advance.
  20. how i can make a insert using this fuctions I m learning php, as using this functions (mysqli abstract) but after update wont work any more. /** insert data array */ public function insert(array $arr) { if ($arr) { $q = $this->make_insert_query($arr); $return = $this->modifying_query($q); $this->autoreset(); return $return; } else { $this->autoreset(); return false; } } complement /** insert query constructor */ protected function make_insert_query($data) { $this->get_table_info(); $this->set_field_types(); if (!is_array(reset($data))) { $data = array($data); } $keys = array(); $values = array(); $keys_set = false; foreach ($data as $data_key => $data_item) { $values[$data_key] = array(); $fdata = $this->parse_field_names($data); foreach ($fdata as $key => $val) { if (!$keys_set) { if (isset($this->field_type[$key])) { $keys[] = '`' . $val['table'] . '`.`' . $val['field'] . '`'; } else { $keys[] = '`' . $val['field'] . '`'; } } $values[$data_key][] = $this->escape($val['value'], $this->is_noquotes($key), $this->field_type($key), $this->is_null($key), $this->is_bit($key)); } $keys_set = true; $values[$data_key] = '(' . implode(',', $values[$data_key]) . ')'; } $ignore = $this->ignore ? ' IGNORE' : ''; $delayed = $this->delayed ? ' DELAYED' : ''; $query = 'INSERT' . $ignore . $delayed . ' INTO `' . $this->table . '` (' . implode(',', $keys) . ') VALUES ' . implode(',', $values); return $query; } before update this class i used to insert data like this $db = Sdba::table('users'); $data = array('name'=>'adam'); $db->insert($data); this method of insert dont works on new class. if i try like this i got empty columns and empty values. thanks for any help complete class download http://goo.gl/GK3s4E
  21. 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 } ?>
  22. I created a recipe site that displays various dishes, and I'm tickled pink that I got it to work (first time doing this!) But I'd like to have pages that displays dishes by its category. The column that houses this is called "category" which has 7 total: Appetizers & Beverages, Soups & Salads, Side Items, Main Dishes, Baked Goods, Desserts, and Cookies & Candy. I have this page connected to a "connection.php" page, but here's the code in question: <!-- Page Title--> <div class="row"> <div class="col-lg-12"> <h1 class="page-header">Appetizers & Beverages</h1> </div> </div> <!-- /Page Title --> <!-- Displayed Data--> <?php $sql = "SELECT id, category, bilde, title FROM oppskrift_table ORDER BY title "; $result = mysqli_query($con, $sql); if(mysqli_num_rows($result) > 0 ){ while($row = mysqli_fetch_assoc($result)){ ?> <div align="center" class="col-md-3"> <a href="#"> <img class="img-responsive img-cat" src="bilder/rBilder/<?=$row['bilde']?>" width="250" alt=""> </a> <h4 style="max-width:250px;"> <a href="#" class="dishes"> <?=$row['title']?> </a> </h4> </div> <?php } } ?> <!-- END Displayed Data--> </div> How can I tweak this so that only the category Appetizers & Beverages shows up on the page?
  23. 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; }
  24. I'm a beginner here and i am learning the basic in converting from MySQL to MySQLi. I am currently working on this registration page which I would want to convert to MySQLi. Please advise me how to modify this script, I would prefer the procedural style. The MySQLi coding is not working because it would notg insert into the database like the MySQL coding would, would appreciate if your can help me. MYSQL <?php error_reporting(1); $submit = $_POST['submit']; //form data $name = mysql_real_escape_string($_POST['name']); $name2 = mysql_real_escape_string($_POST['name2']); $email = mysql_real_escape_string($_POST['email']); $password = mysql_real_escape_string($_POST['password']); $password2 = mysql_real_escape_string($_POST['password2']); $email2 = mysql_real_escape_string($_POST['email2']); $address = mysql_real_escape_string($_POST['address']); $address2 = mysql_real_escape_string($_POST['address2']); $address3 = mysql_real_escape_string($_POST['address3']); $address4 = mysql_real_escape_string($_POST['address4']); $error = array(); if ($submit) { //open database $connect = mysql_connect("localhost", "root", "Passw0rd") or die("Connection Error"); //select database mysql_select_db("logindb") or die("Selection Error"); //namecheck $namecheck = mysql_query("SELECT * FROM users WHERE email='{$email}'"); $count = mysql_num_rows($namecheck); if($count==0) { } else { if($count==1) { $error[] = "<p><b>User ID taken. Try another?</b></p>"; } } //check for existance if($name&&$name2&&$email&&$password&&$password2&&$email2&&$address&&$address2&&$address3&&$address4) { if(strlen($password)< { $error[] = "<p><b>Password must be least 8 characters</b></p>"; } if(!preg_match("#[A-Z]+#",$password)) { $error[] = "<p><b>Password must have at least 1 upper case characters</b></p>"; } if(!preg_match("#[0-9]+#",$password)) { $error[] = "<p><b>Password must have at least 1 number</b></p>"; } if(!preg_match("#[\W]+#",$password)) { $error[] = "<p><b>Password must have at least 1 symbol</b></p>"; } //encrypt password $password = sha1($password); $password2 = sha1($password2); if($_POST['password'] != $_POST['password2']) { $error[] = "<p><b>Password does not match</b></p>"; } //rescue email match check if($_POST['email2'] == $_POST['email']) { $error[] = "<p><b>Rescue Email must not be the same as User ID</b></p>"; } //generate random code $random = rand(11111111,99999999); //check for error messages if(isset($error)&&!empty($error)) { implode($error); } else { //Registering to database $queryreg = mysql_query("INSERT INTO users VALUES ('','$name','$name2','$email','$password','$password2','$email2','$address','$address2','$address3','$address4','$random','0')"); $lastid = mysql_insert_id(); echo "<meta http-equiv='refresh' content='0; url=Activate.php?id=$lastid&code=$random'>"; die (); } } } ?> MYSQLi (NOT WORKING AFTER CONVERTING) <?php error_reporting(1); $submit = $_POST['submit']; //form data $name = mysqli_real_escape_string($connect, $_POST['name']); $name2 = mysqli_real_escape_string($connect, $_POST['name2']); $email = mysqli_real_escape_string($connect, $_POST['email']); $password = mysqli_real_escape_string($connect, $_POST['password']); $password2 = mysqli_real_escape_string($connect, $_POST['password2']); $email2 = mysqli_real_escape_string($connect, $_POST['email2']); $address = mysqli_real_escape_string($connect, $_POST['address']); $address2 = mysqli_real_escape_string($connect, $_POST['address2']); $address3 = mysqli_real_escape_string($connect, $_POST['address3']); $address4 = mysqli_real_escape_string($connect, $_POST['address4']); $error = array(); if ($submit) { //open database $connect = mysqli_connect("localhost", "root", "Passw0rd", "logindb") or die("Connection Error"); //namecheck $namecheck = mysqli_query($connect, "SELECT * FROM users WHERE email='{$email}'"); $count = mysqli_num_rows($namecheck); if($count==0) { } else { if($count==1) { $error[] = "<p><b>User ID taken. Try another?</b></p>"; } } //check for existance if($name&&$name2&&$email&&$password&&$password2&&$email2&&$address&&$address2&&$address3&&$address4) { if(strlen($password)< { $error[] = "<p><b>Password must be least 8 characters</b></p>"; } if(!preg_match("#[A-Z]+#",$password)) { $error[] = "<p><b>Password must have at least 1 upper case characters</b></p>"; } if(!preg_match("#[0-9]+#",$password)) { $error[] = "<p><b>Password must have at least 1 number</b></p>"; } if(!preg_match("#[\W]+#",$password)) { $error[] = "<p><b>Password must have at least 1 symbol</b></p>"; } //encrypt password $password = sha1($password); $password2 = sha1($password2); if($_POST['password'] != $_POST['password2']) { $error[] = "<p><b>Password does not match</b></p>"; } //rescue email match check if($_POST['email2'] == $_POST['email']) { $error[] = "<p><b>Rescue Email must not be the same as User ID</b></p>"; } //generate random code $random = rand(11111111,99999999); //check for error messages if(isset($error)&&!empty($error)) { implode($error); } else { //Registering to database $queryreg = mysqli_query($connect, "INSERT INTO users VALUES ('','$name','$name2','$email','$password','$password2','$email2','$address','$address2','$address3','$address4','$random','0')"); $lastid = mysqli_insert_id(); echo "<meta http-equiv='refresh' content='0; url=Activate.php?id=$lastid&code=$random'>"; die (); } } } ?>
  25. 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.
  • 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.