Processing the Search String with PHP and MySQL - php

I'm in the process of making a web page that's meant to display data that's within a database. The database is stored in MySQL and I'm making the web page in PHP. The PHP code that I have is
<?php
$query = "select * from project where ".$searchtype." like '%".$searchterm."%'";
$result = mysqli_query($db,$query);
$num_results = mysqli_num_rows($results);
echo "<p>Number of projects found: ".$num_results."</p>";
for ($i=0; $i <$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
echo "<p><strong>".($i+1).". Title: ";
echo htmlspecialchars(stripslashes($row['title']));
echo "</strong><br />Author: ";
echo stripslashes($row['author']);
echo "<br />ISBN: ";
echo stripslashes($row['isbn']);
echo "<br />Price: ";
echo stripslashes($row['price']);
echo "</p>";
}
$mysqli_free_result($result);
$mysqli_close($db);
?>
This PHP script is meant to load different projects that's within the database and in a welcome.php script that calls this script connects to the database and it does connect to it correctly. The problem that I'm having is when I run this script, is that I get the following:
Number of projects found:
As shown, it doesn't display any data from the database.
EDIT
My welcome.php script is
<?php
$hostname='mysql.uniwebsite.ac.uk';
$database='uniusername';
$username='database';
$password='password';
$db= mysql_connect($hostname, $username, $password);
if (!$link) {
die('Connection failed: ' . mysql_error());
}
else{
echo "Connection to MySQL server " .$hostname . " successful!
" . PHP_EOL;
}
$db_selected = mysql_select_db($database, $link);
if (!$db_selected) {
die ('Can\'t select database: ' . mysql_error());
}
else {
echo 'Database ' . $database . ' successfully selected!';
}
?>
EDIT #2
My projects.php code is
<?php
$searchtype=$_POST['searchtype'];
$searchterm=trim($_POST['searchterm']);
if (!$searchtype || !$searchterm) {
echo 'No search details. Go back and try again.';
exit;
}
$query = "select * from project where ".$searchtype." like '%".$searchterm."%'";
var_dump($query);
$result = mysqli_query($link,$query);
$num_results = mysqli_num_rows($result);
echo "<p>Number of projects found: ".$num_results."</p>";
for ($i=0; $i <$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
echo "<p><strong>".($i+1).". Project Number: ";
echo htmlspecialchars(stripslashes($row['projectNo']));
echo "</strong><br />Project Name: ";
echo stripslashes($row['pjname']);
echo "<br />Project City: ";
echo stripslashes($row['city']);
echo "</p>";
}
mysqli_free_result($result);
mysqli_close($link);
?>
And when I run it, I get No search details. Go back and try again.
EDIT #3
In my projects.php I have now got
<form action="list_projects.php" method="post">
<p>Choose Search Type: <br /></p>
<select name="searchtype">
<option value="partNo">Part Number</option>
<option value="pname">Part Name</option>
<option value="color">Part Colour</option>
<option value="weight">Part Weight</option>
<option value="city">City</option>
</select>
<br />
<p>Enter Search Term: </p>
<br />
<input name="searchterm" type="text" size="20"/>
<br />
<input type="submit" name="submit" value="Search"/>
</form>
<?php
$searchtype=$_POST['searchtype'];
$searchterm=trim($_POST['searchterm']);
if (!$searchtype || !$searchterm) {
echo 'No search details. Go back and try again.';
exit;
}
$query = "select * from project where ".$searchtype." like '%".$searchterm."%'";
var_dump($query);
$result = mysqli_query($link,$query);
$num_results = mysqli_num_rows($result);
echo "<p>Number of projects found: ".$num_results."</p>";
for ($i=0; $i <$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
echo "<p><strong>".($i+1).". Part Number: ";
echo htmlspecialchars(stripslashes($row['partNo']));
echo "</strong><br />Part Name: ";
echo stripslashes($row['pname']);
echo "<br />Part Colour: ";
echo stripslashes($row['color']);
echo "<br />Part Weight: ";
echo stripslashes($row['weight']);
echo "<br />City";
echo stripcslashes($row['city']);
echo "</p>";
}
mysqli_free_result($result);
mysqli_close($link);
?>
but when I run it, I get string(49) "select * from project where projectNo like '%J1%'"
Number of projects found:

