Jump to content

Turning an array into a column


EricOnAdventure
Go to solution Solved by Muddy_Funster,

Recommended Posts

Hey all, I've been working on this and a few of you have been helping me on it, but I want to post it here so all is clear. First the code.

<?php
session_start();
include("config.php");



function showColor($number)
{
    if ($number == 1) {
        $color = "red";
        $word  = "Low";
    }
    if ($number == 2) {
        $color = "green";
        $word  = "Medium";
    }
    if ($number == 3) {
        $color = "blue";
        $word  = "High";
    }
    if ($number == 4) {
        $color = "orange";
        $word  = "Very High";
    }
    if ($number == 5) {
        $color = "violet";
        $word  = "Extremely High!";
    }
    return "<td style='color:$color';>$word</td>";
}


$sql = "SELECT * FROM " . $SETTINGS["data_table"] . " WHERE id>0 LIMIT 10";

$sql_result = mysql_query($sql, $connection) or die('request "Could not execute SQL query" ' . $sql);

$Scholarships = array();

if (mysql_num_rows($sql_result) > 0) {
    while ($row = mysql_fetch_assoc($sql_result)) {
        
        $Scholarships[] = $row["Scholerships"];

    }
    
} else {
    
    $Scholarships[] = "fail";
    
}

?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Show color</title>
</head>

<body>
<div>
<table style="width:191px;">
  <tr>
<?php
print_r ($Scholarships); 
foreach ($Scholarships as $thecolor) {
    echo showColor($thecolor);}


	
    


?>

  </tr>
</table>
</div>

</body>

</html>

Print R gives me this

 

 

Array ( [0] => 3 ) Array ( [0] => 3 [1] => 3 ) Array ( [0] => 3 [1] => 3 [2] => 3 ) Array ( [0] => 3 [1] => 3 [2] => 3 [3] => 3 ) Array ( [0] => 3 [1] => 3 [2] => 3 [3] => 3 [4] => 3 ) Array ( [0] => 3 [1] => 3 [2] => 3 [3] => 3 [4] => 3 [5] => 3 ) Array ( [0] => 3 [1] => 3 [2] => 3 [3] => 3 [4] => 3 [5] => 3 [6] => 3 ) Array ( [0] => 3 [1] => 3 [2] => 3 [3] => 3 [4] => 3 [5] => 3 [6] => 3 [7] => 3 ) Array ( [0] => 3 [1] => 3 [2] => 3 [3] => 3 [4] => 3 [5] => 3 [6] => 3 [7] => 3 [8] => 3 ) Array ( [0] => 3 [1] => 3 [2] => 3 [3] => 3 [4] => 3 [5] => 3 [6] => 3 [7] => 3 [8] => 3 [9] => 3 )

 

and foreach gives me this.

High High High High High High High High High High

 

The issue is I need the table created by the foreach to create me 1 row and 10 columns. I am not sure how to get that.

Any Advice?

 

Link to comment
Share on other sites

What does your table structure look like?

What kind of data is inside the Scholarships column?

What is inside $SETTINGS["data_table"]?

 

 

Provide us either a screenshot of your structure and some data, or perform a DESCRIBE tableName query and give us the output.

 

Your print_r is not inside a loop so I don't see how it's giving you that output

Link to comment
Share on other sites

HINT: if you are using print_r, put it between <pre>..</pre> tags. It makes it so much easier to understand the array structure.

print_r($array);

    /* OUTPUT :
    Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [1] => Array ( [0] => 2 [1] => 2 [2] => Array ( [0] => 45 [1] => 22 [2] => 34 ) ) [2] => Array ( [0] => 4 [1] => 5 [2] => 6 [3] => 7 ) )
    */
    
echo '<pre>' . print_r($array, true) . '</pre>';

    /* OUTPUT :
    Array
    (
        [0] => Array
            (
                [0] => 1
                [1] => 2
                [2] => 3
            )

        [1] => Array
            (
                [0] => 2
                [1] => 2
                [2] => Array
                    (
                        [0] => 45
                        [1] => 22
                        [2] => 34
                    )

            )

        [2] => Array
            (
                [0] => 4
                [1] => 5
                [2] => 6
                [3] => 7
            )

    )    
    */

