i'd like to write a function which grabs all fields from a database table and puts it in an array.
getting the database fields already works like this:
$sq = "select column_name,data_type from information_schema.columns
where table_name='users'";
i'm just not sure how to store them properly.
when having eg. this database structure:
fieldname type length
--------------------------------
id int 11
username varchar 50
pass varchar 50
lastlogin date
what's the best way to store this data in php in order querying it like this:
$field = myFields["username"];
echo $field->id."/".$field->type."/".field->length;
as you can see i'd like to access the data directly by field name
Make sure you connect to the database first. Then do:
$r = mysql_query('SELECT COLUMN_NAME AS fieldname,
DATA_TYPE AS type,
CHARACTER_MAXIMUM_LENGTH AS length
FROM information_schema.columns
WHERE table_name = "users" AND column_name = "username"');
if ($r)
{
$field = mysql_fetch_object($r);
// $field->type, $field->length, etc.
}
$sql = "YOUR QUERY HERE";
$res = mysql_query($sql);
while ($rowobj = mysql_fetch_object($res)) {
// do what you want to do with $rowobj
echo $rowobj->column_name1 . "<br />\n";
echo $rowobj->column_name2 . "<br />\n";
// ...rest of code...
}
Put your query into $sql variable and replace column_nameX in while loop with columns you SELECTed with your query.
$query = mysql_query("SELECT * FROM table");
$result = array();
while($row = mysql_fetch_array($query))
{
$username = $row['username'];
unset($row['username']);
$result[$username] = (object)$row;
}
Then you can access it by using:
$result['username']->id
Related
I'm trying to extract a string field, under a column called "whenadded", of a mysql table (called "values") with a php script. I'm using this code:
<?php
include("common.php");
$link=dbConnect();
$name = safe($_POST['name']);
$mysqldate = mysql_query("SELECT `whenadded` FROM `values` WHERE `name`= `$name`");
?>
In this table I have only two columns: name and whenadded. Both are strings.
If I try to display the result of $mysqldate, I don't see anything (white field).
[SOLVED] At the end I solved using this:
include("common.php");
$link=dbConnect();
$name = safe($_POST['name']);
$query = mysql_query("SELECT * FROM $dbName . `valorigps` WHERE name = '$name'");
while($row = mysql_fetch_array($query))
{
echo $row['whenadded'];
}
your query string shoud be this:
$mysqldate = mysql_query("SELECT whenadded FROM values WHERE name= '$name'");
or
$mysqldate = mysql_query("SELECT whenadded FROM values WHERE name= '{$name}'");
no need of quote for table columns!
I have a large table and would like to search all of the fields in one go but some of the fields are dates so the search I have created falls over when it hits those fields.
Is there a way to exclude certain types of fields when using this type of search?
$table = 'accounts';
$condition = 'tracey';
$sql = "SHOW COLUMNS FROM accounts";
$result = mysqli_query($mysqli,$sql);
if (mysqli_num_rows($result) > 0)
{
$i=0;
while ($row = mysqli_fetch_array($result))
{
if($i==0)
{
$q="select * from ".$table." where ".$row[0]." LIKE %".$condition."%";
}
else
{
$q.=" or ".$row[0]."="." LIKE %".$condition."%";
}
$i++;
}
}
$sql = $q;
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
$row = mysqli_fetch_array($result);
$answer = $row['phone_office'];
echo '<br><br>answer = '.$answer;
Or perhaps someone can suggest a better way of searching all of the fields in a table in one go?
To exclude certain types of fields You need to change the query SHOW COLUMNS FROM accounts with this one:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE (table_name=".$table.")AND(NOT(DATA_TYPE IN ('field_type_1','field_type_2',...)));
Where field_type_i is the name of an excluded type (for example 'timestamp')
I've been writing a script to display the names of users based on whether they are assigned an even or odd comment id. It calls up data from 2 different tables in the same database. Here is the table information:
Table 'comments' has the columns commentid, tutorialid, name, date: Table 'winners' has the columns pool, pool2, pool3, pool4, pool5, pool6, pool7. Table 'comments' has multiple rows that are updated through user input. Table 'winners' has only 1 row with numbers that are randomly generated daily.
The first part of the script that displays "Result 1" and "Result 2" is working properly. The part that isn't working is the part that calls up the usernames. I only want to display the usernames that corralate with the result that is displayed IE if Result 1 is chosen then I only want the usernames with even 'commentid's displayed.
<?php
$db = mysql_connect('localhost', 'username', 'pass') or die("Database error");
mysql_select_db('dbname', $db);
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
if ($row['pool'] % 2) {
echo "<h4>Result 1</h4>";
$names = get_names(1);
foreach($names as $name) {
echo $name . "<br/>";
}
} else {
echo "<h4>Result 2</h4>";
$names = get_names(0);
foreach($names as $name) {
echo $name . "<br/>";
}
}
function get_names($pool_result)
{
$name_array = array();
$query = "SELECT * FROM comments where mod('commentid',2) = $pool_result";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
array_push($name_array, $row['name']);
}
return $name_array;
}
?>
Can anyone figure out why this isn't working?
The SELECT statement with the mod is not referencing the field. Should be backticks instead of single quotes. Single quotes indicate a string constant, which would result in a constant result set (mod('commentid',2) appears to have a result of 0). It should be something like this:
$query = "SELECT * FROM comments where mod(`commentid`,2) = $pool_result";
Adding quotes around commentid treats it as a string, and you can't mod a string by an integer. Try the following instead:
$query = "SELECT * FROM comments WHERE commentid % 2 = $pool_result";
This was taken from the following Stack question: select row if the "value" % 2 = 1. MOD()
I need to read a text file, query the database table with that name, and store that table's data in another table. So far I have written this code but I don't know why it's not working.
foreach ($lindb as $namedb) {
$query = "SELECT * FROM ntable WHERE name =" .$namedb. "";
$result = mysql_query($query);
while ($r = mysql_fetch_array($result)) {
$query = "INSERT INTO ndtable (name,details,address,login,country) VALUES (\"".$r["name"]."\", \"".$r["details"]."\", \"".$r["address"]."\", \"".$r["login"]."\", \"".$r["country"]."\")";
mysql_query($query);
}
}
You don't have quotes around $namedb
ie. SELECT * FROM ntable WHERE name =" .$namedb. ""; should be SELECT * FROM ntable WHERE name ='" .$namedb. "'";
I suggest a SELECT INTO would be the better choice... and please post the error so we are able to help...
I am using a page where a variable $submissionid is being posted to it. I would like to use this variable and pull the field subcheck from a MySQL table called submission. I would like the value of the field subcheck to simply be a new variable $subcheck. I'm not sure how to do this. I have a query below, but how to I convert the result of the query below into a variable called $subcheck? (For any given submissionid, there will only be one $subcheck.)
Thanks in advance,
John
$querysub = mysql_query("SELECT subcheck FROM submission WHERE submissionid = '$submissionid' ");
mysql_query($querysub) or die(mysql_error());
You can try:
$querysub = mysql_query("SELECT subcheck FROM submission WHERE submissionid = ".
mysql_real_escape_string($submissionid));
$result = mysql_query($querysub);
if (!$result) {
die 'Could not run query: ' . mysql_error();
}
$subcheck = mysql_result($result, 0);
This is more of a 'php' question, than it is for mysql.
Look up the 'extract' keyword for PHP Link. Effectively 'extract' takes the contents of an associative array and creates php variables (symbol table entries) using the names of keys. Each php variable will then contain the associated value.
You should be able to just:
$result = mysql_query("SELECT * FROM table");
$row = mysql_fetch_array( $result, MYSQL_ASSOC );
extract( $row ); // Create php variables, named after each column in the table.
$row["field"] == $field; // Will be a true statement after 'extract()'
Enjoy, you now have the ability to have your code dynamic adjust to a DB schema that could be changed.
-- J Jorgenson --
This should work:
$querysub = mysql_query("SELECT subcheck FROM submission WHERE submissionid = '" . $submissionid ."' ");
$result = mysql_query($querysub) or die(mysql_error());
$row = mysql_fetch_assoc( $result );
if ($row ) {
$subcheck = $row['subcheck'];
} else {
echo "Subcheck not found";
}
Be careful with the escape characters around $submissionid in your query string. In your sample, they are probably letting the name of the variable go into the string you send to the mysql server.