PHP loop increment - php

I have a PHP loop generating a dataset for a chart. It queries two fields I have in a database table.
<?php
$server = "myserver:1234";
$user="dbuser";
$password="userpass";
$database = "dbname";
$connection = mysql_connect($server,$user,$password);
$db = mysql_select_db($database,$connection);
$query = "SELECT X, Y FROM dbtable";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$dataset1[] = array($row['X'],$row['Y']);
}
$final = json_encode($dataset1,JSON_NUMERIC_CHECK);
?>
Currently data in X is meaningless (it's actually an ID column), and a number increment of 1 starting at 1 will be more useful. This is because I only want to plot a line chart, where X values are fixed. ID would be fine but the values put distracting axis labels on my chart.
How can I use PHP to generate this instead of the database select that I currently have?
Many thanks:)

Declare a variable outside your loop and increment it on each iteration:
$i = 1;
while($row = mysql_fetch_assoc($result))
{
$dataset1[] = array($i, $row['Y']);
$i++;
}

Related

Create PHP array out of table column

I am trying to create a loop that displays each row in a table. I think I need to make an array out of the PK, but I can't figure out how to do that. Here is my code so far:
$conn = dbConnect('read');
$getData = 'SELECT * FROM table';
$allData = $conn->query($getdata);
if (!$allData) {
$error = $conn->error;
} else {
$data = $allData->fetch_assoc();
$rowId = array($data['PK']);
} while ($rowId <= count($rowId)) {
// code to be run for each row
$rowId++;
}
EDIT: Sorry my question is confusing, I'm new to PHP.
Your question is a bit confusing but I think this is what you are trying to do:
$sql = 'SELECT * FROM table';
$query = $conn->query($sql);
while ($row = $query->fetch_assoc()) {
$data[$row['PK']] = $row;
}
That would iterate over each row, creating an array and using the row's value for column PK as an associative array key.
fetch_assoc() (I assume mysqli here now) doesn't fetch all data from a result, but one row after each other. So you don't need to make an array of $row['PK'], but need to loop over the results.
$conn = dbConnect('read');
$getData = 'SELECT * FROM `table`'; // you would need backticks here, if the table really is called "table" (what you shouldn't do...)
$result = $conn->query($getData); // it's not 'allData', it is a result_set. And be carefull about Case! $getData!=$getdata
if (!$result) {
$error = $conn->error;
} else {
$cnt=0;
while($row = $result->fetch_assoc()) {
// code to be run for each row
// you can display $row['PK'] now:
echo $row['PK'];
// or add that value to something else, whatever you need
$cnt = $cnt+$row['PK'];
// or to have a new array with the values of one table-column:
$columnRows[] = $row['PK'];
}
// now you can use the created array
foreach($columnRows as $PK) {
echo $PK;
}
}

Setting PHP variables from Database Using MYSQL

Looking to select multiple values from the database and echo with PHP. (Newbie)
For instance:
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 4
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 5
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 6
How would I set the variables.. something along the lines of this using MYSQLi for multiple variables?
$sqlStremail = "SELECT subcheckr
FROM login
WHERE username = '$u'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$variable = $row["subcheckr"];
Truly appreciate any help.
Yes. Though if your query returns multiple rows, you'll need to use:
while ($row = mysqli_fetch_assoc($result))
{
//do something here
}
you need to make a loop for , foreach or a while loop
ex
while ($row = mysqli_fetch_assoc($result))
{
}
This should do it. First you need to connect, then you build your query. If query fails display an error so you know what went wrong. Then build your data array and use it.
$db = mysql_connect("localhost", "mysql_user", "mysql_password");
$sqlStremail = "SELECT `subcheckr`
FROM `login`
WHERE `username` = '".$u."'"; //needs to be concatenated
$result = mysql_query($sqlStremail, $db);
if(!$result) {
echo "query failed:". mysql_error();
exit;
}
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data = $row;
}
echo $data['sponsor'];
echo $data['contact'];
echo $data['script'];
//etc

Database only fetching first variable