Link to comment
Share on other sites

I've done a re-write on your code from the OP.  Most significant change is swapping out the multiple if statements for a switch/case.  This doesn't really change what the code was doing, both ways are equally acceptable, I just felt that this was a good example of when you could choose to use a switch over a bunch of ifs.  Switch statements have the benefit of breaking out when the condition is met, so over larger checks it can save a bunch of processing by not parsing every value against every condition every time.  Another change is that I have added the table rendering code within the initial while loop.  Loops are right up there with the most performance draining aspects of any code and keeping them to a minimum is always a good idea.

 

I don't honestly know if this will fix your issue, not do I expect this to just run.  Read through the code and make sure you can understand it all then see what it does when you apply it to your setup.

 

 

<?php
session_start();
include("config.php");
 
function showColor($n){ 
switch ($n){
case 1: 
$code = array("color" => "red", "word" => "Low");
break;
 
case 2:
$code = array("color" => "green", "word" => "Medium");
         break;
         
        case 3:
         $code = array("color" => "blue", "word" => "High");
         break;
        
        case 4:
         $code = array("color" => "orange", "word" => "Very High");
         break;
         
        case 5:
$code = array("color" => "violet", "word" => "Extremely High!");
         break;
        
        default:
         $code = array("color" => "black", "word" => "Standard");
}
 
    return $code;
}
 
$sql = "SELECT Scholarships AS colorCode FROM " . $SETTINGS["data_table"] . " WHERE id>0 LIMIT 10";
 
$sql_result = mysql_query($sql, $connection) or die('request "Could not execute SQL query" ' . $sql);
 
$cTable = "";
 
if (mysql_num_rows($sql_result) > 0) {
    while ($row = mysql_fetch_assoc($sql_result)) {
        $thisColor = showColor($row["colorCode"]);
$cTable .= "<tr><td style='color:{$thisColor['color']}>{$thisColor['word']}</td></tr>";
    }
} 
else {
    $cTable .= "<tr><td>No Results</td></tr>";    
}
$htmlHead = <<<HTML_HEADING
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Show color</title>
</head>
 
<body>
HTML_HEADING;
 
$htmlBody = <<<HTML_BODY
<div>
<table style="width:191px;">
 <tr><th>ColorKey</th></tr>
HTML_BODY;
 
$htmlBody .= $cTable;
$htmlBody .= "</table></div></body></html>";
 
echo $htmlHead;
echo $htmlBody;
 
?>
Link to comment
Share on other sites

Wow, amazing! I tested it and of course it works, of course, but when I tried to apply it to my complete search script, I just couldn't get it to work, no matter what I tried. I learned a lot from this, and I greatly appropriate it, thank you so much for taking your time to redo the script, your work is nothing less then magic! Could you give me any advice on how I could apply this correctly to my university search script. I tried so many options, but none worked correctly. I have attached a pic of what it looks like now in my search script, and the whole script is below.

 

Capture.PNG

<?php
session_start();
include("config.php");



if(isset($_GET["programtype"])){
	$programtype=$_GET["programtype"];
	$_SESSION['programtype']=$programtype;
	}
else {
	$programtype=$_SESSION['programtype'];
	}
	if (!isset($programtype)){
				header("location: index.php");
				exit;				
		}
		
if(!isset($_GET["Country"])){	
$_GET["Country"]='United States of America';
	}

	
//////////////color
 
function showColor($n){ 
switch ($n){
case 1: 
$code = array("color" => "red", "word" => "Low");
break;
 
case 2:
$code = array("color" => "green", "word" => "Medium");
         break;
         
        case 3:
         $code = array("color" => "blue", "word" => "High");
         break;
        
        case 4:
         $code = array("color" => "orange", "word" => "Very High");
         break;
         
        case 5:
		$code = array("color" => "violet", "word" => "Extremely High!");
         break;
        
        default:
         $code = array("color" => "black", "word" => "Standard");
}
 
    return $code;
}
 
$sql = "SELECT Scholarships AS colorCode FROM " . $SETTINGS["data_table"] . " WHERE id>0 LIMIT 10";
 