EDIT
Here are the both files corrected. There were few more typos with function names like $mysqli_free_result($result) and $mysqli_close($db).
File welcome.php:
<?php
$hostname='mysql.uniwebsite.ac.uk';
$database='uniusername';
$username='database';
$password='password';
$link = mysql_connect($hostname, $username, $password);
if (!$link) {
die('Connection failed: ' . mysql_error());
}
else{
echo "Connection to MySQL server " .$hostname . " successful!
" . PHP_EOL;
}
$db_selected = mysql_select_db($database, $link);
if (!$db_selected) {
die ('Can\'t select database: ' . mysql_error());
}
else {
echo 'Database ' . $database . ' successfully selected!';
}
?>
<?php
$query = "select * from project where ".$searchtype." like '%".$searchterm."%'";
// var_dump($query); -- uncomment to make sure the final query makes sense after filling those variables
$result = mysqli_query($link,$query);
$num_results = mysqli_num_rows($result);
echo "<p>Number of projects found: ".$num_results."</p>";
for ($i=0; $i <$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
echo "<p><strong>".($i+1).". Title: ";
echo htmlspecialchars(stripslashes($row['title']));
echo "</strong><br />Author: ";
echo stripslashes($row['author']);
echo "<br />ISBN: ";
echo stripslashes($row['isbn']);
echo "<br />Price: ";
echo stripslashes($row['price']);
echo "</p>";
}
mysqli_free_result($result);
mysqli_close($link);
?>

UPDATE
Remove mysql_close($link);
And then, instead of using $db in the rest of your code, use $link.
$result = mysqli_query($link, $query);

Related

Session variable and Dynamic Pagination in php

<form action='movies.php' method='POST'>
Language: <select name="language">
<option selected>hindi</option>
<?php
require("config.php");
$result="SELECT language FROM movies";
$q = mysqli_query($conn,$result) or die(mysql_error());
while ($row=mysqli_fetch_array($q)) {
$s1=$row["language"];
echo "<option>
$s1
</option>";
}
echo "<br>"
?>
</select>
<br /> <br />
<input type='submit' value='Submit' />
</form>
<?php
$lang=#$_POST['language'];
$_SESSION["lang1"]=$lang;
/*
if($lang){
$sql = "SELECT name,language FROM movies WHERE language='$lang'";
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows($result)>0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<div class="query"> <img src="images\tiles\bb.jpg"> ';
echo "<h3> " . $row["name"]."</h3>". "<br>";
echo "</div>";
}
} else {
echo "0 results";
}
}
*/
$page=#$_GET['page'];
if($page==""|| $page=="1")
{
$page1=0;
}
else{
$page1=($page*3)-3;
}
$sql = "SELECT name,language FROM movies WHERE language='". $_SESSION['lang1']."' limit $page1,3 ";
$result = mysqli_query($conn,$sql);
$a= mysqli_num_rows($result);
while ($list=mysqli_fetch_array($result))
{
echo $list['name'] . " : " . $list['language'] . "<br />";
}
$sql = "SELECT name,language FROM movies WHERE language='$lang'";
$result = mysqli_query($conn,$sql);
$a= mysqli_num_rows($result);
$numrows=$a;
$rowsperpage=3;
$totalpages= ceil($numrows/$rowsperpage);
echo "</br>";
for($b=1;$b<=$totalpages;$b++)
{
?><?php echo $b." ";?> <?php
}
?>
I get proper output on movies.php which is the first 3 rows from database,but when i click on the dynamically created pagination link like movies.php?page=2 then there is no output on this page.This code works fine if i manually set the
$_SESSION["lang1"]="English"; then i get proper output but when i take input from the form it doesnt work.

UPDATE single column in database: PHP&MYSQL

