PHP - Is There A Way To Make Rsults From Sql Query Into An Array
Ok, so this seems kinda vague, cus normally thats what you do, however I am talking about a differnt kinds of output from a query... Here is what i am a talking about:
My Query Code: $query = "SELECT * FROM settings WHERE storeid='store350' "; $which = $handle_db2; $result = mysql_query($query,$which); $num = mysql_num_rows ($result); $id = mysql_result($result,$i,"id"); $storeid = mysql_result($result,$i,"storeid"); $tinypass = mysql_result($result,$i,"tinypass"); $taxsetting = mysql_result($result,$i,"taxsetting"); $gst = mysql_result($result,$i,"gst"); $pst = mysql_result($result,$i,"pst"); $hst = mysql_result($result,$i,"hst"); $canpar = mysql_result($result,$i,"canpar"); $cp_fuelcharge = mysql_result($result,$i,"cp_fuelcharge"); $cp_markup = mysql_result($result,$i,"cp_markup"); $fedex = mysql_result($result,$i,"fedex"); $fe_fuelcharge = mysql_result($result,$i,"fe_fuelcharge"); $fe_markup = mysql_result($result,$i,"fe_markup"); $dhl = mysql_result($result,$i,"dhl"); $dh_fuelcharge = mysql_result($result,$i,"dh_fuelcharge"); $dh_markup = mysql_result($result,$i,"dh_markup"); $tnt = mysql_result($result,$i,"tnt"); $tn_fuelcharge = mysql_result($result,$i,"tn_fuelcharge"); $tn_markup = mysql_result($result,$i,"tn_markup"); As you can see, my variables are the same as my table column names... now if this "project" goes thorugh I could have hundreds of columns, I would hate to have to define each one making my file even larger. Is there a way to make it dynamically create the variables via an array or something Theoriticaly something like this: $query = "SELECT * FROM settings WHERE storeid='store350' "; $which = $handle_db2; $result = mysql_query($query,$which); $num = mysql_num_rows ($result); (While loop here) $Table_name_var = mysql_result($result,$i,"table_name"); (end while loop) Possible? Similar TutorialsIf I have a db with these fields: displayname, title and I run a successful query on the db, will this code: if (mysql_num_rows($results) == 0) { return "!fail"; } else { while ($row = mysql_fetch_assoc($results)) { extract($row); } return $row; } create an associative array of $var = array(array('displayname' => value, 'title' => value), array('displayname' => value, 'title' => value)...) If not, is there a way to do so, especially when I will not know the names or number of fields in a db table? I am trying to get my database entry's to C# in Unity to display them. This formatting works echo ("|".$row['GUID']. PHP_EOL. "|".$row['userName']. PHP_EOL. "|".$row['health']. PHP_EOL. "|".$row['level']. PHP_EOL. "|".$row['points']. PHP_EOL. "|".$row['killBonus']. PHP_EOL. "|".$row['killRate']. PHP_EOL. "|".$row['kills']. PHP_EOL. "|".$row['misses']. PHP_EOL. ";"); But When I get it into Unity using this code string Data_string = www.downloadHandler.text; string[] DataArray; DataArray = Data_string.Split('|'); //Debug.Log(DataArray); string guid = (DataArray[0]); Debug.Log(guid); string username = (DataArray[1]); Debug.Log(username); int health = System.Convert.ToInt32(DataArray[2]); Debug.Log(health); int level = System.Convert.ToInt32(DataArray[3]); Debug.Log(level); int points = System.Convert.ToInt32(DataArray[4]); Debug.Log(points); int killBonus = System.Convert.ToInt32(DataArray[5]); Debug.Log(killBonus); float killRate = float.Parse(DataArray[6]); Debug.Log(killRate); float kills = float.Parse(DataArray[7]); Debug.Log(kills); float misses = float.Parse(DataArray[8]); Debug.Log(misses); It puts out the first string "GUID" but then throws an error before "username". Can someone help me understand what I am doing wrong?
This is the error I am getting.
FormatException: Input string was not in a correct format. System.Number.StringToNumber (System.String str, System.Globalization.NumberStyles options, System.Number+NumberBuffer& number, System.Globalization.NumberFormatInfo info, System.Boolean parseDecimal) (at <df7127ba07dc446d9f5831a0ec7b1d63>:0) System.Number.ParseInt32 (System.String s, System.Globalization.NumberStyles style, System.Globalization.NumberFormatInfo info) (at <df7127ba07dc446d9f5831a0ec7b1d63>:0) System.Int32.Parse (System.String s, System.IFormatProvider provider) (at <df7127ba07dc446d9f5831a0ec7b1d63>:0) System.Convert.ToInt32 (System.String value) (at <df7127ba07dc446d9f5831a0ec7b1d63>:0) Login+<LoginCalled>d__4.MoveNext () (at Assets/CODE/Login.cs:52) UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17) Edited December 14, 2019 by J450n 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? I want to select 20 sites randomly. But when I generate a random number and use it in my query to extract the site information. But if an ID doesn't exist with that random number, it doesn't display information. How can this be fixed? $amount_get = mysql_query("SELECT id FROM users"); $random = rand(0,mysql_num_rows($amount_get)); for($amount = $random; $amount > 30; $amount = $random) { $query = mysql_query("SELECT site_url,username,id FROM users WHERE id='$amount' LIMIT 150"); $data_grab = mysql_fetch_assoc($query); echo $data_grab['site_url']."<input type='submit'>"; } Hello all, I've made this for users login, and now I want the user to only be able to see his info so how can I use the $_SESSION['userid'] to search the database for it's value and echo results? here is my code, I want to use the session value instead of get Code: [Select] <? if (isset($_GET['id'])) { $con = mysql_connect("supremecenter14.co.uk","teko_waw","tmisabro77"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("teko_waw", $con); $result = mysql_query("select * from users where id = '{$_GET['id']}'"); $row = @mysql_fetch_array($result); echo "<table width=98%>"; echo "<tr>"; echo "<td valign=\"top\" width=\"120px\">"; $rowid = $row['id']; echo "<td valign=\"top\">"; echo "<table> <tr> <td valign=\"top\" class=\"searchtitle\"> ".$row['fname']. ' ' .$row['mname']. ' ' .$row['lname']." </td> </tr>"; ?> and here is where they're set Code: [Select] if (isset($_POST['email'])) { $email = mysql_real_escape_string($_POST['email']); $password = mysql_real_escape_string($_POST['password']); //Query $results = mysql_query("SELECT * FROM users WHERE email = $email AND password = $password"); if(!result) { $_SESSION['error'] = '<span style="color: red">Login Failed. Email or Password is Incorrect <br/>'; } else { $row = mysql_fetch_assoc($results); $_SESSION['userid'] = $row['id']; $_SESSION['email'] = $email; $_SESSION['error'] = 'Login Successful<br/>. Welcome,'. $email; } Given array Code: [Select] Array ( [Post] => Array ( [title] => new with has many through for tags [body] => hello tags [category_id] => 11 [tags] => one two three [mark] => 1 ) ) I need to make an array something like this: Code: [Select] Array ( [Post] => Array ( [title] => new with has many through for tags [body] => hello tags [category_id] => 11 [mark] => 1 ) [Tag] => Array ( [0] => Array( [name] => one ) [1] => Array( [name] => two ) [2] => Array( [name] => three ) ) ) How can i make it? Is there a cleaner way to do this? $query = "SELECT branches.Language FROM eua_users, branches WHERE eua_users.AssignedBranch = branches.country" ; include("dbconnectlocal.php") ; $result = mysql_query($query) ; $row = mysql_fetch_object($result) ; $usrlang = $row->Language ; $query = "SELECT UserName, Email FROM eua_users WHERE UserName = '$user'" ; include("dbconnectlocal.php") ; $result = mysql_query($query) or die(mysql_error()); $row = mysql_fetch_object($result) ; $branchmail = $row->Email ; $query = "SELECT $usrlang FROM autoreplies WHERE ReplyID = '0'" ; include("dbconnectlocal.php") ; $result = mysql_query($query) or die(mysql_error()) ; $row = mysql_fetch_object($result) ; $message = $row->$usrlang ; $query = "SELECT $usrlang FROM autoreplies WHERE ReplyID = '1'" ; include("dbconnectlocal.php") ; $result = mysql_query($query) or die(mysql_error()) ; $row = mysql_fetch_object($result) ; $url = $row->$usrlang ; $query = "SELECT $usrlang FROM autoreplies WHERE ReplyID = '2'" ; include("dbconnectlocal.php") ; $result = mysql_query($query) or die(mysql_error()) ; $row = mysql_fetch_object($result) ; $subject = $row->$usrlang ; Hi, I have a regular MySQL query that displays it's results to the screen in a browser as an HTML table, all nice and fruity. The managers who use this function like to send out the results to staff, currently they simply take a screen shot and paste it into an email to send out to everyone - quite an overhead on the email system, company network, not to mention the time taken to do the screen shot and paste it into an email in the first place. It would be good if I could include a standard HTML form button (preferably) or link on the results page to shove the displayed results to Outlook as an email, that contains the table all ready for the manager to add in what ever they want to the email and then send (usually to 'all@mysite.com' but it would be useful if they could change or add to this as they see fit). This is kind of what happens with a normal mailto HTML tag, except I want it to contain the MySQL query result too. This is the existing table output routine (something I inherited): Code: [Select] /* Output data into a HTMl table */ echo "<p>"; echo "<table align=center width=800 border=\"1\">"; echo "<tr>"; echo "<td BGCOLOR=\"#ffcc00\"><strong>Agent name</strong></td> <td BGCOLOR=\"#ffcc00\"><strong>Number of calls made / handled</strong></td> <td BGCOLOR=\"#ffcc00\"><strong>Average call minutes</strong></td> <td BGCOLOR=\"#ffcc00\"><strong>Total mins (inc hours + secs rounded)</strong></td> </tr>"; while($row = mysql_fetch_row($numresults)) { echo "<tr>"; for($i=0; $i < mysql_num_fields($numresults); $i++) { echo "<td align=center width=443>$row[$i]</td>"; } echo "</tr>\n"; } echo "</table></p>"; $looponce = 1; foreach ($this->info as $k => $v) { if ( (($k == 'subject') && ($v['required'])) && (!$this->settings['customSubject'])) { for ($i = 0; $i <= 0; $i++) { $output[] = $this->display_errors('error_system_subject'); } } if ( (($k == 'name') && (!$v['required'])) || ((!array_key_exists("name", $this->info)) && ($looponce == 1)) ) { $output[] = $this->display_errors('error_system_name'); $looponce++; } } That is my loop that i check things in. What i'm more interested in is the name if statement. If currently checks for a name key in an array(below) and makes sure that it is set to required. If it's not set to required, print out a system error and die()'s. I'm looking for ways to remove the need for program errors and just change them to what is needed to run. What i know how to do is, get into the inner array, what i don't know is how to edit the data and put it back exactly as it was given to me. The inner array data can be put back in any order, but the outer array must be in exact order as it was given. above code $this->info = $formdata; $formdata = array( 'name' => array('name'=>"Full Name", 'required'=>false, 'type'=>'text'), # This needs to be required=>true, but i can't trust the user, which is why i have the error. 'telephone' => array('name'=>"Telephone", 'required'=>false, 'type'=>'phone'), ); Any help is greatly appreciated, also am i doing the foreach loop in the code above in an efficient manner or is there another way? Hey, I've been developing a browsergame. In this you are able to produce something ("weed"). Now I've got some kind of trouble with the function that is responsible for updating the "weed" on the user accounts. Im going to explain, how my script is working First step: Loading the datas from "worlds". In this case id, weed_factor, weed_basis. What this is required for you will see in the next steps <?php include 'includes/settings/mysql.php'; mysql_connect($dbhost, $dbuser, $dbpass); mysql_select_db($dbbase); $time = time(); $update_weed_world_data_sql = "SELECT id, weed_factor, weed_basis FROM worlds"; $update_weed_world_data_res = mysql_query($update_weed_world_data_sql) OR DIE (mysql_error()); while($update_weed_world_data_while = mysql_fetch_assoc($update_weed_world_data_res)){ $update_weed_world_id = $update_weed_world_data_while['id']; $update_weed_world_basis[$update_weed_world_id] = $update_weed_world_data_while['weed_basis']; $update_weed_world_factor[$update_weed_world_id] = $update_weed_world_data_while['weed_factor']; global $update_weed_world_basis; } Second step: This is the function which is editing each account by the data given as parameters. function do_update_weed($profile_id,$world,$update,$level,$time){ $update_weed_period = $time - $update; $update_weed_add = ($update_weed_period / 3600 * $update_weed_world_basis[$world] * pow($update_weed_world_factor[$world],$level)) +1; echo $update_weed_world_basis[$world]; echo "<br>"; mysql_query("UPDATE profiles SET weed = weed +$update_weed_add, weed_update = $time WHERE id = $profile_id LIMIT 1"); } Note: echo $update_weed_world_basis[$world]; doesnt result an output. In step three, the accounts are loaded: function todo_update_weed($time){ $todo_update_weed_sql = "SELECT * FROM profiles WHERE weed_update < $time"; $todo_update_weed_res = mysql_query($todo_update_weed_sql) or die (mysql_error()); while($todo_update_weed_while = mysql_fetch_assoc($todo_update_weed_res)){ do_update_weed( $todo_update_weed_while['id'], $todo_update_weed_while['world_id'], $todo_update_weed_while['weed_update'], $todo_update_weed_while['level_farm'], $time ); } } And the last step is calling function "todo_update_weed" with the time. todo_update_weed($time); I script calculate the time between the last update and the current time. This make a difference in time. With this value I calculate something else. And then the update time has to be saved. The script has just working fine, when I set the variable "$update_weed_add" with a fix value. But by now the script doesn't work, because I don't know how to make the array available inside functions. I considered whether I put the database-function for the world_data inside the function that updates the profiles. But if I do this, the database will be called thousands of times... Hope anybody has a nice idea to fix the problem I'm using a web service call, my response comes back as an array:
stdClass Object ( [contractVehicle] => Array ( [0] => ITSchedule70 [1] => ITCommodityProgram ) ) I then need to hand this response off to anther developer who needs to know that "ITSchedule70" is the selected Contract Vehicle (actually there could be more than one, this only returns one for now), so he can insert it into a SQL query against a MySQL database (to match "Products" with the right "Contract Vehicle". So basically how do I do that? How to wrap it up and send it off, and how to insert a query? I am trying to compare a teams average attendance compared to the average across all teams. The query that show the average by team (column 'atte') is Code: [Select] $att_table = mysql_query(" SELECT t.team_name as Tm , ROUND(AVG(g.attendance))atte , SUM(g.attendance) tot , MAX(g.attendance) max , MIN(g.attendance) min from teams t left join all_games g on t.team_id = g.home_team WHERE comp = '1' AND home_goals IS NOT NULL AND date BETWEEN '2010-07-01' AND '2011-06-31' GROUP BY t.team_id ORDER BY atte DESC ");A simple query to show the total average is Code: [Select] $lgeav = mysql_query(" (AVG(g.attendance))atte2 from all_games g WHERE comp = '1' AND home_goals IS NOT NULL AND date BETWEEN '2010-07-01' AND '2011-06-31' ");I am hoping to put the second query into an array and use the two to show the teams whose own average attendance is higher than the total average attendance in bold, with something along the lines of while ($row_att_table = mysql_fetch_assoc($att_table)){ if ($row_att_table['atte'] > $lgeav['atte2']) echo '<tr style="font-weight:bold">'; else echo '<tr>'; I know that this can be done with views but in an attempt to broaden my knowledge (and also in case I ever have to do something similar on MySQL4) I wondered if there was a simple way to do this through PHP? Thanks in advance Steve I'm trying to delete items from a table by selecting them via checkboxes. I managed to post all the ids of the checkboxes I filled in the url like this, check_box=154,153,152 etc... and turned that into an array Array ( [0] => 154 [1] => 153 [2] => 152 ) Array using $delete_selected = $connection->real_escape_string($_POST['check_box']); $check_box_array = explode(",", $delete_selected); Now I can't figure out how to put that into $sql = "DELETE FROM categories WHERE cat_id = '$delete_selected'"; it only deletes one. Any ideas? Hi there i need to make an array with the result from a query (numbers 1-4) I need to calculate how many occurances of each 1-4 number is in the table. Im new to this and havent much experience with arrays but ive managed to create an array and echo the results: 2 Class 3 Class 1 Class 3 Class 3 Class 2 Class 2 Class 2 Class So i need to somehow Add the occurance of them and echo the results e.g. 4 Class 2, 1 Class 1, 3 Class 3. If someone could please point me in the right direct that would be great. Code: [Select] $colname_Recordset1 = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_Recordset1 = (get_magic_quotes_gpc()) ? $_SESSION['MM_Username'] : addslashes($_SESSION['MM_Username']); } mysql_select_db($database_swb, $swb); $query = sprintf("SELECT Class FROM ships WHERE PlayerName = %s", GetSQLValueString($colname_Recordset1, "text")); $result = mysql_query($query, $swb) or die(mysql_error()); while($row = mysql_fetch_array($result)){ echo $row['Class']. " Class "; echo "<br />"; } mysql_free_result($result);?>; Thank You Hi I am trying to store the results of a mysql query into a php array. Here is the code i am using $test = implode(",",$_GET['checkbox']); $query = mysql_query("SELECT categoryTitle FROM `category` where categoryid in ($test)"); $test2 = array(); while ($result = mysql_fetch_assoc($query)) { $test2[] = $result; } $test3 = implode(", ",$test2); print_r($test3); Everything works fine until implode the array. When i try to print after the implode the result is "Array, Array". if i remove the implode it prints "Array ( => Array ( [categoryTitle] => Escalators & Lifts ) [1] => Array ( [categoryTitle] => Human Resource/Payroll/ Training ) )" The values here are ture. Im thinking that its storing an array inside another array so cannot implode. Is there something i can do to solve this
This is the cart array: I want the key to be "id" and the value to be "quantity" like it is for the cart array. How do I define my cart_items array using variables? Hi, I am creating a new menu (food) in my system. This consists of a menu, menu_items and menu_connection table. I can insert the menu name just fine and return its id just fine. When inserting the menu items, i need to get each of the menu_item_ids to use in the query that inputs the menu_connection. This is what i have so far: if ($_SERVER['REQUEST_METHOD']=="POST") { ///////////////////// //menu name insert // ///////////////////// $mname = mysqli_real_escape_string($conn, $_POST['newMenuName']); $stmt=$conn->prepare(' INSERT IGNORE INTO ssm_menu (menu_name) VALUES (?); '); $stmt->bind_param('s',$mname); $stmt->execute(); $menuInsId = $stmt->insert_id; echo $menuInsId; $stmt->close(); ///////////////////// //menu item insert // ///////////////////// $mitname = $_POST['newMenuItem']; $stmt=$conn->prepare(' INSERT IGNORE INTO ssm_menu_items (menu_item_name) VALUES (?); '); foreach ($_POST['newMenuItem'] as $k => $nmItem) { $mitname = mysqli_real_escape_string($conn, $nmItem); $stmt->bind_param('s',$mitname); $stmt->execute(); $menuItmInsId = $stmt->insert_id; echo $menuItmInsId; } $stmt->close(); /////////////////////////// //menu connection insert // /////////////////////////// $stmt=$conn->prepare(' INSERT IGNORE INTO ssm_menu_connection (menu_id, menu_item_id) VALUES (?,?) '); foreach ($_POST['newMenuItem'] as $k => $nmItem) { $stmt->bind_param('ii',$menuInsId, $menuItmInsId); $stmt->execute(); $connectionInserId = $stmt->insert_id; echo $connectionInserId; } $stmt->close(); } Currently it is inserting each of the items in the connection table with the same id - i understand why but i dont know how to collect up all of the ids to use later Hello just wondering if someone can help me... I have a select multiple form that sends the id numbers of records I want to get... how do I construct the query to the mysql db to do this? $array-$_POST['form-array'] so something like $r = ("SELECT column from 'Table' WHERE ID = (array, values, here)") Thanks for any help. 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 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 |