PHP - Array From Select Query
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 Similar Tutorialshi 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 all, probably a fairly straightforward question, but I can't find the answer I'm looking for: I have an array 'idents' that contains ID numbers. I now want to write a MySQL query that selects all values of the table-field 'email' where the field 'ID' = any of the IDs stored in 'idents'. Then I want to put those emails in an array 'emails'. So e.g. my table is as follows: ID | email ---------------------- 111111 | email1 222222 | email2 333333 | email3 444444 | email4 555555 | email5 666666 | email6 and the array 'idents' is as follows: '111111','444444','555555' then I want the query to return 'emails' = array('email1','email4','email5'); Thanks for your help! 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 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, 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.
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
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 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>"); } 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
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 ? 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 :| So I'm querying my database to add the results (mapID's) into a PHP array. The MySQL query I used in the below code would usually return 10 values (only 10 mapID's in the database) Code: [Select] while($data = mysql_fetch_array(mysql_query("SELECT mapID FROM maps"))){ $sqlsearchdata[] = $data['mapID']; } Instead the page takes ages to load then gives this error: Quote Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate 16 bytes) It says the error begins on the first line of the above code. I'm assuming this is not the right way to add the value from the MySQL array into a normal PHP array. Can anyone help me? hi all, in mysql, how can i extract 100 words before and 100 words after my search key? example: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla est nibh, mattis eu mattis id, pulvinar eu augue. Duis ut sem nisi. Sed id ante sed orci vestibulum lacinia ac id nibh. Donec cursus, elit eget auctor semper, ipsum eros laoreet quam, nec ullamcorper" vestibulum is my search key [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. The 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`"; 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)); $var = @$_GET['q'] ; $trimmed = trim($var); $table = @$_GET['field']; $query="SELECT * FROM contacts WHERE @'table' contains @'trimmed' order by id"; $result=mysql_query($query); $num=mysql_numrows($result); Why wont this work? Zacron 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? hi im trying to use query to select from a table where the price is between to values that the user has to input such as min of 3 and max of 8 and return all the fields from the database where it is true im unsure how to do this but this is what i have so far
$res = pg_query ($conn, "SELECT ref,artist,composer,genre,title,album,label,price,description FROM music WHERE price = < && > "); |