$sql_result = mysql_query($sql, $connection) or die('request "Could not execute SQL query" ' . $sql);
 
$cTable = "";
 
if (mysql_num_rows($sql_result) > 0) {
    while ($row = mysql_fetch_assoc($sql_result)) {
        $thisColor = showColor($row["colorCode"]);
$cTable .= "<tr><td style=color:{$thisColor['color']}>{$thisColor['word']}</td></tr>";
    }
} 
else {
    $cTable .= "<tr><td>No Results</td></tr>";    
}
 $htmlBody =$cTable;

 
?>




<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>University Search</title>
<style>
BODY, TD {
	font-family:Arial, Helvetica, sans-serif;
	font-size:12px;
}
</style>
</head>


<body>

<form id="form1" name="form1" method="get" action="search.php">
<label>Country</label>
<select name="Country">
<option value="<?php echo $_GET["Country"];?>"><?php echo $_GET["Country"];?></option>
<option value='United Kingdom'>United Kingdom</option><br />
<option value='United States of America'>United States of America</option>
<option value='Argentina'>Argentina</option><br />
<option value='Australia'>Australia</option><br />
<option value='Austria'>Austria</option><br />
<option value='Bangladesh'>Bangladesh</option><br />
<option value='Belarus'>Belarus</option><br />
<option value='Belgium'>Belgium</option><br />
<option value='Brazil'>Brazil</option><br />
<option value='Canada'>Canada</option><br />
<option value='Chile'>Chile</option><br />
<option value='China'>China</option><br />
<option value='Colombia'>Colombia</option><br />
<option value='Cyprus'>Cyprus</option><br />
<option value='Czech Republic'>Czech Republic</option><br />
<option value='Denmark'>Denmark</option><br />
<option value='Egypt'>Egypt</option><br />
<option value='Estonia'>Estonia</option><br />
<option value='Finland'>Finland</option><br />
<option value='France'>France</option><br />
<option value='Germany'>Germany</option><br />
<option value='Ghana'>Ghana</option><br />
<option value='Greece'>Greece</option><br />
<option value='Hong Kong'>Hong Kong</option><br />
<option value='Hungary'>Hungary</option><br />
<option value='Iceland'>Iceland</option><br />
<option value='India'>India</option><br />
<option value='Indonesia'>Indonesia</option><br />
<option value='Iran'>Iran</option><br />
<option value='Israel'>Israel</option><br />
<option value='Italy'>Italy</option><br />
<option value='Japan'>Japan</option><br />
<option value='Jordan'>Jordan</option><br />
<option value='Kenya'>Kenya</option><br />
<option value='Latvia'>Latvia</option><br />
<option value='Lebanon'>Lebanon</option><br />
<option value='Lithuania'>Lithuania</option><br />
<option value='Luxembourg'>Luxembourg</option><br />
<option value='Macau'>Macau</option><br />
<option value='Malaysia'>Malaysia</option><br />
<option value='Mexico'>Mexico</option><br />
<option value='Morocco'>Morocco</option><br />
<option value='Netherlands'>Netherlands</option><br />
<option value='New Zealand'>New Zealand</option><br />
<option value='Nigeria'>Nigeria</option><br />
<option value='Norway'>Norway</option><br />
<option value='Oman'>Oman</option><br />
<option value='Pakistan'>Pakistan</option><br />
<option value='Poland'>Poland</option><br />
<option value='Portugal'>Portugal</option><br />
<option value='Qatar'>Qatar</option><br />
<option value='Republic of Ireland'>Republic of Ireland</option><br />
<option value='Romania'>Romania</option><br />
<option value='Russian Federation'>Russian Federation</option><br />
<option value='Saudi Arabia'>Saudi Arabia</option><br />
<option value='Serbia'>Serbia</option><br />
<option value='Singapore'>Singapore</option><br />
<option value='Slovakia'>Slovakia</option><br />
<option value='Slovenia'>Slovenia</option><br />
<option value='South Africa'>South Africa</option><br />
<option value='South Korea'>South Korea</option><br />
<option value='Spain'>Spain</option><br />
<option value='Sweden'>Sweden</option><br />
<option value='Switzerland'>Switzerland</option><br />
<option value='Taiwan'>Taiwan</option><br />
<option value='Thailand'>Thailand</option><br />
<option value='Turkey'>Turkey</option><br />
<option value='Uganda'>Uganda</option><br />
<option value='Ukraine'>Ukraine</option><br />
<option value='United Arab Emirates'>United Arab Emirates</option><br />
</select>


