Jump to content

Search the Community

Showing results for tags 'sql'.

  • 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. I am having a minor problem with my code if any one can help. I have a form where the user can add a new article however on submit this error is displayed: Warning: mysqli_query() expects parameter 1 to be mysqli, object given in //public_html/admin/includes/addnews.php on line 12. This is the code: $auth = $_POST['auth']; $tit = $_POST['tit']; $stat = $_POST['stat']; $shrt = $_POST['short']; $art = $_POST['art']; $conn = mysqli_connect("localhost","db","password","db") or die ("Could not connect to database"); $query = $conn->prepare ("INSERT INTO newsitem (author,title,shortdesc,article,newsdate,status) VALUES ('$auth','$tit','$shrt','$art',CURDATE(),'$stat')"); $result = mysqli_query($query,$conn); if($result){ echo "successful"; echo "<BR>"; echo "<a href='news.php'>Back to News </a>"; } else { echo "error could not upload article"; } mysqli_close($conn); ?> I have been looking at this for the last two hours with no hope, is there anyone who can point me in the right direction please?
  2. Hi Guys I am wanting to create a menu page which displays menu's based on if the menu field in the sql database has a yes or no in the contents by using an if statement. I have not had much success and would like some help to point me in the right direction. <?php include("../edb.php"); $id =$_REQUEST['id']; $result=mysql_query("SELECT * FROM `eusers` WHERE id='".$_SESSION['uid']."'"); if($MENUAdviser="Y") echo '<script type="text/javascript" src="ExtranetMenu.js"></script>'; if($MENUPAS="Y") echo '<script type="text/javascript" src="PASMenu.js"></script>'; if($MENUStaff="Y") echo '<script type="text/javascript" src="IntranetMenu.js"></script>'; if($MENUWebAdmin="Y") echo '<script type="text/javascript" src="WebAdminMenu.js"></script>'; ?>
  3. Sooo, I could use some help. The code is needed to populate a database from the form, unfortunately, it is not populating the database. When I click submit, a white page appears <?php $a = $_POST['auth']; $t = $_POST['tit']; $st = $_POST['stat']; $sn = $_POST['short']; $c = $_POST['art']; $conn = mysqli_connect(""); if(!is_uploaded_file($_FILES['file']['tmp_name'])) { $query = "INSERT INTO newsitem (author,title,shortdesc,article,newsdate,status) VALUES ('$a','$t','$sn','$c',CURDATE(),'$st')"; } 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") { $query = "INSERT INTO newsitem (author,title,shortdesc,article,newsdate,status) VALUES ('$a','$t','$sn','$c',CURDATE(),'$st')"; } else { $finame = $_FILES["file"]["name"]; $result = move_uploaded_file($_FILES['file']['tmp_name'], "../news/$finame"); if ($result == 1) { $query = "INSERT INTO newsitem (author,title,shortdesc,article,newsdate,status) VALUES ('$a','$t','$sn','$c',CURDATE(),'$st','$finame')"; } else { $query = "INSERT INTO newsitem (author,title,shortdesc,article,newsdate,status) VALUES ('$a','$t','$sn','$c',CURDATE(),'$st')"; } } } $conn->close(); ?> I cannot for the life of me see what it wrong with it, When I run the debugger it cuts off at conn with the Call to undefined function mysqli_connect() error message. If anyone could help point me in the right direction that would be great
  4. I'm currently working on a WordPress website project and I am hoping someone can help me out on this. In the registration page, the data entered is stored into the WordPress database. I've also build a connection to store those data into an external database as well. So basically, If a visitor registers on the site, their data info is stored in the WP and external DB. My question is since the external DB relies on checking to see if the submit button has been pressed, do those data input values need to be escaped to prevent sql injection into the external DB since the data submitted to WordPress has already been sql escaped? Thanks for helping.
  5. Hi! I wanna export data from my mysql database but when i do it, the php on the other site whith the same code shows a ? mark in a square like <?>. I tried everything but nothing works. Please help
  6. Hello Guys, I have a database that is set up something like this: Name Type_a Type_b 3 series Car BMW 1 series Car BMW A class Car Merc C class Car Merc 500 Motorbike XYZ 600 Motorbike XYZ I want to pull this info out of my database and display it like this: Cars: BMW: 1 Series 3 Series Merc A Class Merc C Class Motorbikes: XYZ: 500 600 So far I have this: $result = mysql_query("SELECT * FROM Cars")or die(mysql_error()); while ($row = mysql_fetch_array($result)) { // we get all of the items in this project and put them into a 3 part Array.... $assets= array('Name' => $row['Name], type_a' => $row['Type_A'], 'Type_B' => $row['Type_B']); } print_r($assets); Now this works fine, I end up with a 3 part array containing all of the information I need. The part I am struggling with, is how to get the information back out of the array in a way I can deal with, to produce the above example. Any help? Thanks guys!
  7. Hi PHP Experts, I need some help. I have two tables as follows names table id name man_no 1 Alex 12340 2 Anne 12341 3 Ben 12342 4 Jude 12343 5 Carlos 12344 6 Goofy 12345 scores table id score man_no 1 12 12340 2 5 12341 3 0 12342 1st query $query = "SELECT * FROM names'"; $result = mysqli_query($dbc, $query); ($row = mysqli_fetch_array($result)); $name = $row["name"]; $mat_no = $row["man_no"]; 2nd query $query = "SELECT * FROM scores WHERE man_no='$man_no'"; $result = mysqli_query($dbc, $query); ($row = mysqli_fetch_array($result)); $man_no = $row["man_no"]; Then var_dump($score); gives me string '12' (length=2) string '5' (length=1) string '0' (length=1) null null null Now, here is my question: The Names table will always have people who do not have scores as the scores are added when available. The first query gets the man numbers and using the man numbers, queries for each man number's associated score, returning nill where a score is unavailable. What I want is to get a result set that only incldes scores available in mysql without the null values, a way to avoid null values in the result set. I am still learning joints so I do ask that your help deals with individual queries as I am not yet at a I can use joins. Is it possible to restrict mysql results to only when an entry is available in MySQL. In the above example, is there a clause I can add to the query to only return results where a value was found? Or may be killing the null values after the query? I could not find a way to kill them! My aim is to have: string '12' (length=2) string '5' (length=1) string '0' (length=1)
  8. I am trying to get all the "posts" from a users friends list on their news feed. I'm trying to do so by getting all those posts where the user is the initiator_user_id and get all the posts from the friend_user_id then I want to get all the posts from initiator_user_id where the user's id is the friend_user_id. This is what I have that's messing up: $wallsql= $conn->prepare('SELECT * FROM activity f INNER JOIN wp_bp_friends n1 ON (n1.initiator_user_id=f.user_id) INNER JOIN wp_bp_friends n2 ON (n2.friend_user_id=f.user_id) WHERE (n1.friend_user_id=:userid) OR (n2.initiator_user_id=:userid) ORDER BY datetime DESC LIMIT 8'); $wallsql->bindParam(':userid', $_SESSION['uid']); $wallsql->execute(); Previously this works but it only gets the posts where the user is the initiator_user_id: $wallsql= $conn->prepare('SELECT * FROM activity f INNER JOIN wp_bp_friends n2 ON n2.friend_user_id=f.user_id WHERE n2.initiator_user_id=:userid ORDER BY datetime DESC LIMIT 8'); Any help would be much appreciated!
  9. Greetings <? mysql_connect("xxx","xxx","xxx"); mysql_select_db("name"); if (!isset($_POST['submit'])) { print "<h1>"; print "Welcome"; print "</h1>"; print "<br><br><br>"; echo "<center>"; print "<form action=\"\" method=\"POST\">"; print "<input name=\"dgt\" id=\"Join\" style=\"width:400px\" type=\"text\"> "; print "<input name=\"submit\" value=\"Join\" type=\"submit\">"; print "</form>"; } else { $name = $_POST['dgt']; if(strlen($name) != "10") { print "Name is incorrect."; } else { $query = mysql_query("SELECT * FROM contacts WHERE name ='$name';"); if(mysql_num_rows($query) > 0){ $row = mysql_fetch_assoc($query); print "True"; print "$row[no]"; }else{ print "False"; } } } ?> This script is vulnerable to SQLi I need help in fixing the vulnerability please.
  10. Hello, I have been starded using redbean. I have a really big table and want to select 5000 rows at time using redbean! I want only the rows where the field "status" IS NULL This is my code: $min = R::$c->begin()->addSQL('SELECT MIN(id)')->from('emailtable')->get('cell'); $max = R::$c->begin()->addSQL('SELECT MAX(id)')->from('emailtable')->get('cell'); for ($i = $min; $i < $max; $i = $i + 5000) { $x = $i; $y = $i + 5000; $select = R::$c->begin() ->addSQL(' SELECT * ') ->from('emailtable') ->where(" id >= ? AND id < ? AND status IS NULL ") ->put($x) ->put($y) ->get(); } Anyone know if this is the right way to go! Should i use: id >= ? AND id < ? AND status IS NULL or maybe i should use BETWEEN but not sure. My problem is The code above is sometimes selecting same id twice and that is what i do not expect! there for i ask if there is a other solution four the code above! All ides are welcome. It is really hard to find information about redbean/chunk/select/ example
  11. I have two tables, mod_music_category has a field id which autoincrements and the other table, mod_music_entries has category_id field whose value is mod_music_category.id but enclosed with "b" and "e" .e.g."b mod_music_category.id e" no spaces like b1e. I am trying to select all records from mod_music_entries whose category_id is LIKE or EQUAL to mod_music_category id field as follows: SELECT `c`.id, `c`.category, `e`.`category_id`, `c`.teaser, `c`.style FROM `".DB_EXTENTION."mod_music_category` `c` LEFT JOIN `".DB_EXTENTION."mod_music_entries` `e` ON( `e`.`category_id` = '%b`c`.`id`e%') ORDER BY c.`priority` ; Its returning all values even if there is no join. Is ther a better way. Thanks
  12. I keep getting this error how can I fix this?? Warning: Invalid argument supplied for foreach() in /hermes/waloraweb071/b2172/moo.mangowebdesignsnet/shopping/includes/functions.inc.php on line 1082 MySQL Error OccurredError Message: 1064: 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 '' at line 1 SQL: SELECT I.productId, I.image, I.price, I.name, I.sale_price FROM mangostoreCubeCart_inventory AS I, mangostoreCubeCart_category AS C WHERE C.cat_id = I.cat_id AND I.disabled != '1' AND I.showFeatured = '1' AND I.cat_id > 0 AND C.hide != '1' ORDER BY I.productId DESC LIMIT If anyone can help me with this I would be deeply grateful. If you need anything or more details please respond to this topic please. I need this fixed ASAP. Thanks
  13. Hi again , Im trying to create form which allows the users to edit their data , I've created the form ,added the sql i think is right but its not working and giving me sql erro that the data can't be inserted . this is my code for the form details.php : <?php include '../header.php'; include '../config2.php'; session_start(); $id = $_POST['ID']; ?> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/parsley.js"></script> <script> $(document).ready(function() { // submit data on click and check if valid $('#sendData').click(function(e) { //check if valid with parsley var valid = $('#detailform').parsley ( 'validate' ); if ( valid === false ) { e.preventDefault(); } else { $.post("updateprocess.php", $("#detailform").serialize()); } }); }); </script> <div id="title"> <div class="inner"> <h1>Changing Your Account Details</h1> </div> </div> <div id="content" class="right-sidebar"> <div class="container inner"> <div id="main" role="main"> <div class="container"> <h3>Please Choose Which information Your would like to change</h3> <form data-validate="parsley" method="POST" action="updateprocess.php" id="detailform" > <label>Email Address</label> <input type="text" name="login_email" data-required="true" value="<?php echo $account['login_email']; ?>"/> <label>Change a password</label> <input type="password" name="login_password" data-notblank="true"/> <label>Re-enter new password</label> <input type="password" name="confirm" data-notblank="true"/> <label>First Name</label> <input type="text" name="first_name" data-required="true" value="<?php echo $account['first_name']; ?>" disabled="disabled" /> <label>Last Name</label> <input type="text" name="last_name" data-notblank="true" /> <label>Address line 1</label> <input type="text" name="address_one" data-required="true" value="<?php echo $account['address_one']; ?>"/> <label>Address line 2</label> <input type="text" name="address_two" data-required="true" value="<?php echo $account['address_two']; ?>"/> <label>Town/City</label> <input type="text" name="town_city" data-required="true" value="<?php echo $account['town_city']; ?>" /> <label>County</label> <input type="text" name="county_option" data-required="true" value="<?php echo $account['county_option']; ?>"/> <label>Postcode</label> <input type="text" name="post_code" data-required="true" value="<?php echo $account['post_code']; ?>"/> <label>Phone number</label> <input type="text" name="phone_number" data-required="true" value="<?php echo $account['phone_number']; ?>"/> <p></p> <p></p> <p></p> <p></p> <p></p> <input type="checkbox" class="checkbox" id="agree" name="agree" /> I Agree With Terms & Conditions</p> <td> <input type="submit" name="submit" class="button" value= "Save"/></td> </form> </div> <div class="space"></div> </div> <ul class="sidebar" role="complementary"> <li> <h2>Navigation</h2> <ul class="link-list"> <li><a href="/account/dashboard.php">Dashboard</a></li> <li><a href="/account/transfer.php">Transfer Money</a></li> <li><a href="/account/transactions.php">Transactions</a></li> <li><a href="/account/withdrawal.php">Withdraw Funds</a></li> <li><a href="/account/upload.php">Upload Funds</a></li> <li><a href="/account/details.php">Change My details</a></li> </ul> </li> </ul> </div> </div> <?php include '../footer.php'; ?> this is the update.php script <?php include "config2.php"; $id = $_POST['ID']; $sql="SELECT * FROM users WHERE id='$id'"; $result=mysql_query($sql); $id = $_POST['ID']; $rows=mysql_fetch_array($result); $email = $_POST['login_email']; $pass = md5($_POST['login_password']); $confirm = md5($_POST['confirm']); $fname = $_POST['first_name']; $lname = $_POST['last_name']; $addressone = $_POST['address_one']; $addresstwo = $_POST['address_two']; $towncity = $_POST['town_city']; $countyoption = $_POST['county_option']; $postcode = $_POST['post_code']; $phone = $_POST['phone_number']; $update = 'UPDATE users SET( login_email, login_password, confirm, first_name, last_name, address_one, address_two, town_city, county_option, post_code, phone_number) VALUES("'.$email.'","'.$pass.'","'.$confirm.'","'.$fname.'","'.$lname.'","'.$addressone.'","'.$addresstwo.'","'.$towncity.'","'.$countyoption.'","'.$postcode.'","'.$phone.'")WHERE id="'.$id.'""'; //$insert = 'UPDATE users SET login_email="'.$email.'", login_password="'.$pass.'", confirm="'.$confirm.'", first_name="'.$fname.'", last_name="'.$lname.'", address_one="'.$addressone.'", address_two="'.$addresstwo.'", town_city="'.$towncity.'", county_option="'.$countyoption.'", post_code="'.$postcode.'", phone_number="'.$phone.'" WHERE id="'.$id.'""'; mysql_query($update) or die("Failed Updating Your Data,check SQL"); header( 'Location: ../account/success.php' ) ; ?>
  14. I'm having a problem with PHP and a stored procedure in SQL Server 2005. I haven't really touched stored procedures before and haven't used them with php. I can't retrieve a value from a table that I know is definitely there. I have a simple login table, what I want the stored procedure to do is to take a username as an input and then output that user's password salt. I want the stored procedure to use parameterised values to avoid SQL injection. What happens at the moment is when the php page is run, nothing is returned and the SQL Profiler displays the following error: User Error Message: Incorrect Syntax near '@Username' While this error message should tell me something is wrong, I can't for the life of me see where the incorrect syntax is. Copy of the Php: $user = "usercm"; $password ="cmuserpassword"; try{$conn = new PDO("odbc:DRIVER={SQL Server Native Client 10.0};SERVER=TestingServer;DATABASE=TestingDatebase;",$user,$password);} catch(PDOException $e){echo "oh no";} $username = "sdct"; $prepusp = $conn->prepare("EXEC uspReturnSalt(?,?)"); $prepusp->bindParam(1, $username, PDO::PARAM_STR); $prepusp->bindParam(2, $usersalt, PDO::PARAM_STR, 450); $prepusp->execute(); Copy of the Stored Procedure: ALTER PROCEDURE [dbo].[uspReturnSalt] @Username NVARCHAR(100), @Usersalt NVARCHAR(450) OUTPUT AS BEGIN DECLARE @sqlcmd NVARCHAR(MAX); DECLARE @params NVARCHAR(MAX); SET @sqlcmd = N'SELECT @Usersaltone = salt FROM CMUsers WHERE username = @Usernameone'; SET @params = N'@Usernameone NVARCHAR(100), @Usersaltone NVARCHAR(450) OUTPUT'; EXECUTE sp_executesql @sqlcmd, @params, @Usernameone = @Username, @Usersaltone = @Usersalt OUTPUT; END To clarify, the server this is on runs Windows 2003 so I cannot use the sqlsrv drivers as they require SQL Server Native Client 2012 which is incompatible. It is impossible to upgrade the operating system (server isn't mine) so I can't use any php drivers that require SQL Server Native Client 2012. If anyone could help I would be eternally grateful. Here is the sql profiler messages before and after that error: RPC:Completed | exec [sys].sp_sproc_columns_90 N'uspReturnSalt' ,@ODBCVer=3 RPC:Starting | declare @p1 int set @p1 =NULL exec sp_prepare @p1 output,N'@Username nvarchar(100),@P2 text OUTPUT' ,N'EXEC uspReturnSalt(@Username,@P2 OUTPUT)' ,1 select @p1 Exception | Error: 102, Severity: 15, State: 1 User Error Message | Incorrect syntax near '@Username'. SP:CacheMiss | (@Username nvarchar(100),@P2 text OUTPUT)EXEC uspReturnSalt(@Username,@P2 OUTPUT) Exception | Error: 8180, Severity: 16, State: 1 User Error Message | Statement(s) could not be prepared RPC:Completed | declare @p1 int set @p1=NULL exec sp_prepare @p1 output, N'@Username nvarchar(100),@P2 text OUTPUT' ,N'EXEC uspReturnSalt(@Username,@P2 OUTPUT)',1 select @p1
  15. I have a database class that uses PDO and it all works until i need to do an update where I increment the value What I have is a table and one of the columns is called 'counter' and I need to update this table every time a page is visited This is the function that handles all the PDO and creates the query /** * update * @param string $table A name of table to insert into * @param string $data An associative array * @param string $where the WHERE query part */ public function update($table, $data, $where) { ksort($data); $fieldDetails = NULL; foreach($data as $key=> $value) { $fieldDetails .= "`$key`=:$key,"; } $fieldDetails = rtrim($fieldDetails, ','); $sth = $this->prepare("UPDATE $table SET $fieldDetails WHERE $where"); foreach ($data as $key => $value) { $sth->bindValue(":$key", $value); } $sth->execute(); } and this is how I call the function by passing parametres to the function $board = ucwords(str_replace('-',' ',$board)); $sql = "SELECT boardid from boards WHERE boardname = :board"; $rows = $this->db->select($sql, array(':board' => $board)); $postData = array( 'counter' => 'counter+1', ); $this->db->update('topics', $postData, "`topicid` = {$topic} AND `boardid` = {$rows[0]['boardid']}"); It fails the update with this error message The counter column is of type INT
  16. My apologies if I've placed this in the wrong section. It concerns a basic connection to n SQL database, and doing a simple count of the records. I'm learning from DAVID POWERS PHPSOLOUTIONS book. Examples in his book show connecting to the local db differently than my host wants me to connect, and I believe therin lies the issue. If I can figure out the method or problem I'm having, I'll be very thankful. I'm just connecting to a database, running one query, and counting records. The code that I altered, and I am trying to use, looks like this: <?php //Sample Database Connection Syntax for PHP and MySQL. include ('/includes/imageconn.inc.php'); include ('/includes/imagetableconn.inc.php'); mysql_select_db($dbname); # Check If Record Exists $sql = "SELECT * FROM $usertable"; $result = $conn->query($sql) or die(mysqli_error()); $numrows = $result->num_rows; ?> <html> <head> <title>PHP Test</title> </head> <body> <?php echo $numrows; ?> </body> </html> ----------------------------------------------------------------------- My imageconn.inc.php file holds a set of variables needed for the connection. I have verified it works (online, where I want), using other simple pages I made. This is the imagetableconn.inc.php file. It contains one line of code (which also works in the test file the host sent me). $conn = mysql_connect($hostname, $username, $password) or die ('Error connecting to mysql'); ------------------------------------------------------------------------- I'm pretty sure the problem lies in this line (which is from the BOOK, which I can't figure out how to modify for my online needs): $result = $conn->query($sql) or die(mysqli_error()); My error message: Fatal error: Call to a member function query() on a non-object in D:\Hosting\4641474\html\testimagedb1.php on line 12
  17. Hi! I can't figure out this code: SELECT Student.fornavn,etternavn,brukernavn Fag.fagkode, COUNT(Oppgave.nr) AS AntalOppgaver FROM Student,Fag LEFT JOIN Student WHERE Fag.fagkode='DAT1000' = Syntax error , mariadb....... The task text is : The question should get an overview of all students(Here: Student) in a choosen subject(Here:fag) and count how many tasks(here:oppgave) The overview should show sirname(Etternavn)name(Fornavn) username(Brukernavn)and numbers of tasks in the subject(fag) The overview shuld be order by sirname(etternavn)and then on name(fornavn) Any idea? - Look at the E/R attachment
  18. im using the jquery UI datepicker to submit a date to my database but i keep storing 0000-00-00 instead of the date how do I make the date show up in the database? can someone help me?
  19. I have a function that updates a database and it works fine for one record but i have a form which shows loads of rows with checkboxes and i want to do a batch update (I suppose the principle is the same for a batch delete). When I click a load of checkboxed and call the funtion to update, i get an error about an array to string conversion and also this error message "Unknown column 'Array' in 'where clause" I know a way around it but it's not great using a foreach loop to update the database but that involves loads of queries This is my function I call to update the database /** * update * @param string $table A name of table to insert into * @param string $data An associative array * @param string $where the WHERE query part */ public function update($table, $data, $where) { ksort($data); $fieldDetails = NULL; foreach($data as $key=> $value) { $fieldDetails .= "`$key`=:$key,"; } $fieldDetails = rtrim($fieldDetails, ','); $sth = $this->prepare("UPDATE $table SET $fieldDetails WHERE $where"); foreach ($data as $key => $value) { $sth->bindValue(":$key", $value); } $sth->execute(); } This works public function newsEdit($data) { $postData = array( 'title' => $data['news_title'], 'content' => $data['news_content'], 'photo' => $data['imgname'], 'keywords' => $data['news_keywords'], 'alternate' => $data['alternate'] ); $this->db->update('news', $postData, "`id` = {$data['newsid']}"); } $data = array(); $data['news_title'] = $_POST['news_title']; $data['news_content'] = $_POST['news_content']; $data['imgname'] = $_POST['imgname']; $data['news_keywords'] = $_POST['news_keywords']; $data['alternate'] = substr($_POST['imgname'],0,strrpos($_POST['imgname'], ".")); newsEdit($data); This doesn't public function newsArchive($ids) { $postData = array( 'archived' => 'Y' ); $this->db->update('news', $postData, "`id` IN ({$ids})"); } newsArchive($_POST['id']); What have i got to change to get the update working?
  20. For some reason the attached code does not submit the data to the sql table. I get the "saved" message but cannot see any obvious reason why the data is not being entered. Can someone please use your expert eye to shed some light on why this is not working? I have a number of forms all using similar coding and they all appear to work fine. <?php if(isset($_POST['Submit'])){ $DateUploaded = protect($_POST['DateUploaded']); $Subject = protect($_POST['Subject']); $Text = protect($_POST['Text']); $URL1 = protect($_POST['URL1']); $ImageType1 = protect($_POST['ImageType1']); $cssclass1 = protect($_POST['cssclass1']); $Notes1 = protect($_POST['Notes1']); $URL2 = protect($_POST['URL2']); $ImageType2 = protect($_POST['ImageType2']); $cssclass2 = protect($_POST['cssclass2']); $Notes2 = protect($_POST['Notes2']); $URL3 = protect($_POST['URL3']); $ImageType3 = protect($_POST['ImageType3']); $cssclass3 = protect($_POST['cssclass3']); $Notes3 = protect($_POST['Notes3']); $URL4 = protect($_POST['URL4']); $ImageType4 = protect($_POST['ImageType4']); $cssclass4 = protect($_POST['cssclass4']); $Notes4 = protect($_POST['Notes4']); $URL5 = protect($_POST['URL5']); $ImageType5 = protect($_POST['ImageType5']); $cssclass5 = protect($_POST['cssclass5']); $Notes5 = protect($_POST['Notes5']); $URL6 = protect($_POST['URL6']); $ImageType6 = protect($_POST['ImageType6']); $cssclass6 = protect($_POST['cssclass6']); $Notes6 = protect($_POST['Notes6']); if(!$Subject || !$Text){ //if any weren't display the error message echo "<center>You need to fill in all of the required fields! This record <b>HAS NOT </b> been saved</center>"; }else{ $res = mysql_query("INSERT INTO `edocs_hoct_comms` (`DateUploaded`, `Subject`, `Text`, `URL1`, `ImageType1`, `cssclass1`, `Notes1`, `URL2`, `ImageType2`, `cssclass2`, `Notes2`, `URL3`, `ImageType3`, `cssclass3`, `Notes3`, `URL4`, `ImageType4`, `cssclass4`, `Notes4`, `URL5`, `ImageType5`, `cssclass5`, `Notes5`, `URL6`, `ImageType6`, `cssclass6`, `Notes6`) VALUES ('".$DateUploaded."', '".$Subject."', '".$Text."', '".$URL1."', '".$ImageType1."', '".$cssclass1."', '".$Notes1."', '".$URL2."', '".$ImageType2."', '".$cssclass2."', '".$Notes2.", '".$URL3."', '".$ImageType3."', '".$cssclass3."', '".$Notes3."'', '".$URL4."', '".$ImageType4."', '".$cssclass4."', '".$Notes4."', '".$URL5."', '".$ImageType5."', '".$cssclass5."', '".$Notes5."', '".$URL6."', '".$ImageType6."', '".$cssclass6."', '".$Notes6."')"); echo "Saved!"; }} ?>
  21. i have put 3 users on my database. If i login with all 3 it works there is no problem(providing correct username and password matches). The problem is that it recognizes all 3 users as the first user. even if i check password it will display all three users password the same(all tho when i log in i have to have correct password and username for each user) as the first user which is user id 1. When i echo username or name or surname it displays the first users name or surname whatever i echo , no matter who i log in with I am not sure whats going on here at all. here is my code for the login functions i think the problems lies here i know this is not the best code but there must be a way to fix this users.php <?php function register_user($register_data){ Global $dbc; array_walk($register_data,'array_sanatize'); $register_data['password']= md5($register_data['password']); $fields='`'.implode('`, `',array_keys( $register_data)).'`'; $data='\''.implode('\', \'', $register_data).'\''; //print_r($register_data); mysqli_query($dbc," INSERT INTO `users` ($fields) VALUES ($data)"); //mysqli_error($dbc); } function user_data($user_id){ Global $dbc; $data=array(); $user_id = (int)$user_id; $func_num_args=func_num_args(); $func_get_args=func_get_args(); if($func_num_args >=1){ unset($func_get_args[0]); $fields='`'.implode('`, `', $func_get_args).'`'; $data=mysqli_query($dbc," SELECT $fields FROM `users` WHERE `user_id` = $user_id "); //mysqli_error($dbc); if ($data === false) { die("error on mysqli_query: ". mysqli_error($dbc)); } $data=mysqli_fetch_assoc($data); //print_r ($data); return $data; } } function logged_in(){ GLOBAL $dbc; return(isset($_SESSION['user_id'])) ? true : false; } function user_exists($username){ GLOBAL $dbc; $username=sanatize($username); $query= mysqli_query($dbc,"SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' "); $check= mysqli_fetch_array( $query , MYSQLI_BOTH); return ($check[0]==1)?true:false; } function email_exists($email){ GLOBAL $dbc; $email=sanatize($email); $query= mysqli_query($dbc,"SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '$email' "); $check= mysqli_fetch_array( $query , MYSQLI_BOTH); return ($check[0]==1)?true:false; } function user_active($username){ GLOBAL $dbc; $username=sanatize($username); $query= mysqli_query($dbc,"SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `active` = 1 "); $check= mysqli_fetch_array( $query , MYSQLI_BOTH); return ($check[0]==1)?true:false; } function user_id_from_username($username){ GLOBAL $dbc; $username = sanatize($username); $query= mysqli_query($dbc,"SELECT `user_id` FROM `users` WHERE `username` = '$username' "); $check= mysqli_fetch_array( $query , MYSQLI_BOTH); return $check[0]=='user_id'; } function login($username , $password){ GLOBAL $dbc; $user_id = user_id_from_username($username); $username = sanatize($username); $password = md5($password); $query= mysqli_query($dbc,"SELECT `user_id` FROM `users` WHERE `username` = '$username' AND `password` = '$password'"); //$check= mysqli_fetch_array( $query , MYSQLI_BOTH); if(mysqli_num_rows($query) == 1) { return 0 == 1 ? $user_id : true ; } // no results found so return false return false; log.php include("config/init.php"); if(empty($_POST)===false){ $username= $_POST['username']; $password= $_POST['password']; } if(empty($username) ===true || empty($password) ===true){ $errors[] ='Please enter a valid username and password'; } else if (user_exists($username)===false){ $errors[] ='This username does not exist. Please sign up'; } else if (user_active($username)===false) { $errors[]="you have not activated your account via email"; } else { // here errors //testing username passwords ect, if all of the above statemens failed $login=login($username,$password); if($login===false){ //$error[]= echo "That username and password combination is incorrect"; } else { // set username session // redirect user to home //die($login); $_SESSION['user_id']=$login; header('location:index.php'); exit(); } } //print_r($errors); include('templates/header.php'); include('templates/footer.php'); ?> config/init.php <?php session_start(); require('connect.php'); require('functions/general.php'); require('functions/users.php'); // to be accessed by every page to check errors for login if(logged_in()===true){ $session_user_id=$_SESSION['user_id']; $user_data = user_data($session_user_id,'user_id','username','password','name' ,'surname' ,'email'); //echo $user_data['name']; if(user_active($user_data['username'])=== false){ session_destroy(); header('Location:index.php'); exit(); } } //else echo "cannot retreive data"; $errors=array(); ?> this does not echo correct username or id . no errors are displayed <aside id="widgets"> require_once('config/init.php'); require_once('config/functions/users.php'); require_once('config/functions/general.php'); ?> <h4 class="username"> Welcome <?php echo $user_data['name'];?> </h4> <div class="inner"> <ul> <li> <a href="logout.php"> Log out </a> </li> <li> <a href="changepassword.php"> New password </a> </li> </ul> </div> <?php echo mysqli_error($dbc);?> </aside> <?php include('templates/footer.php'); ?> <?php ?>
  22. prolife

    Sql issue

    Hello please i dont know what went wrong ;this SQL is meant to count provided that this conditions are true. i want to count the total number of rooms that were booked for in a particular month. Please what is the right syntax to use when selecting from two different tables and then counting the total number of occurance. Here is the SQL i came up with but its messig up. SELECT (SELECT COUNT(*) FROM `rooms`) (SELECT COUNT(*) FROM `order`) AS `total_rooms` FROM `rooms` WHERE `order`.`checkin`>'$real_date' AND `rooms`.`cond` ='available'
  23. I'm attempting to use PHP to connect to an SQL database to use to store quotes from an IRC chat bot. So far the bot seems to be running, but the sql connection isn't working and I'm not exactly sure why. I've tried reading through all sorts of sites, and I modified code I found on the WC3 schools site just to be sure I wasn't missing some huge 'derp'. Nothing seems to work, and I'm feeling my brain melt. Relevant connection data for writing to the db: function addquote() { $con=mysqli_connect("localhost","BotBot","password","Quotes"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } mysqli_query($con,"INSERT INTO `Quotes`.`quotes` (`ID_NUM`, `DATA`, `USER`) VALUES (NULL, \'$qd\', \'\');"); $this->pm("Quote added to database."); mysqli_close($con); } Second connection for reading a random result from the db and messaging it: function randomquote() { $con=mysqli_connect("localhost","BotBot","password","Quotes"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $result = mysqli_query($con,"SELECT * FROM quotes ORDER BY RAND() LIMIT 1"); $this->pm($result); mysqli_close($con); } "password" in both is being replaced with the relevant password for that user account, and the account has full access to r/w the db. I am getting the pm("Quote added to database") line returned to me through the IRC bot, and it doesn't disconnect the moment you try to use these functions (took about a week of pokes and prods to figure out what I was doing wrong!). I'm not exactly sure how a response down past that sql connection could be working if it's not connecting, not without giving me a 'die'. PHPMyAdmin isn't showing that 'BotBot' account even attempting a connection and dying for a bad password or anything, so... kinda running out of ideas here. If anyone can give me a hand here, I'd be grateful for it.
  24. I have a problem that when I submit the page goes blank or goes to the location specified in header but it does not update the sql record. This used to work but I made some changes and now I cannot get it back. Any assistance would be appreciate. <?php require('edb.php'); $id=$_REQUEST['id']; $ActivateCode=$_REQUEST['ActivateCode']; $result=mysql_query("SELECT * FROM `eusers` WHERE id = '$id' && ActivateCode = '$ActivateCode'"); $test=mysql_fetch_array($result); if (!$result) { die("Error: Data not found.."); } $id=$test['id']; $FirstName=$test['FirstName']; $LastName=$test['LastName']; $State=$test['State']; $Username=$test['Username']; $Password=$test['Password']; $Email=$test['Email']; $Active=$test['Active']; $SecurityCode=$test['SecurityCode']; $AdviserCode=$test['AdviserCode']; $UserType=$test['UserType']; $ActivateCode=$test['ActivateCode']; if(isset($_POST['Submit'])) { $Password_save =sha1($_POST['Password']); $Email_save =$_POST['Email']; $Active_save =$_POST['Active']; $SecurityCode_save =$_POST['SecurityCode']; $ActivateCode_save =$_POST['ActivateCode']; mysql_query("UPDATE `eusers` SET Password ='$Password_save', Email ='$Email_save', Active ='$Active_save', SecurityCode ='$SecurityCode_save', ActivateCode ='$ActivateCode_save' WHERE id ='$id'") or die(mysql_error("Did not Save")); echo "Saved!"; header("Location: index.php"); } ?>
  25. Hi, I have been trying to get this piece of coding to submit my form after checking but it keeps going to a 500Error. I have spent so long trying to work it out that now I am confused on what works and what doesn't. Can someone please help with where I am going wrong. <?php if(isset($_POST['Submit'])){ $DateUploaded = protect($_POST['DateUploaded']); $AdviserCode = protect($_POST['AdviserCode']); $DocName = protect($_POST['DocName']); $URL = protect($_POST['URL']); $ImageType = protect($_POST['ImageType']); $Current = protect($_POST['Current']); $css_class = protect($_POST['css_class']); if(!$ImageType || !$DocName){ echo "<center>You need to fill in all of the required filds!</center>"; }else{ $res = mysql_query ("INSERT INTO `adocs_cpd` (`DateUploaded`, `AdviserCode`, `DocName`, `URL`, `ImageType`, `Current`, `css_class`) VALUES ('".$DateUploaded."','".$AdviserCode."','".$DocName."','".$URL."','".$ImageType."','".$Current."','".$css_class."')"); echo "Saved!"; } } ?>
×
×
  • 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.