So, I am trying to figure out how do this this and it boggling me. THIS WILL NOT BE USED ONLINE LIVE SO SQL INJECTION I DONT' CARE ABOUT. What am I doing wrong/right?
<?php
$db = mysql_connect("localhost", "root", "root");
if (!$db) {
die("Database connect failed: " . mysql_error());
}
$db_select = mysql_select_db("UNii", $db);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$comment = $_GET['comment'];
$id = $_GET['id'];
$sql = "UPDATE Dbsaved SET comment = '{$comment}' WHERE id = $id";
$comment1 = mysql_query($sql);
if (!$comment1) {
die("did not save comment: " . mysql_error());
}
echo $sql;
The main problem is with the statement itself, the connection is fine. I am trying to read $comment, and then update that into a MYSQL table and then have it read back in a different file.
EDIT: Mark up for the form I'm taking $comment from.
<!DOCTYPE html>
<html lang="en">
<LINK href="stylesheet.css" rel="stylesheet" type="text/css">
<script src ="js/validateform.js"></script>
<head>
<meta charset="UTF-8">
<title>UniHelp Home</title>
</head>
<body>
<div id="headeruni">
<h1>Welcome <?php echo $_GET["name"]; ?> to UniHelp!</h1>
</div>
<div id ="infouni">
<h3>Welcome to UniHelp. The social Network getting you connected to other people all over the University for any help you require!</h3>
</div>
<div id ="nameandemail">
<form action="formsend.php" method="post">
First name: <br> <input type="text" name="name"><br>
Email: <br> <input type="text" name="email"><br>
Comment: <br> <input type="text" name="message"><br>
<input type="submit" name="submit">
</form>`enter code here`
</div>
<div id="grabphpdiv">
<?php
$db = mysql_connect("localhost", "root", "root");
if (!$db) {
die("Database connect failed: " . mysql_error());
}
$db_select = mysql_select_db("UNii", $db);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$result = mysql_query("SELECT * FROM Dbsaved", $db);
if (!$result) {
die ("Database query failed: " . mysql_error());
}
$comment = $_POST['$comment'];
while ($row = mysql_fetch_array($result)) {
echo "<div id='posts'>";;
echo "<h2>";
echo $row[1] . "";
echo "</h2>";
echo "<p>";
//echo $timestamp = date('d-m-y G:i:s ');
echo "<br>";
echo "<br>";
echo $row[2] . "";
echo "</p>";
echo "<p>";
echo $row[3] . "";
echo "</p>";
echo 'Delete';
echo "<br>";
echo "<br>";
echo 'Comment: <br>
<input type=text name=comment><br>
<a href=addcomment.php?id=' . $row[0]. '&comment='. $row['$comment'].'>Comment</a>';
echo "<p>";
echo $row['comment'] . "";
echo "</p>";
echo "</div>";
echo "<br>";
}
?>
</div>
</body>
<div id="footer">Copyright &copy James Taylor 2016</div>
</html>
I just ran this code:
$comment = "Hello World!";
$id = 1;
$sql = "UPDATE Dbsaved SET comment = '{$comment}' WHERE id = {$id}";
echo $sql;
and saw:
UPDATE Dbsaved SET comment = 'Hello World!' WHERE id = 1
which is a correct SQL statement, so if it is not working, you might want to play with SQL directly to get something working. Hope that helps!
SOLUTION:
$comment = $_GET['$comment'];
$id = $_GET['$id'];
while ($row = mysql_fetch_array($result)) {
echo "<div id='posts'>";;
echo "<h2>";
echo $row[1] . "";
echo "</h2>";
echo "<p>";
//echo $timestamp = date('d-m-y G:i:s ');
echo "<br>";
echo "<br>";
echo $row[2] . "";
echo "</p>";
echo "<p>";
echo $row[3] . "";
echo "</p>";
echo 'Delete';
echo "<br>";
echo "<br>";
echo $row[4] . "";
echo "<br>";
echo 'Comment: <br>
<form action="addcomment.php?id=' . $row[0]. '" method="post">
<input type=text name=comment><br>
<input type=submit name="submit">
</form>';
echo "<p>";
echo $row['comment'] . "";
echo "</p>";
echo "</div>";
echo "<br>";
}
?>
and:
<?php
$db = mysql_connect("localhost", "root", "root");
if (!$db) {
die("Database connect failed: " . mysql_error());
}
$db_select = mysql_select_db("UNii", $db);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$comment = $_POST['comment'];
$id = $_GET['id'];
$sql = "UPDATE Dbsaved SET comment = '$comment' WHERE id = $id ";
$comment1 = mysql_query($sql);
echo $sql;
if (!$comment1) {
die("did not save comment: " . mysql_error());
}
else {
header("location: UniHelpindex.php");
}
It was to do with mainly needing to get the id which was used in $row[0]' in the form created in the while loop. And actually using the correct syntax for the update Dbsaved... bit.