<label>How do you want to sort the universities?</label>
<select name="sorthow" id="sorthow"  >
<option selected="" value="">---Select---</option>
<option value="<?php echo $programtype ?>"><?php echo $programtype ?> Ranking</option>
<option value='rank'>Overall Ranking</option>
<option value="`Immigration rate`">Immigration rate</option>
<option value="`Income greater then average`">Income</option>
<option value="Scholarships">Scholarships</option>
<option value="TA">Teaching Asstantships</option>
<option value="RA">Research Asstantships</option>
<option value="satisfaction">Student Satisfaction</option>
</select>

<label>What level of ramnking are you looking for?</label>
<select name="number" id="number"  >
<option selected="" value="">---Select---</option>
<option value='0'>The Best of the best</option>
<option value="25">Top 25+</option>
<option value="50">Top 50+</option>
<option value="75">Top 75+</option>
<option value="100">Top 100+</option>
</select>


<input type="submit" name="button" id="button" value="Search" />

</form>
<br /><br />
<table width="700" border="1" cellspacing="0" cellpadding="4">
  <tr>
    <td width="191" bgcolor="#CCCCCC"><strong><button onclick="odds()">Odds of Getting Accepted</button></strong></td>
	<td width="191" bgcolor="#CCCCCC"><strong>University</strong></td>
    <td width="113" bgcolor="#CCCCCC"><strong>Country</strong></td>
    <td width="159" bgcolor="#CCCCCC"><strong><button onclick="programrank()"><?php echo $programtype ?> Ranking</button></strong></td>
    <td width="191" bgcolor="#CCCCCC"><strong><button onclick="rank()">Overall Rank</button></strong></td>
	<td width="191" bgcolor="#CCCCCC"><strong><button onclick="immigrant()">Immigration rate</button></strong></td>
	<td width="191" bgcolor="#CCCCCC"><strong><button onclick="Income()">Income</button></strong></td>
	<td width="191" bgcolor="#CCCCCC"><strong><button onclick="Scholarships()">Scholarships<br></button></strong></td>
<!--	<td width="191" bgcolor="#CCCCCC"><strong><button onclick="Teaching()">Teaching Asstantships</button></strong></td>
	<td width="191" bgcolor="#CCCCCC"><strong><button onclick="Research()">Research Asstantships</button></strong></td>
	<td width="191" bgcolor="#CCCCCC"><strong><button onclick="Satisfaction()">Student Satisfaction</button></strong></td>
--> 
 </tr>
  






  
  
  
  
<?php
$number='';
If ((($_GET["sorthow"]) == 'rank') || (($_GET["sorthow"]) == $programtype)){
$upordown="ASC";
	if(isset($_GET['number'])){$number = " AND ". mysql_real_escape_string($_GET['sorthow']). " >=". mysql_real_escape_string($_GET['number'])." ";}
}
else {$upordown="DESC";}
	$search_Country = " Country='". mysql_real_escape_string($_GET['Country']). "'";	
	$search = " ORDER BY '". mysql_real_escape_string($_GET['sorthow']). "' ".$upordown;	


$sorthow=mysql_real_escape_string($_GET["sorthow"]);

//////////////feedback

if ($_GET["sorthow"]<>'') {
	$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE ".$search_Country. $number. $search. " LIMIT 10";
} else {
	$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE ".$search_Country." LIMIT 300";
}
echo "SELECT * FROM unidata WHERE rank >= 75 AND Country='Australia' ORDER BY 'rank' ASC<br>";
echo $sql;
///////////////////
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
if (mysql_num_rows($sql_result)>0) {
	while ($row = mysql_fetch_assoc($sql_result)) {

?>
  <tr>
    <td>'Members Only'<br> <a href="signup.php">Sign Up now<i class="icon-long-arrow-right"></i></a></td>
	<td><?php echo $row["University"]; if(isset($row["City"])){echo $row["City"]; }?></td>
    <td><?php echo $row["Country"];?></td>
    <td><?php echo $row[$programtype]; ?></td>
    <td><?php echo $row["Rank"]; ?></td>
    <td><?php echo $row["Immigration rate"]; ?></td>
	<td><?php echo $row["Income greater then average"]; ?></td>
<?php   echo $htmlBody; ?>

	
	

  </tr>
  
  <?php

}}
?>
 