This php is populated by a form posting variables to it. Once it has the car model it should be collecting data from the database and storing each variable for use further down the code. This is used alongside another database so I would rather populate each var list before moving ahead.
The problem is, the database is only collecting the first variable and none of the following variables. How can I call all variables and hold them there for use in the html below.
eg. The client selects the car model, submits and the form sends the model to this code where the database should collect more information about the car for use in a automatically generated PDF brochure.
Thanks for your help!!
//database, table CARS and store variables
$conn = mysql_connect("localhost", "blah", "blah");
mysql_select_db("car_db", $conn);
$sql = "SELECT * FROM cars WHERE modelname = '$carmodel'" or die(mysql_error());
$rs_result = mysql_query ($sql, $conn);
while ($row = mysql_fetch_assoc($rs_result))
//create variables from database entry
$dbbrand = $row['brandname'];
$dbseries = $row['series'];
$dbprice = $row['price'];
$dbseats = $row['seats'];
$dbtype = $row['type'];
$dbcolor = $row['color'];
// -------------------- HTML CONTENT -------------------- //
$html = "
<body>
<!--Print Wrap Start-->
<div id=\"content\">
<!--Header with logo-->
<div id=\"div-head\"><div id=\"div-head\"><span class=\"important\">". $dbbrand ."</span></div></div>
<!--start relative container-->
<div id=\"div-1\"><span class=\"important\">". $dbseries ."</span>
Assuming your syntax is copied as stated above, you need to put braces "{" and "}" around your variable assignments.
$sql = "SELECT * FROM cars WHERE modelname = '$carmodel'" or die(mysql_error());
$rs_result = mysql_query ($sql, $conn);
while ($row = mysql_fetch_assoc($rs_result)) { <----- here
//create variables from database entry
$dbbrand = $row['brandname'];
$dbseries = $row['series'];
$dbprice = $row['price'];
$dbseats = $row['seats'];
$dbtype = $row['type'];
$dbcolor = $row['color'];
} <---- here
The problem is here
while ($row = mysql_fetch_assoc($rs_result))
//create variables from database entry
$dbbrand = $row['brandname'];
That code assigns a record from the result set into the $row variable, which in only used to assign the current value into the $dbbrand variable below the loop.
The while loop only controls one line of code and that is $dbbrand = $row['brandname'];. You need to wrap all the relevant lines of code below as a apart of the the while loop. Below I will demonstrate and correct for the other logical error in your code.
$data = array();
int a=0;
while ($row = mysql_fetch_assoc($rs_result)) {
//create variables from database entry
$data[a]['dbbrand'] = $row['brandname'];
$data[a]['dbseries'] = $row['series'];
$data[a]['dbprice'] = $row['price'];
$data[a]['dbseats'] = $row['seats'];
$data[a]['dbtype'] = $row['type'];
$data[a]['dbcolor'] = $row['color'];
$a++;
}
If you want all values returned by the query, the adjustment to your code above will suffice.

MSSQL returns multiple rows into array, explode into one array per row

I have an MSSQL query where it SELECTS all rows that meet a specific criteria. In PHP I want to fetch that array, but then I want to convert it into one array per row. So if my query returns 3 rows, I want to have 3 unique arrays that I can work with.
I'm not sure how to go about this. Any help would be greatly appreciated!
Thanks, Nathan
EDIT:
$query = "SELECT * FROM applicants WHERE applicants.user_id ='{$_SESSION['user_id']}'";
$query_select = mssql_query($query , $connection);
if (mssql_num_rows($query_select) == 2){
$message = '2 students created successfully';
}
$i = 0;
while($row = mssql_fetch_array($query_select)) {
$student.$i['child_fname'][$i] = $row['child_fname'];
$student.$i['child_lname'][$i] = $row['child_lname'];
$i++;
}
$query_array1 = $student0;
$query_array2 = $student1;
You will notice from the code above that I am expecting two rows to be returned. Now, I want to take those two rows and create two arrays from the results. I tried using the solution that was give below. Perhaps my syntax is incorrect or I didn't understand how to properly implement his solution. But any help would be greatly appreciated.
$query = mssql_query('SELECT * FROM mytable');
$result = array();
if (mssql_num_rows($query)) {
while ($row = mssql_fetch_assoc($query)) {
$result[] = $row;
}
}
mssql_free_result($query);
Now you can work with array like you want:
print_r($result[0]); //first row
print_r($result[1]); //second row
...
$i=0;
while( $row = mysql_fetch_array(query){
$field1['Namefield1'][$i] = $row['Namefield1'];
$field2['Namefield2'][$i] = $row['Namefield2'];
$field3['Namefield3'][$i] = $row['Namefield3'];
$i++;
}
or if you preffer an bidimensional array:
$i=0;
while( $row = mysql_fetch_array(query){
$result['Namefield1'][$i] = $row['Namefield1'];
$result['Namefield2'][$i] = $row['Namefield2'];
$result['Namefield3'][$i] = $row['Namefield3'];
$i++
}

Using in_array to compare MySQL data

I have a table set up in MySQL with two columns:
ID (auto_increment)
recentlyplayed (VARCHAR, set up like "1 44" or "2 140", etc)
I'm trying to get the mysql data into an array and compare it to something defined outside MySQL. But it doesn't seem to work for some reason. Here is my code:
$whichPlaylist is a 1 character INT, and $num is a 3 character INT.
//Note: These values are actually received through file_get_contents('textfile.txt');
$whichPlaylist = "1";
$num = "44";
//Combine playlist number and video number
$joint = $whichPlaylist. "" .$num;
//Insert joint var into Mysql database
mysql_query("INSERT INTO recentlyplayed (numplayed) VALUES('$joint') ");
$query = "SELECT * FROM recentlyplayed";
$result = mysql_query($query) or die ("no query");
while($row = mysql_fetch_array($result))
{
$stored[] = $row['1'];
}
if (in_array($joint, $stored['1'])){
$reroll = 1;
}
echo $reroll;
Even if the same value of $joint is in the MySQL table, $reroll doesn't echo 1. Could this because of extra spacing when inserting the $joint variable? I'm actually getting the $whichPlaylist and $num from a text file that has a new line after the number. Any help is appreciated. :)
Move the While End braces after if statement, and see if it works.
Try this code in your script:
$stored = array();
while($row = mysql_fetch_array($result)) {
$stored[] = $row[1];
}
if (in_array($joint, $stored)){
$reroll = 1;
}
The array is $stored (not $stored['1']).

Categories