I need to rename columns in my MySQL table using PHP.
This is made difficult because the syntax is ALTER TABLE [table] CHANGE COLUMN [oldname] [newname] [definition]. The definition is a required parameter.
Is there a way to grab the definition and simply feed this back into the SQL statement? Some sample code would be fantastic, thanks!
According to http://codingforums.com/showthread.php?t=148936, you may have to parse the results of SHOW CREATE TABLE to get the current definition, then use that in the ALTER statement.
mysql_fetch_field() may be useful also.
You can read information_schema.
SHOW TABLE STATUS [{FROM | IN} db_name] [LIKE 'pattern' | WHERE expr]
Issue SHOW CREATE TABLE, read off the line describing the column that is of interest, identify the column definition and construct your ALTER TABLE statement.
My solution was this:
$table = "tableName";
$createTableSQL = $dbh->Execute('SHOW CREATE TABLE ' . $table);
$createTableSQL = $createTableSQL[0][1];
$mappingTable = "originalToDevMapping";
//get mapping
$sql = "SELECT origField, newField
FROM " . $mappingTable;
$newColumns = $dbh->Execute($sql);
foreach ($newColumns as $newColumn) {
if (strlen($newColumn['newField'])<1) {
echo "***Removing*** " . $newColumn['origField'] . "<br><br>";
$sql = "ALTER TABLE " . $table . " DROP COLUMN " . $newColumn['origField'];
$dbh->Execute($sql);
if (strlen($dbh->errorStr)>1) {
echo "<br>************************<br>";
echo "<br>ERROR:<br>";
echo $dbh->errorStr;
echo "<br>************************<br>";
}
} else {
echo "Renaming " . $newColumn['origField'] . " to " . $newColumn['newField'] . "<br><br>";
$sql = "ALTER TABLE " . $table . " CHANGE COLUMN " . $newColumn['origField'] . " " . $newColumn['newField'];
$fieldPos = strpos($createTableSQL,$newColumn['origField']);
$definitionStart = $fieldPos + strlen($newColumn['origField']) + 2;
$definitionEnd = strpos($createTableSQL,',',$definitionStart) - 1;
$definition = substr($createTableSQL,$definitionStart,$definitionEnd-$definitionStart+1);
//workaround - if enum type, comma is included.
if (strstr($definition,'enum')) {
//look for comma after enum end bracket.
$commaPos = strpos($createTableSQL, ',', strpos($createTableSQL,')',$definitionStart));
$definition = substr($createTableSQL,$definitionStart,$commaPos-$definitionStart);
}
$dbh->Execute($sql . " " . $definition);
if (strlen($dbh->errorStr)>1) {
echo "<br>************************<br>";
echo "ERROR:<br>";
echo $dbh->errorStr;
echo "<br>************************<br>";
}
}
}
Related
I am new to PHP and MySQL and hope you can help me with some tipps or comments on this.
I have a MySQL db with a table "Languages" from which I want to fetch all data and then echo it on my page with some HTML tags around it.
In the example below "ISO" is a language code and "$trans" the selected translation of the language names, e.g. English.
The output here is a list of (customized) checkboxes with a checkbox for each language.
So far I have the following which works as intended but since I am new to this I was wondering if I actually need the While loop here or if there is a shorter / better way to get the same - in the end I only need to echo the results of my Select.
My PHP:
// select data from db
$tbl = "Languages";
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM " . $tbl . " ORDER BY ISO ASC";
$result = $conn->query($sql);
// create array
while($arrLanguages = $result->fetch_assoc()){
$languages[] = array("ISO" => $arrLanguages["ISO"], "trans" => $arrLanguages[$lang]);
}
$conn->close();
// echo results with some HTML tags
$i = 1;
foreach($languages as $language){
echo "<input type='checkbox' class='checkSingle' id='language" . $i . "' name='language' value='" . $language['ISO'] . " - " . $language["trans"] . "' />";
echo "<label for='language" . $i . "'>" . $language['ISO'] . "</label>";
$i++;
}
Never do select * if you don't intend to use all of the fields in the table. It's a waste of bandwidth/cpu cycles to request fields that'll simply be thrown away later.
$sql = "SELECT ISO, trans ...";
... execute ...
while($arrLanguages = ...) {
$languages[] = $arrLanguages;
}
Since you only selected the two fields you really wanted, $arrLanguages will contain ONLY those fields, and you don't have type in the full-blown array creation. That was done automatically by the fetch_assoc() call.
I have a MYSQL table containing tournament data for players. Each player has stats like games_won, games_lost, etc. I am trying to display this information in a table.
My PHP code looks like this:
//Connecting to $db
//...
//Store table data into array
$result = mysqli_query($db, "SELECT * FROM ladder");
while($row = mysqli_fetch_array($result)) {
echo $row['id'] . " " . <a href=$row['link']$row['username']</a> . " " . $row['tourney_wins'] . " " . $row['game_wins'] . " " . $row['game_losses'] . " " . $row['last_played'];
echo "<br>";
I get an error (Unexpected "<") on
<a href=$row['link']$row['username']</a>
I am trying to display each username in the table as a hyperlink to their respective profile on another site. Can anyone give me a correction? Thanks!
This is how it should be quoted (assuming I interpreted how you wanted the link properly):
//Connecting to $db
//...
//Store table data into array
$result = mysqli_query($db, "SELECT * FROM ladder");
while($row = mysqli_fetch_array($result))
{
echo( $row['id']." <a href='".$row['link']."'>".$row['username']."</a> ".$row['tourney_wins']." ".$row['game_wins']." ".$row['game_losses']." ".$row['last_played'] );
echo("<br>");
}
Change
<a href=$row['link']$row['username']</a>
to
"<a href=$row['link']$row['username']</a>"
You forgot to quote your html:
echo $row['id'] . " " . <a href=$row['link']$row['username']</a> . " " ...snip...
^--here ^--here
Since it's not quoted, PHP is interpreting it <a as concatenate less than undefined constant 'a', which makes no sense.
I have got one piece of code which gives me a list of all the column names for a specific table. Can i use this list as my $row['VARIABLE'] instead of specifying every row?
The current output of the table names can be seen here this is the second paragraph of text, the first ones are my table names (USERS, ADMIN_LOGIN)
I am working on making a small script which will list all the table contents of a table but it is likely the table will change often so i want a script which can auto generate the table of contents without me having to manually re-enter it all as i have done in the second piece of code below?
Thanks guys
<?php
// Display all sqlite column names for chosen table
$db = new SQLite3('data.db');
$tablesquery = $db->query("PRAGMA table_info(USERS)");
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
echo $table['name'] . '<br />';
}
// Display * from USERS
$db = new SQLite3('data.db');
$results = $db->query('SELECT * FROM USERS');
while ($row = $results->fetchArray()) {
echo "ID = ". $row['ID'] . "\n";
echo "USERNAME = ". $row['USERNAME'] ."\n";
echo "AGE = ". $row['AGE'] ."\n";
echo "LOCATION = ".$row['LOCATION'] ."\n\n";
echo "ANYTHING_ELSE = ". $row['ANYTHING_ELSE'] . "\n";
echo "EMAIL = ". $row['EMAIL'] ."\n";
echo "PROFILE_APPROVED = ". $row['PROFILE_APPROVED'] ."\n";
echo "NUMBER_OF_BATTLES = ".$row['NUMBER_OF_BATTLES'] ."\n\n";
echo "TOTAL_WINS = ".$row['TOTAL_WINS'] ."\n\n";
}
?>
Yes, you can use variables for the index values of an array. For example,
$row = array('col_name' => 'column value');
$index = 'col_name';
echo $row[$index]; // Equivalent to $row['col_name']. Prints "column value"
You should be able to accomplish what you want pretty easily using the above logic. Basically just store the column names from the first query into an array, then loop through that array to get the column names each time you print a row.
Give this a try:
// Display all sqlite column names for chosen table
$db = new SQLite3('data.db');
$tablesquery = $db->query("PRAGMA table_info(USERS)");
$columns = array();
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
$columns[] = $table['name'];
}
// Display * from USERS
$db = new SQLite3('data.db');
$results = $db->query('SELECT * FROM USERS');
while ($row = $results->fetchArray()) {
foreach ($columns as $col)
echo $col . " = " . $row[$col] . "\n";
}
I use the following in order to get a list of columns names in the order they are defined in the table. I use it to populate an insert/select when preserving data.
sel columnname
from dbc.columns
where databasename='databasename'
and tablename='tablename'
order by columnid;
I'm designing a website for a neighbor for a potential restaurant he wants to open. I need to create a page for testimonials/review. I'd like to code it so that the number of stars is in a SQL, I'm just not sure how to do it.
Essentially what I'm looking for is a way to determine the integer of the ratings field (1-5) and for each number, display a star image.
So:
if rating = 1, display star.png once
if rating = 2, display star.png twice
...
if rating = 5, display star.png five times
I'm just not sure how to write the code to do so.
The website is being written in PHP and CSS. I'd like to avoid JQuery, Javascript, .NET, and so forth, as I'm not as familiar with them and will be the one keeping the site up to date.
Here's what I've got so far, but it's not working right, and I get a syntax error:
$result = mysqli_query($con,"SELECT * FROM Reviews");
while($row = mysqli_fetch_array($result))
{
IF (Rating = "1"()){
echo '<img src="star.png">' . }
ELSE IF (Rating = "2"()){
echo '<img src="star.png"><img src="images/star.png">' . }
Else IF (Rating = "3"()){
echo '<img src="star.png">star.png"><img src="images/star.png">' . }
ELSE IF (Rating = "4"()){
echo '<img src="star.png"><img src="images/star.png">star.png"><img src="images/star.png">' . }
ELSE
echo '<img src="star.png"><img src="images/star.png">star.png"><img src="images/star.png"><img src="images/star.png">' .
"<br/> <b>" .
$row['Name'] .
"</b> <em>" .
$row['City'] . $row['State'] . $row['Country'] . "</em><br/>" .
$row['Review'] . "<br/> <hr> <br/>"
}
?>
Use a select statement to get the ratings for a place from your database.
Store the result in a php variable (lets call it $rating)
Use php logic to output number of stars (in html obviously) based on value of $rating.
Hope that helps :)
I would recommend 3 tables for this idea.
Users Table
UserRatings Table
Dish Table
Users table is used to store just that. User information. Possibly a username, password, first name, last name for example. The table should have a primary key. Call it UsersID. It should auto increment itself and be unique for every row.
The Dish table is next. Put a dish name in it. It should have a primary key as well. Call it DishID.
Lastly is the UserRatings table will store UserRatingsId, Rating, InsertTimeStamp, UpdateTimeStamp.
Use a loop to output your HTML based on your rating.
$rating = 4; //Figure this out in your script and set accordingly
for($i = 0; $i < $rating; $i++) {
echo '<img src="star.png" />';
}
Should print out four stars for you.
Help from a friend:
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$starCount = 0;
$result = mysqli_query($con,"SELECT * FROM Reviews");
while($row = mysqli_fetch_array($result)) {
$starCount = $row['Rating'] ;
while ($starCount > 0) {
echo '<img src="images/star.png">';
$starCount -- ;
}
$starCount = 0;
echo "<br/> <b>" . $row['Name'] . "</b> - <em>" .
$row['City'] .", ". $row['State'] ." ". $row['Country'] . "</em><br/>" .
$row['Review'] . "<br/> <hr> <br/>" ;
}
?>
$number=$row->rating ;
$middle="";
$first="<td width='200' align='left'>";
for($x=1;$x<=$number;$x++) {
$middle=$middle.img($fullimage_properties);
}
if (strpos($number,'.')) {
$middle=$middle.img($halfimage_properties);
$x++;
}
while ($x<=5) {
$middle=$middle.img($blankimage_properties); ;
$x++;
}
echo $last=$first.$middle."</td>";
right guys im having trouble with one.
what i want to do is have a variable which is made from a mysql query. the problem i have is that it needs to contain multiple rows from the query and combine them into one.
currently i have
$lender = mysql_query("Select * from lender where reference = '$reference'");
while($lenderrow=mysql_fetch_array($lender)) {
$lender1 = $lenderrow["lender"] . " " . $lenderrow["lenderref"] . " " . "£" . $lenderrow["amount"]
echo '<br />';
}
so basically i want it to take this format if it has multiple rows
blackhorse htfhg125h £250
santander htdhfr58hryf £541
Test 125452asaed2 £760
currently i only get the last result when i echo $lender 1 (obviously because its the last call in the while loop)
Cheers In Advance
You need to use a other array.
<?php
$lender = mysql_query("Select * from lender where reference = '$reference'");
$formated_lender = array();
while ($lenderrow=mysql_fetch_array($lender)) {
$formated_lender = $lenderrow["lender"] . " " . $lenderrow["lenderref"] . " " . "£" .
$lenderrow["amount"];
}
foreach ($formated_lender as $row)
{
echo $row . '<br />';
}
Or, if you would just one variable containing all the row, replace $lende1 = ... by $lender1 .= ...
Just put your echo inside the loop. A loop isn't restricted to one statement.
$lender = mysql_query("Select * from lender where reference = '$reference'");
while($lenderrow = mysql_fetch_array($lender)) {
$result = $lenderrow["lender"] . " " . $lenderrow["lenderref"] . " " . "£" . $lenderrow["amount"];
echo $result . "<br />";
}
If you want it in an array, you can use an empty while loop too:
$lender = mysql_query("Select * from lender where reference = '$reference'");
$results = array();
while($results[] = mysql_fetch_array($lender)); // Empty loop
Also, you might want to be careful about SQL injection if $reference is user-supplied and unescaped.