</table>



<script>
function odds() {
    alert("Your odds of being accepted into a university depend on a lot of factors, including:	\n Grades\n Test scores\n The quality of your References\nThe quality and information in your Personal Statement\n Your Work and Volunteer Experience\n\nWe use a complex algorithm to match your all of these to the requirements of each school. If you want to know our algorithm, here it is:\n Odds=[ð‘¤ð»24(S24+0.4ð»14ð´+0.4ð»24ð‘ƒ)+ð‘¤ð»47(ð»38+0.4L48ð´+0.4ð»48ð‘ƒ)\n+ð‘¤ð»72(ð»72+0.4ð»72ð´+0.4ð»72ð‘ƒ)+ð‘¤ð·(ð·+0.4ð·ð´+0.4ð·ð‘ƒ)\n+ð‘¤ð‘€ð‘€0.3+ð‘¤ð¿ð¿0.05+ð‘¤ð‘…ð‘…20,000+ð‘¤ð‘‡ð‘‡+ð‘¤ð‘„ð‘„0.02+ð‘¤ðºðº0.04]×ð‘†");
}
function programrank() {
    alert("The <?php echo $programtype; ?>ranking sorts the best <?php echo $programtype; ?> university programs. This ranking IS MUCH more important than the Overall Ranking");
}
function rank() {
    alert("The Overall Ranking looks at the total ranking of all programs a university has and sums them up. While this ranking can be helpful for sorting universities, it should not be the main focus of which university you choose as it unfairly gives advantages to larger universities with more programs also ignores many specialty programs");
	}
function immigrant() {
    alert("Our Immigration Rate Score is based on the past success of applications who graduating from this school applying for and being accepted as Immigrants to this the county. While the quality of the university does make a difference, do keep in mind that some countries have much higher immigration rates than others.");
	}
function Income() {
    alert("We based this score on the average income of schools graduates and the standard income of the countries the school is in. The rating ranges from making the same as the average for that country to making much higher income then the average in the country");
	}
function Scholarships() {
    alert("This list shows is based on the amount of scholarships in total available for the student population. The more scholarships available, the greater your chance of getting one or many.");
	}
function Teaching() {
    alert("This list shows is based on the amount of Teaching Assistantships for Graduate (masters and PhD) students available for the student population. The more Teaching Assistantships available, the greater chance of you getting one.");
	}
function Research() {
    alert("This list shows is based on the amount of Research Assistantships for Graduate (masters and PhD) students available for the student population. The more Research Assistantships available, the greater chance of you getting one.");
	}
function Satisfaction() {
    alert("This Score measures the overall Self-reported satisfaction from students at that school.");
	}

	
</script>






</body>
</html>
<?php

    

?>
Link to comment
Share on other sites

  • Solution

Fist of all, compared to most of the regulars on this forum I am a rank amateur, so your praise is somewhat excessive.

Now to the issue at hand: You just need to expand the query (and the string assignment) - I altered it to only select the scholarships column from the table as that was the only column you were working with in the previous code, change the query to this:

 

**Change field names as appropriate - I'm guessing as to what TA, RA satisfaction and Rank actually apply to in your HTML table.**

$ sql = <<<SQL_QRY
SELECT
  Scholarships AS colorCode,
  University,
  Country,
  satisfaction AS HLStudiesRank,
  Rank as overallRank,
  TA AS immigration,
  RA AS income,
FROM
  {$SETTINGS["data_table"] }
WHERE
  id>0
LIMIT 10
SQL_QRY;

and then update the string append in the the while loop to include the other column values:

$cTable .= "<tr>";
$cTable .= "<td style=color:{$thisColor['color']}>{$thisColor['word']}</td>";
$cTable .= "<td>{$row['University']}</td>";
$cTable .= "<td>{$row['Country']}</td>";
$cTable .= "<td>{$row['HLStudiesRank']}</td>";
$cTable .= "<td>{$row['overallRank']}</td>";
$cTable .= "<td>{$row['immigration']}</td>";
$cTable .= "<td>{$row['income']}</td>";
$cTable .= "</tr>";

Again, most of this is assumed and will need to be customised for your data.

Edited by Muddy_Funster
Link to comment
Share on other sites

Why are you people helping get obsolete insecure code working? You should be helping him convert this to PDO.

 

One step at a time.  Forcing the OP to change paradigm before offering help will only result in them seeking help elsewhere. Looking up out dated guides that support the obsolete code and getting into a worse position than they are in just now.  However, building trust at this point by helping with the problems that are surrounding the obsolete code means that they both get to a position where they are confident to implement the change to PDO (or mysqli; as they have said they will be choosing that route once they are ready) sooner, and also that they will be prepared to come back here for help should they struggle with that change.

Link to comment
Share on other sites

Yea! took me a couple hours but it's looking real good now! I'll try to convert it to my SQLi tomorrow (just programed from 8am to midnight, time to sleep). I have an idea about how to approach this, but if I run into a wall, I'll be back. :)
Thanks again Muddy, and everyone. I couldn't have done this without you.

Link to comment
Share on other sites

Experience shows that once they get their old code working they never convert it later. Not always, but mostly. The only thing that is truly going to solve this is when every server has PHP 7.

 

You need more faith @benanamen :) Confucius say: Just because most people don't follow the right path doesn't mean you should shut the gate on everyone that might. (he didn't really, I just made that up - before someone starts an intellectual property suit against me)

Link to comment
Share on other sites

Benanamen say: Stop teaching people how to use code that has been deprecated starting over TEN years ago. There is just no excuse to keep that kind of code alive. Better to teach the OP's PDO or at the least Mysqli. There is no reward waiting for you in programmers heaven for fixing obsolete code. Word on the street is you may even get sent somewhere else for doing it.

  • Like 1
Link to comment
Share on other sites

Benanamen say: Stop teaching people how to use code that has been deprecated starting over TEN years ago. There is just no excuse to keep that kind of code alive. Better to teach the OP's PDO or at the least Mysqli. There is no reward waiting for you in programmers heaven for fixing obsolete code. Word on the street is you may even get sent somewhere else for doing it.

 

Yeah, that's not really got the same ring to it though...   :tease-03:

Link to comment
Share on other sites

Benanamen, if you're just here to troll and not offer any help, then.... you know, move along.  You can preach best practices until you're blue in the face, but it's not "help."  Just as you pointed out yourself

 

Experience shows that once they get their old code working they never convert it later.

 

So what? We're not here to spoon-feed and shove best practices down our community members' throats.  The basis of PHPFreaks is to allow someone with barely any knowledge of PHP (or web dev related things) to gain a firm grasp of it.  If the user decides to continue using legacy code, then so be it.  It's not like we're going to be held accountable, and even if someone attempted to do that, this is a volunteer based forum.  Let them use their old code.  In the long run, it means the user will return asking why XYZ isn't doing ABC, and someone will point out that the culprit is a line of legacy code, a legacy function.  Ultimately, the main goal is to have the users be able to learn how to expand on their questions and provide just the right amount of information for someone to help them effectively.  In due time, assuming the user pursues learning PHP, they will eventually see the error in their legacy methods and realize that the only fix is to be up-to-date.

 

PHP7 is very young at this point, compared to PHP 5.6, which most people have been using for a long while.  Although it would be an awesome feeling to know that you helped someone create an innovative idea using the most up-to-date methods, it's not something to expect of our members.

Just my 2 cents. ;).

Link to comment
Share on other sites

Troll? Hardly! No one in this thread even mentioned a single thing about the OP's obsolete code. So I am a troll because I pointed out something VERY important, not only for the OP, but for the web?

 

How are you helping when you don't even tell the OP that his code is obsolete and point him the way of PDO or at least Mysqli? Help with bad code all you want but at least tell the OP so he knows.

 

 

 

 