Not able to store values from dynamic drop list into database on mysql(php)

this is starva i need your help for storing values into database here is my code i want to store the values fetched from list into database '$post[]'
<html>
<head>
<title>order</title>
</head>
<body>
<table>
<form action="order2.php" method="post">
<tr><td><input type="submit" name="submit" value="show"></td>
<td><input type="submit" name="order" value="Order"></td>
</tr>
</table>
<!________________________________!>
<?php
$servername="localhost";
$username="root";
$password="";
$database="mess_db";
$con = mysql_connect($servername,$username,$password);
if(!$con)
{
Die('Could not connect:'.mysql_error());
}
if($con)
{
echo "DB Connected<br>";
}
mysql_select_db($database,$con);
if(isset($_POST["submit"]))
{
$sql="SELECT * FROM menu";
$result= mysql_query($sql,$con);
echo '<select name="roti">';
while($row = mysql_fetch_array($result))
{
echo '<option value="'. $row['roti'].'">' . $row['roti'].'';
}
echo '</select><br><br>';
}
if(isset($_POST["submit"]))
{
$sql="SELECT * FROM menu";
$result= mysql_query($sql,$con);
echo '<select name="sabji">';
while($row = mysql_fetch_array($result))
{
echo '<option value=" ' . $row['sabji'].'">' . $row['sabji'].'';
}
echo '</select><br><br>';
}
if(isset($_POST["submit"]))
{
$sql="SELECT * FROM menu";
$result= mysql_query($sql,$con);
echo '<select name="daal">';
while($row = mysql_fetch_array($result))
{
echo '<option value=" ' . $row['daal'].'">' . $row['daal'].'';
}
echo '</select><br><br>';
}
if(isset($_POST["submit"]))
{
$sql="SELECT * FROM menu";
$result= mysql_query($sql,$con);
echo '<select name="sweet">';
while($row = mysql_fetch_array($result))
{
echo '<option value=" ' . $row['sweet'].'">' . $row['sweet'].'';
}
echo '</select><br><br>';
}
if(isset($_POST["submit"]))
{
$sql="SELECT * FROM menu";
$result= mysql_query($sql,$con);
echo '<select name="starter">';
while($row = mysql_fetch_array($result))
{
echo '<option value=" ' . $row['starter'].'">' . $row['starter'].'';
}
echo '</select><br><br>';
}
if(isset($_POST["order"]))
{
echo "Hi...";
$servername="localhost";
$username="root";
$password="";
$database="mess_db";
$con = mysql_connect($servername,$username,$password);
if(!$con){
Die('Could not connect:'.mysql_error());
}
if($con){
echo "DB Connected<br>";
}
mysql_select_db($database,$con);
if(!$_POST=="")
{
$sql="INSERT INTO order VALUES('$_POST[roti]')";
$result=mysql_query($sql,$con);
echo "Hello";
}
}
mysql_close($con);
?>
please help me on this topic
i ma not at all getting any error and database is still empty

Multiple search form using functions and if else

