PHP - Select Query Problem
Hi,
i'm trying to select some entries from my DB, i don't quite understand what's the problem here, i'm using this: Code: [Select] //Customers Online $query = "SELECT COUNT(*) as Anzahl FROM customers WHERE status = 1"; $queryerg = mysql_query($query) OR die(mysql_error()); while($row = mysql_fetch_array($queryerg)){ $customers_online = $row[0]; } Which works fine, now i want to select by country and i'm doing this: Code: [Select] //Customers DE $query = "SELECT COUNT(*) as Anzahl FROM customers WHERE country = 'de'"; $queryerg = mysql_query($query) OR die(mysql_error()); while($row = mysql_fetch_array($queryerg)){ $customers_de = $row[0]; } Which doesn't work? If i print / echo $customers_de i just get a blank value, not even 0 or anything just blank. Any help ? Similar TutorialsThe code below is part of some validation code that I have, it is supposed to count the number of entries in the table 'test_selections' where 'userid' equals the user that is logged in and where the 'transfer_in' date is a date within the current month. I am getting an error saying "Error running query Unknown column '10' in 'where clause' ". Does anybody know why this could be? I am hoping that it is something to do with the snippet of code below so I don't need to post the whole lot!! Any help would be much appreciated. Code: [Select] $current_month = date("m"); $query = "SELECT COUNT(`userid`) as `transfers_count` FROM `test_selections` WHERE `userid` = '{$_SESSION['userid']}' AND Month(`transfer_in`) = `$current_month` GROUP BY `userid`"; Hello all,
Based on the suggestion of you wonderful folks here, I went away for a few days (to learn about PDO and Prepared Statements) in order to replace the MySQLi commands in my code. That's gone pretty well thus far...with me having learnt and successfully replaced most of my "bad" code with elegant, SQL-Injection-proof code (or so I hope).
The one-and-only problem I'm having (for now at least) is that I'm having trouble understanding how to execute an UPDATE query within the resultset of a SELECT query (using PDO and prepared statements, of course).
Let me explain (my scenario), and since a picture speaks a thousand words I've also inlcuded a screenshot to show you guys my setup:
In my table I have two columns (which are essentially flags i.e. Y/N), one for "items alreay purchased" and the other for "items to be purchased later". The first flag, if/when set ON (Y) will highlight row(s) in red...and the second flag will highlight row(s) in blue (when set ON).
I initially had four buttons, two each for setting the flags/columns to "Y", and another two to reverse the columns/flags to "N". That was when I had my delete functionality as a separate operation on a separate tab/list item, and that was fine.
Now that I've realized I can include both operations (update and delete) on just the one tab, I've also figured it would be better to pare down those four buttons (into just two), and set them up as a toggle feature i.e. if the value is currently "Y" then the button will set it to "N", and vice versa.
So, looking at my attached picture, if a person selects (using the checkboxes) the first four rows and clicks the first button (labeled "Toggle selected items as Purchased/Not Purchased") then the following must happen:
1. The purchased_flag for rows # 2 and 4 must be switched OFF (set to N)...so they will no longer be highlighted in red.
2. The purchased_flag for row # 3 must be switched ON (set to Y)...so that row will now be highlighted in red.
3. Nothing must be done to rows # 1 and 5 since: a) row 5 was not selected/checked to begin with, and b) row # 1 has its purchase_later_flag set ON (to Y), so it must be skipped over.
Looking at my code below, I'm guessing (and here's where I need the help) that there's something wrong in the code within the section that says "/*** loop through the results/collection of checked items ***/". I've probably made it more complex than it should be, and that's due to the fact that I have no idea what I'm doing (or rather, how I should be doing it), and this has driven me insane for the last 2 days...which prompted me to "throw in the towel" and seek the help of you very helpful and intellegent folks. BTW, I am a newbie at this, so if I could be provided the exact code, that would be most wonderful, and much highly appreciated.
Thanks to you folks, I'm feeling real good (with a great sense of achievement) after having come here and got the great advice to learn PDO and prepared statements.
Just this one nasty little hurdle is stopping me from getting to "end-of-job" on my very first WebApp. BTW, sorry about the long post...this is the best/only way I could clearly explaing my situation.
Cheers guys!
case "update-delete": if(isset($_POST['highlight-purchased'])) { // ****** Setup customized query to obtain only items that are checked ****** $sql = "SELECT * FROM shoplist WHERE"; for($i=0; $i < count($_POST['checkboxes']); $i++) { $sql=$sql . " idnumber=" . $_POST['checkboxes'][$i] . " or"; } $sql= rtrim($sql, "or"); $statement = $conn->prepare($sql); $statement->execute(); // *** fetch results for all checked items (1st query) *** // $result = $statement->fetchAll(); $statement->closeCursor(); // Setup query that will change the purchased flag to "N", if it's currently set to "Y" $sqlSetToN = "UPDATE shoplist SET purchased = 'N' WHERE purchased = 'Y'"; // Setup query that will change the purchased flag to "Y", if it's currently set to "N", "", or NULL $sqlSetToY = "UPDATE shoplist SET purchased = 'Y' WHERE purchased = 'N' OR purchased = '' OR purchased IS NULL"; $statementSetToN = $conn->prepare($sqlSetToN); $statementSetToY = $conn->prepare($sqlSetToY); /*** loop through the results/collection of checked items ***/ foreach($result as $row) { if ($row["purchased"] != "Y") { // *** fetch one row at a time pertaining to the 2nd query *** // $resultSetToY = $statementSetToY->fetch(); foreach($resultSetToY as $row) { $statementSetToY->execute(); } } else { // *** fetch one row at a time pertaining to the 2nd query *** // $resultSetToN = $statementSetToN->fetch(); foreach($resultSetToN as $row) { $statementSetToN->execute(); } } } break; }CRUD Queston.png 20.68KB 0 downloads hirealimo.com.au/code1.php this works as i want it: Quote SELECT * FROM price INNER JOIN vehicle USING (vehicleID) WHERE vehicle.passengers >= 1 AND price.townID = 1 AND price.eventID = 1 but apparelty selecting * is not a good thing???? but if I do this: Quote SELECT priceID, price FROM price INNER JOIN vehicle....etc it works but i lose the info from the vehicle table. but how do i make this work: Quote SELECT priceID, price, type, description, passengers FROM price INNER JOIN vehicle....etc so that i am specifiying which colums from which tables to query?? thanks ok, so I need to know how I can perform an operation of $total equaling $price1 + $price2 etc.... if they are not empty in the database............... does this make sense? i am unable to select total_comment from mysql table related to each post..
For detail information check http://stackoverflow...-query-in-mysql
Hi, Everyone! This my first time posting here. Anyways, I've been having problem getting the correct data from my database. I want to select the total_on/off_hours,exposure,plate_number, and terminal_status. But when I select the terminal_status, there are duplicates, I already used the DISTINCT function. It's a little hard to explain so, I'll just show you.
Here's a screen cap of my code trying to get just the terminal_status
What's the problem? What should I do? Any suggestions/help will be much appreciated.
I have this code below: Code: [Select] members_count <= ".$diff." || members_count >= ".$defmemcount." My test says $diff = 6 and $defmemcount = 11, members_count = 14 So how come this returns as if members_count isn't less or equal to 6 OR higher or equal to 11? Hi I need to do a SELECT query like $query = "SELECT name FROM myusers WHERE myidnum = ".$_SESSION['myid'].""; and put the results into an array like $myusers = array("David","John","Lucy","Sarah"); But I cannot figure out how to do this Can anyone help? Thanks hi i have this function for select / function select($table, $rows = '*', $where = null, $group = null, $order = null, $limit = null) this is what i do to display the records. $db->select('loan'); $records = $db->getResult(); foreach($records as $row) { $user = $row['id']; //$name = $row['firstname']; //print_r($row); echo $user; ?> the codes is running.but when i want to use WHERE id = $_POST['id']; this is what im doing. $db->select('member')->where(array('id' => $_POST['client'])); an error as occured where in function where is not existing. please help how to use the proper way of using select * $table where id=$id; in array. thanks Hi there
I am new to this forum and not much of a php expert. I hope you can assist me.
My problem is as follows:
I have a column consisting of several values (in this case: sceience, art, humanistics and music)
I would like to use the following mysqli query in order to count the appearances of each value in this column:
$query = "SELECT SUM (IF(department = 'science', 1, 0)) AS science, SUM(IF(department = 'art', 1, 0))-> AS art FROM new2"
I have tried lots of ways to loop the results but couldn't get the it working.
Can anyone suggest any idea?
Thanks
Hanan
Hello, Im trying to write a select query that has two conditions. First the playername is = username and second shipyard = 1 I keep getting a parse error: Parse error: syntax error, unexpected ',' in C:\wamp\www\SWB\planet1.php on line 85 Heres the code: Code: [Select] $tester = "1"; $colname_Planet1 = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_Planet1 = (get_magic_quotes_gpc()) ? $_SESSION['MM_Username'] : addslashes($_SESSION['MM_Username']); } mysql_select_db($database_swb, $swb); $query_Planet1 = ("SELECT * FROM planet WHERE ShipYard = %s AND PlayerName = %s", GetSQLValueString($tester, "int"),GetSQLValueString($colname_Planet1, "text")); $Planet1 = mysql_query($query_Planet1, $swb) or die(mysql_error()); $row_Planet1 = mysql_fetch_assoc($Planet1); $totalRows_Planet1 = mysql_num_rows($Planet1); Please help :| Hello there, Having a nightmare here. It feels like what I need to do is really easy but I just can't get it to work. I have a table called "groups2" that holds a unique id and the name of an activity. I already have a query that finds the users selected groups using a while loop but I also want to show how many other members are in that group by counting the number of times the activity comes up or the id comes up. I don't know whether I need 2 while loops nested or what but I get the error Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource on line 32 which is highlighted. Can anyone help. I am no expert at php and still learning so some advice or example code would be great. $result = mysql_query("SELECT * FROM groups2 WHERE L_ID = ". $_SESSION['member_ID'] .";"); $data = mysql_query("SELECT COUNT('name') AS num FROM groups2 WHERE name = " . $row['name'] . ""); $count = mysql_fetch_assoc($data); $numbers = $count['num']; while ( $row = mysql_fetch_assoc($result) ) { echo("<tr> <td><font face='Arial, Helvetica, sans-serif' size='3'><strong>" . $row["name"] . "</strong></font></td> </tr><tr> <td><font face='Arial, Helvetica, sans-serif' size='1' color='#0000FF'><strong>Members (" . $numbers . ")</strong></font></td> </tr><tr> <td><hr width=95%><br></td> </tr>"); } Code: [Select] $DB->query("SELECT SUM(amount) FROM gold_logs WHERE from_id = {$ibforums->member['id']} GROUP BY from_id"); $data = $DB->fetch_row(); Okay, then I echo out Code: [Select] {$data['SUM(amount)']} but I want to select the sum(amount) from "to_id" ALSO! how can I add that into the query I dont want to use 2 queries, thanks I need to convert the following select statement to a pdo->query but have no idea how to get it working: SELECT t.id FROM ( SELECT g.* FROM location AS g WHERE g.start <= 16785408 ORDER BY g.start DESC, g.end DESC LIMIT 1 ) AS t WHERE t.end >= 16785408; Here's the code I'm trying: <?php $php_scripts = '../../php/'; require $php_scripts . 'PDO_Connection_Select.php'; require $php_scripts . 'GetUserIpAddr.php'; function mydloader($l_filename=NULL) { $ip = GetUserIpAddr(); if (!$pdo = PDOConnect("foxclone_data")) { exit; } if( isset( $l_filename ) ) { $ext = pathinfo($l_filename, PATHINFO_EXTENSION); $stmt = $pdo->prepare("INSERT INTO download (address, filename,ip_address) VALUES (?, ?, inet_aton('$ip'))"); $stmt->execute([$ip, $ext]) ; $test = $pdo->prepare("SELECT t.id FROM ( SELECT g.id FROM lookup AS g WHERE g.start <= inet_aton($ip) ORDER BY g.start DESC, g.end DESC ) AS t WHERE t.end >=inet_aton($ip)"); $test ->execute() ; $ref = $test->fetchColumn(); $ref = intval($ref); $stmt = $pdo->prepare("UPDATE download SET ref = '$ref' WHERE address = '$ip'"); $stmt->execute() ; header('Content-Type: octet-stream'); header("Content-Disposition: attachment; filename={$l_filename}"); header('Pragma: no-cache'); header('Expires: 0'); readfile($l_filename); } else { echo "isset failed"; } } mydloader($_GET["f"]); exit; It gives the following error: QuoteFatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '.144.181) ORDER BY g.start DESC, g.end DESC ) AS t WHERE t.end >=inet_aton(7' at line 1 in /home/foxclone/test.foxclone.com/download/mydloader.php:19 Stack trace: #0 /home/foxclone/test.foxclone.com/download/mydloader.php(19): PDO->prepare('SELECT t.id FRO...') #1 /home/foxclone/test.foxclone.com/download/mydloader.php(38): mydloader('foxclone40a_amd...') #2 {main} thrown in /home/foxclone/test.foxclone.com/download/mydloader.php on line 19 How do I fix this? This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=348309.0 The Script:
<?php include("connect.php"); ?> <?php echo "<h1>The Hashtag: </h1>"; if(isset($_GET['hashtag'])){ echo $_GET['hashtag']; } // Select the ID of the given hashtag from the "hashtags" table. $tqs = "SELECT `id` FROM `hashtags` WHERE `hashtag` = '" . $_GET['hashtag'] . "'"; $tqr = mysqli_query($dbc, $tqs) or die(mysqli_error($dbc)); $row = mysqli_fetch_assoc($tqr); // This prints e.g.: // 100 echo "<br/><br/>"; print_r($row['id']); // Select the threads from the "thread" table which contains the hashtag ID number. $tqs_two = "SELECT * FROM `thread` WHERE `hashtag_id` IN ('" . $row['id'] . "')"; $tqr_two = mysqli_query($dbc, $tqs_two) or die(mysqli_error($dbc)); $row_two = mysqli_fetch_assoc($tqr_two); echo "<br/><br/>"; print_r($row_two); ?>The script should select the rows by that ID number of the hashtag. It should look in the "hashtag_id" column of the table and see if that ID number can be found there, if it can be found there, then it should select that row. The ID numbers are inside that "hashtag_id" column separated by commas. Example: 98, 99, 100My Question: How to do the SQL query so it selects the rows by the hashtag ID number? Edited by glassfish, 17 October 2014 - 10:35 AM. Last Christmas my wife bought me a book on html and css because I said that I have always wanted to write a website. Over the last 10 months I have really enjoyed learning web design and have progressed to try and learn php and using myPHPadmin databases.
I am now trying to write a private message function. I've got a members database and a conversation database. I am trying to filter out whether a private message is 'read' or 'unread', but whatever I try it is still listing all messages under both options. I've spent 48 hours staring at this bit of code. Can anyone see what I have done wrong? The relevant (and self-explanatory) fields from my members database a id username member_first_name member_last_name The relevant fields from my conversation database a id id2 (always set as '1' to count messages in a conversation) member1 (the initial sender of the first message) member2 (the initial recipient of the first message) read1 (member1 has read this message default to yes when message sent and to no when message received) read2 (member2 has read this message default to yes when message sent and to no when message received) removed1 (member1 has deleted this message from their record) removed2 (member2 has deleted this message from their record) time (timestamp) <?php $query1 = DB::getInstance()->query("SELECT c1.id, c1.title, c1.time, c1.removed1, c1.removed2, count(c2.id) AS reps, m.id as memberid, m.username m.member_first_name, m.member_last_name FROM conversation as c1, conversation as c2, members as m WHERE ((c1.member1='{$logid}' AND c1.read1='No' AND c1.removed1='No' AND m.id=c1.member2) OR (c1.member2='{$logid}' AND c1.read2='No' AND c1.removed2='No' AND m.id=c1.member1)) AND c1.id2='1' AND c2.id=c1.id GROUP BY c1.id ORDER BY c1.id DESC"); $query2 = DB::getInstance()->query("SELECT c1.id, c1.title, c1.time, c1.removed1, c1.removed2, count(c2.id) as reps, m.id as memberid, m.username, m.member_first_name, m.member_last_name FROM conversation as c1, conversation as c2, members as m WHERE ((c1.member1='{$logid}' AND c1.read1='Yes' AND c1.removed1='No' AND m.id=c1.member2) OR (c1.member2='{$logid}' AND c1.read2='Yes' AND c1.removed2='No' AND m.id=c1.member1)) AND c1.id2='1' AND c2.id=c1.id GROUP BY c1.id ORDER BY c1.id DESC"); ?> UNREAD MESSAGES (<?php echo intval($query1->count()); ?>) <br> READ MESSAGES (<?php echo intval($query2->count()); ?>)I've tried running through things in a logical path: UNREAD MESSAGES member1 = logged in user read1 = No removed1 = No members.id = member2 OR member2 = logged in user read2 = No removed2 = No members.id = member1 READ MESSAGES member1 = logged in user read1 = Yes removed1 = No members.id = member2 OR member2 = logged in user read2 = Yes removed2 = No members.id = member1 I can't understand how if 'read1 = yes and the logged in user is member1, why they are being counted in the unread list. Can anyone see what I have done wrong? Edited by MartynLearnsPHP, 15 November 2014 - 08:05 AM. [text]I created two tables in a database called 'members' and 'blogs'. The blogs table uses the primary key of the members table (member_id), as a foreign key. The member_id is an auto incremented column in the members table and when I query and print out the rows of this table, the member_id values for the two members I created, turn out to be 1 and 2 as expected. Now when I use a subselect query in an insert statement, to input member_id values into the blogs table, and then query the rows of this table, both member_id values show up as 0. I will display both tables and the insert query for the blogs table below. Can anyone identify the problem? I'm convinced there is something about the subselect query that I'm not getting right. Ill also include the select query that displays the results of the blogs table just in case. [/text] Code: [Select] <?php $query = "CREATE TABLE members ( member_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , username VARCHAR( 50 ) NOT NULL UNIQUE, firstname VARCHAR( 50 ) NOT NULL , lastname VARCHAR( 50 ) NOT NULL , title VARCHAR(10), password VARCHAR( 50 ) NOT NULL , primary_email VARCHAR(100), secondary_email VARCHAR(100), register_date DATE, ip VARCHAR( 50 ) NOT NULL , UNIQUE (username) )"; ?> <?php $query = "CREATE TABLE blogs ( blog_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , member_id INT UNSIGNED, like_id INT UNSIGNED, title VARCHAR( 500 ) NOT NULL, entry VARCHAR( 2000 ) NOT NULL , blog_date DATE )"; ?> <?php $query = "INSERT INTO blogs ( member_id, title, entry, blog_date) VALUES ( 'SELECT member_id FROM members', '{$_POST['title']}', '{$_POST['entry']}', NOW())"; ?> <?php $query= 'SELECT * FROM blogs'; if($r = mysql_query ($query)) {//Run the query. //Retrieve and print every record. while ($row = mysql_fetch_array ($r)) { print " {$row['title']}" ; print " {$row['entry']}" ; print " {$row['blog_date']}" ; print " {$row['member_id']}" ; } } else {//Query didn't run. die (' Could not retrieve the data becasue: .mysql_error(). '); }//End of query IF. mysql_close(); //Close the database connection. ?> Any help is appreciated. I'm trying to figure out some pagination on a left joined query, and not having any luck. The query seems to be pulling the entire database, so I went into the query's WHERE and added the table name "descriptors." Now I'm getting this error with the below query: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /data/21/2/40/160/2040975/user/2235577/htdocs/leafsearch4.php on line 35 also: Unknown column 'descriptors.leaf_shape' in 'where clause' I thought this was syntax, but maybe I'm missing something. Code: [Select] $query = "SELECT COUNT(*) as num FROM descriptors LEFT JOIN plantae ON (descriptors.plant_id = plantae.plant_name) WHERE `descriptors.leaf_shape` LIKE '%$select1%' AND `descriptors.leaf_venation` LIKE '%$select3%' AND `descriptors.leaf_margin` LIKE '%$select4%'"; $total_pages = mysql_fetch_array(mysql_query($query)); |