In due time, assuming the user pursues learning PHP, they will eventually see the error in their legacy methods

 

In due time? For real? The OP is here right now. Teach him the right way while he is here, not some mystical time in the future.

 

 

OP: Check out this link on how to use PDO: https://phpdelusions.net/pdo

  • Like 1
Link to comment
Share on other sites

I think the “troll” accusation is a bit unfair. Maybe benanamen is taking a minority position here, but that doesn't make it wrong.

 

In my own experience, it actually can be more productive to move users towards modern PHP rather than trying to repair their legacy code over and over again. I've introduced quite a lot of PHP beginners to PDO, and while they weren't all happy with it at first, they did eventually recognize the benefits. So a five-minute argument can save hours, days, sometimes years of turd polishing, which is in absolutely everybody's interest.

 

This also goes far beyond the problem of legacy applications. PHP code relying ext/mysql is notorious for SQL injection vulnerabilities, awful error handling or no error handling at all as well as idiotic habits from 90s tutorials. It's not just old, it's truly harmful.

 

I don't think that's “shoving best practices down people's throats”. None of us is afraid to reject the ideas of a user when they're clearly bad, so we shouldn't be afraid to reject bad code either.

Link to comment
Share on other sites

Yeah, I suppose the word "troll" wasn't the best word to use (a bit harsh), I'll apologize for that.

 

I do agree though that teaching best practices is a great thing to be doing, and leading people away from sub-par tutorials.  But, my point was that benanamen only ever mentioned obsolete code, never provided any relevant links,  nor provided any example code or anything other than just saying, It's obsolete, it ain't 1337.  Doing that is no different than the OP providing very vague information like "It doesn't work."  Lead by example, make an effort to explain that:

$connection = mysql_connect("localhost", "username", "password");
mysql_select_db('myDatabase');

can be upgraded and consolidated to just

$connection = mysqli_connect("localhost", "username", "password", "myDatabase")';

Things like, what a prepared statement looks like, why is it better, yada yada.  There is always the short and simple solution to RTFM, but I'd say that message is mainly warranted to users that repeatedly don't read the manual and continue to say "it doesn't work, why?"  And perhaps this could be one of those cases.  Anyway, this is way off topic and I probably shouldn't have drank all of those beers before posting that reply  :intoxicated:

 

I know that I, myself, didn't provide any help in this topic, but I did make sure to ask questions that we would need to know.  Regardless, I'm just rambling now.  :keep_quiet:

Link to comment
Share on other sites

In my "defense" my response was directed to the "Experts" that posted on this thread and not to the OP. An expert doesn't need an explanation of obsolete code. Anyone with enough expertise to respond with help to the OP "should" know enough to spot the obsolete code and at least point it out even if you are going to help fix it. To my surprise, nobody did. Had I responded to the OP, I would have directed OP to the PDO tutorial that I just did. In the words of Forrest Gump, "That's all I have to say about that".

Link to comment
Share on other sites

@benanamen - Just for clarification, comments and suggestions on the use of PDO / mysqli_ over mysql_ were made in abundance in the OP's previous thread (that's how I knew the OP would prefer mysqli_).  It's fare to assume going forward that, in the first instance, warnings and recommendations will always be included as part of replies to people seeking assistance with mysql_ and other obsolete code.

 

@Zane - I appreciate what your saying here, but another way to look at it could be: when the OP sees that the "Regulars" (I'm far to self deprecating to include myself under the "Expererts" column) are have a conversation to the nature of the one in this thread - as long as it's kept civil and relevant - it can often encourage them to look into the facts being discussed. So it's kind of like telling them off by proxy.  When people see that a bunch of respected coders are having an impassioned debate over aspects of the code they have chosen to use, and it's application in the real world, it can be enough to inspire those that wouldn't otherwise fully investigate the options to go and do so.  So if you look at it like that: technically (and kinda indirectly) @benanamen was helping  :happy-04:

 

 

P.S. - probably wouldn't be the worst idea to lock this thread? I'm failing the fight to not post in it and we have drifted off-topic in a more than subtle way ;D  .

Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.