Hi Im creating a multiple search form using PHP,HTML,SQL with the use of functions, for example I have 3 search fields Firstname, lastname and email. I would let the user input from any of those, therefore i would be needing the if else statement, but to be able to satisfy all conditions it would take a lot of if else, so i think of using a function to output the table and place it inside the if else after the query on the database. But it seems that it could not be able to search in the database if I do it like this it outputs "0 results", but if i remove the function and place it on the end of my script I am able to search in the db but it could not detect my else condition which is "You have not yet entered any values"
function checkres()
{
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
if (!empty($sfname) && empty($slname) && empty($semail) )
{
$sql = "select * from Userlist where FirstName LIKE '%". $sfname ."%'" ;
checkres();
}
else if (!empty($sfname) && !empty($slname) && empty($semail))
{
$sql = "select * from Userlist where FirstName LIKE '%". $sfname ."%' AND LastName LIKE '%". %slname. "%'";
checkres();
}
else
{
echo "You have not yet entered any values ";
}
mysqli_close($conn);
?>
This is the new one
<form method="post" action="#" id="searchform">
First Name:<br>
<input type="text" name="fname">
<br>Last Name:<br>
<input type="text" name="lname">
<br>Email: <br>
<input type="text" name="email">
<br>
<input type="submit" name="submit" value="Search">
</form>
<?php
$sfname = $_POST["fname"];
$slname = $_POST["lname"];
$semail = $_POST["email"];
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
function checkres()
{
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
if(!empty($sfname) || !empty($slname) || !empty($semail)){
$emailQueryPart = !empty($semail) ? "Email LIKE '%$semail%'" : "";
$lastnameQueryPart = !empty($slname) ? "LastName LIKE '%$slname%'" : "";
$firstnameQueryPart = !empty($sfname) ? "FirstName LIKE '%$sfname%'" : "";
$arr = array($emailQueryPart, $lastnameQueryPart,$firstnameQueryPart);
$sql = "select * from Userlist";
for($i = 0; $i < count($arr); $i++){
if(!empty($arr[$i])){
if($i > 0){
$sql.= " AND ".$arr[$i];
}else{
$sql.= " WHERE ".$arr[$i];
}
}
}
}else{
echo "You must enter at least one value";
}
checkres();
mysqli_close($conn);
?>
You have a few errors:
$sql = "select * from Userlist where FirstName LIKE '%". $sfname ."%' AND LastName LIKE '%". %slname. "%'";
You have %slname instead of $slname.
Another mistake is in the program flow. Your else condition, which is saying :"You have not yet entered any values" will be reached in two cases:
When all fields are left blank
When all fields are filled with values.
You don't want that. You have to improve your logic, and build a query based on that, and that can be done like this:
function checkres()
{
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
if(!empty($sfname) || !empty($slname) || !empty($semail)){
$emailQueryPart = !empty($semail) ? "Email LIKE '$semail'" : "";
$lastnameQueryPart = !empty($slname) ? "LastName LIKE '%$slname%'" : "";
$firstnameQueryPart = !empty($sfname) ? "FirstName LIKE '%$sfname%'" : "";
$arr = array($emailQueryPart, $lastnameQueryPart,$firstnameQueryPart);
$sql = "select * from Userlist";
for($i = 0; $i < count($arr); $i++){
if(!empty($arr[$i])){
if($i > 0){
$sql.= " AND ".$arr[$i];
}else{
$sql.= " WHERE ".$arr[$i];
}
}
}
}else{
echo "You must enter at least one value";
}
checkres();
mysqli_close($conn);
?>
What you do is in my opinion a little bit confusing (and a little bit odd n terms of the program's flow structure).
You can simply use an array of variables for your input fields and then loop through the array to generate your SQL statement. So your HTML form would look like this:
<form method="post" action="#" id="searchform">
First Name:<br />
<input type="text" name="queryArray[FirstName]" />
<br />Last Name:<br />
<input type="text" name="queryArray[LastName]" />
<br />Email:<br />
<input type="text" name="queryArray[Email]" />
<br />
<input type="submit" name="submit" value="Search" />
</form>
A more clear structure would be if you define these 2 functions, which of course can be placed anywhere in your PHP code block:
function createSql($queryArray) {
if (is_array($queryArray)) {
$sql = null;
foreach ($queryArray as $key => $value) {
if ($value != null ) {
$addQuery = "`".$key."` LIKE '%".$value."%'";
if ($sql == null)
$sql = "SELECT * FROM `Userlist` WHERE ".$addQuery;
else
$sql = $sql." AND ".$addQuery;
}
return $sql;
}
}
function checkres($sql) {
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
die("Connection failed: " . mysqli_connect_error());
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0) {
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else
echo "0 results";
// Close connection
mysqli_close($conn);
}
Finally you will have to call the functions according to user activity:
if ($_POST != null) {
$sql = createSql($_POST[queryArray]);
checkres($sql);
}
An example how the SQL generation works is listed here

How do I reduce the number of variables and connections for php connecting to mysql server?

I am trying to reduce the number of connections that this page makes. Everything I read says that only one connection should be enough however if I remove the additional connections the page doesn't connect to my server and provide me the results I am looking for. Also one of the queries I am using twice but if I call the original query the second time it also does not work.
What am I doing wrong?
<?php
$dbaddress="localhost";
$dbuser="testuser";
$dbpass="testpass";
$dbname="testdb";
$dbtable="elo";
$query="SELECT Sequnce, mcacctname FROM `elo`;";
$con=mysqli_connect($dbaddress,$dbuser,$dbpass,$dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysql_connect($dbaddress, $dbuser, $dbpass);
mysql_select_db($dbname);
$sql = "SELECT Sequence, mcacctname FROM `elo`;";
$result = mysql_query($sql);
mysql_connect($dbaddress, $dbuser, $dbpass);
mysql_select_db($dbname);
$sql2 = "SELECT Sequence, mcacctname FROM `elo`;";
$result2 = mysql_query($sql2);
$sqlstart = "SELECT mcacctname, elo FROM `elo`;";
$q = mysql_query($sqlstart);
?>
<form name="player1" method="post" action="predictions.php">
<label for="Select Player 1">Select Player 1:
<?php
echo "<select name='elouser1'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['Sequence'] . "'>" . $row['mcacctname'] . "</option>";
}
echo "</select>";
?>
</label>
<input type="submit" value="Player 1 Wins">
</form>
<br>
<form name="player2" method="post" action="predictions.php">
<label for="Select Player 2">Select Player 2:
<?php
echo "<select name='elouser2'>";
while ($row2 = mysql_fetch_array($result2)) {
echo "<option value='" . $row2['Sequence'] . "'>" . $row2['mcacctname'] . "</option>";
}
echo "</select>";
?>
</label>
<input type="submit" value="Player 2 Wins">
</form>
<table>
<tr>
<?
echo '<div class="container">';
while($res = mysql_fetch_array($q)){
echo '<tr><td><div class="item">'. $res['mcacctname'] . '</td><td>' . $res ['elo'] . '</div></td></tr>';
}
echo '</div>';
mysqli_close($con);
?>
</tr>
</table>
Once a connection is open in a page you don't need to re-open it for each query. You can simply remove all the statements that create a connection and select the database, except the first one.
Note you're using mysqli to open the connection, but mysql to query it. The two sets of functions are not interchangeable: use mysqli as 'mysql' is deprecated and support will be removed in the future.
Try this:
$dbaddress="localhost";
$dbuser="testuser";
$dbpass="testpass";
$dbname="testdb";
$dbtable="elo";
$query="SELECT Sequence, mcacctname FROM `elo`;";
$con=mysqli_connect($dbaddress,$dbuser,$dbpass,$dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT Sequence, mcacctname FROM `elo`;";
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
$sql2 = "SELECT Sequence, mcacctname FROM `elo`;";
$result2 = mysqli_query($con,$sql2) or die(mysqli_error($con));
$sqlstart = "SELECT mcacctname, elo FROM `elo`;";
$q = mysqli_query($con, $sqlstart) or die(mysqli_error($con));
?>
<form name="player1" method="post" action="predictions.php">
<label for="Select Player 1">Select Player 1:
<?php
echo "<select name='elouser1'>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['Sequence'] . "'>" . $row['mcacctname'] . "</option>";
}
echo "</select>";
?>
</label>
<input type="submit" value="Player 1 Wins">
</form>
<br>
<form name="player2" method="post" action="predictions.php">
<label for="Select Player 2">Select Player 2:
<?php
echo "<select name='elouser2'>";
while ($row2 = mysqli_fetch_array($result2)) {
echo "<option value='" . $row2['Sequence'] . "'>" . $row2['mcacctname'] . "</option>";
}
echo "</select>";
?>
</label>
<input type="submit" value="Player 2 Wins">
</form>
<table>
<tr>
<?
echo '<div class="container">';
while($res = mysqli_fetch_array($q)){
echo '<tr><td><div class="item">'. $res['mcacctname'] . '</td><td>' . $res ['elo'] . '</div></td></tr>';
}
echo '</div>';
mysqli_close($con);
?>
</tr>
</table>

Categories