mysqli_query not recognizing database? - php

I've already asked a question on this code I'm working on, just not about the same problem. Either way sorry for the repost!
So I'm having trouble with the code, as follows:
<?php
// Create connection
$host = "localhost";
$username="tudor";
$password="passw0rd";
$con=mysqli_connect($host, $username, $password);
if(! $con )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br />';
$db_1 = mysqli_select_db( $con, 'db_1' );
if (! $db_1) {
die('Could not select database: ' . mysqli_error());
}
else {
echo "Database successfully selected<br />===============================<br />";
}
//===================================
$a = 1;
$b = 2234;
$table = "CREATE TABLE info (id INT NOT NULL AUTO_INCREMENT, city CHAR(40), country CHAR(40))";
if (! $table) {
die('Could not create table ' . mysqli_error($con));
}
else {
echo "Table created<br />";
}
$insert = "INSERT INTO info (city, country) VALUES ($a, $b)";
if (! $insert) {
die('Could not insert ' . mysqli_error($con));
}
else {
echo "Inserted<br />";
}
$select = "SELECT * FROM info";
$result = mysqli_query ($con, $insert);
if (! $result) {
die('Result not working ' . mysqli_error($con));
}
else {
echo "Result working<br />";
}
echo "result: ".$result['city']. " ";
mysqli_close($con);
?>
This outputs (blockquote doesn't display page breaks):
Connected successfully Database successfully selected
=============================== Table created Inserted Result not working Table 'db_1.info' doesn't exist
What does it mean by "Table 'db.info'" not existing? It clearly says that my info table was created...
What I tried doing is inverting the variables in the $result query: $result = mysqli_query ($insert, $con);, because I had seen that syntax in a book. However all it gave was the following message in the output:
Warning: mysqli_query() expects parameter 1 to be mysqli, string given
in C:\wamp...
Thoughts anyone? Thanks in advance!
Edit: really appreciate the help everyone, thanks a lot!

You are not doing a mysqli_query() on $table before your mysqli_query() on $insert, and you are not doing a mysqli_query() on $select
$table = "CREATE TABLE info (id INT NOT NULL AUTO_INCREMENT, city CHAR(40), country CHAR(40))";
if (! $table)
$insert = "INSERT INTO info (city, country) VALUES ($a, $b)";
if (! $insert) {
$select = "SELECT * FROM info";
$result = mysqli_query ($con, $insert);
if (! $result)
try adding the mysqli_query() -
$table_sql = "CREATE TABLE `info` (`id` INT NOT NULL AUTO_INCREMENT, `city` CHAR(40), `country` CHAR(40), PRIMARY KEY (`id`))";
$table = mysqli_query ($con, $table_sql);
if (! $table) {
die('Could not create table ' . mysqli_error($con));
}
else {
echo "Table created<br />";
}
$insert_sql = "INSERT INTO `info` (`city`, `country`) VALUES ('$a', '$b')";
$insert = mysqli_query ($con, $insert_sql);
if (! $insert) {
die('Could not insert ' . mysqli_error($con));
}
else {
echo "Inserted<br />";
}
$select = "SELECT * FROM `info`";
$result = mysqli_query ($con, $select);
if (! $result) {
die('Result not working ' . mysqli_error($con));
}
else {
echo "Result working<br />";
}
Edit
Also, this line will fail -
echo "result: ".$result['city']. " ";
as you have to fetch the array from the query using mysqli_fetch_array()
$results = mysqli_fetch_array($result);
echo "result: ".$results['city']. " ";

Table 'db_1.info' doesn't exist
Means, that table info does not exist in db db_1 so, make sure if that is the case.

ok. Here is your code.
if(! $con )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br />';
if (!$con) {trigger_error("Could not connect to MySQL: " . mysqli_connect_error()); }
else { echo "Database successfully connected<br />===============================<br />"; }
$a = 1;
$b = 2234;
$table = mysqli_query($con,"CREATE TABLE IF NOT EXISTS info (`id` int(11) unsigned NOT NULL auto_increment,
`city` CHAR(40),
`country` CHAR(40), PRIMARY KEY (`id`) )ENGINE=MyISAM DEFAULT CHARSET=utf8");
if (!$table) {
die('Could not create table ' . mysqli_error($con));
}
else {
echo "Table created<br />";
}
$insert = mysqli_query ($con,"INSERT INTO info (city, country) VALUES ('$a', '$b')");
if (!$insert) {
die('Could not insert ' . mysqli_error($con));
}
else {
echo "Inserted<br />";
}
$select = mysqli_query ($con,"SELECT * FROM info");
$res=mysqli_fetch_array($select);
if (! $res) {
die('Result not working ' . mysqli_error($con));
}
else {
echo "Result working<br />";
}
echo "result: ".$res['city']. " ";
echo "result: ".$res['country']. " ";
mysqli_close($con);

Related

Error in SQL syntax (quotes ???!!!)

Can someone help me to debug this
<?php
$file_name = basename(__FILE__,'.php');
include("conf.php");
include("XMLSoccer.php");
$years = 1; ///<-------NUMBER OF YEARS TO GO BACK
$leagueretrive = 3; ///<--------THE LEAGUE ID TO RETRIEVE DATA FOR
$date1 = date('y', strtotime("-$years years"));
$date2 = date("y");
//CHECKING IF TABLE EXIST IF NOT CREATE NEW
$table = $file_name;
$query = "SELECT ID FROM " . $table;
$resultat = mysqli_query($conn,$query);
if(empty($resultat)) {
echo "<p>" . $table . " table does not exist</p>";
$query = mysqli_query($conn,"CREATE TABLE IF NOT EXISTS $file_name (
Id int NOT NULL PRIMARY KEY,
HomeGoalDetails varchar(800) NOT NULL,
)CHARACTER SET utf8 COLLATE utf8_general_ci");
}
else {
echo "<p>" . $table . "table exists</p>";
} // else
/////GETING THE DATA FROM SERVICE
try {
$soccer = new XMLSoccer($api_key);
$soccer->setServiceUrl("http://www.xmlsoccer.com/FootballDataDemo.asmx");
$results = $soccer->GetHistoricMatchesByLeagueAndSeason(array("league"=>$leagueretrive,"seasonDateString"=>"$date1$date2"));
print_r($results);
} catch (XMLSoccerException $e) {
echo "XMLSoccerException: " . $e->getMessage();
}
foreach ($results->Match as $team) {
$id = $team->Id;
$homeGoalDetails = $team->HomeGoalDetails;
///INSERTING DATA INTO THE TABLE
$sql = "INSERT INTO $file_name (HomeGoalDetails)
VALUES ('$homeGoalDetails')
on duplicate key update HomeGoalDetails='$homeGoalDetails'";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The response what i get
Error: INSERT INTO testing2 (HomeGoalDetails) VALUES ('35': Stefan
Johansen;4': penalty Leigh Griffiths;') on duplicate key update
HomeGoalDetails='35': Stefan Johansen;4': penalty Leigh Griffiths;'
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near ': Stefan Johansen;4': penalty Leigh Griffiths;') on duplicate
key update HomeGo' at line 2 Process finished with exit code 0
You've got unescaped quotes in your query.
Try:
<?php
$file_name = basename(__FILE__,'.php');
include("conf.php");
include("XMLSoccer.php");
$years = 1; ///<-------NUMBER OF YEARS TO GO BACK
$leagueretrive = 3; ///<--------THE LEAGUE ID TO RETRIEVE DATA FOR
$date1 = date('y', strtotime("-$years years"));
$date2 = date("y");
//CHECKING IF TABLE EXIST IF NOT CREATE NEW
$table = $file_name;
$query = "SELECT ID FROM " . $table;
$resultat = mysqli_query($conn,$query);
if(empty($resultat)) {
echo "<p>" . $table . " table does not exist</p>";
$query = mysqli_query($conn,"CREATE TABLE IF NOT EXISTS $file_name (
Id int NOT NULL PRIMARY KEY,
HomeGoalDetails varchar(800) NOT NULL,
)CHARACTER SET utf8 COLLATE utf8_general_ci");
}
else {
echo "<p>" . $table . "table exists</p>";
} // else
/////GETING THE DATA FROM SERVICE
try {
$soccer = new XMLSoccer($api_key);
$soccer->setServiceUrl("http://www.xmlsoccer.com/FootballDataDemo.asmx");
$results = $soccer->GetHistoricMatchesByLeagueAndSeason(array("league"=>$leagueretrive,"seasonDateString"=>"$date1$date2"));
print_r($results);
} catch (XMLSoccerException $e) {
echo "XMLSoccerException: " . $e->getMessage();
}
foreach ($results->Match as $team) {
$id = $team->Id;
$homeGoalDetails = $team->HomeGoalDetails;
///INSERTING DATA INTO THE TABLE
$sql = "INSERT INTO $file_name (HomeGoalDetails)
VALUES ('".mysqli_real_escape_string($conn,$homeGoalDetails)."')
on duplicate key update HomeGoalDetails='".mysqli_real_escape_string($conn,$homeGoalDetails)."'";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

MySQL Database not Updating when Form Submitted using PHP

This is a webpage that I have:
// Info to connect to the Wishlist database
$servername = "em";
$dbusername = "";
$password = "!19";
$dbname = "";
// To connect to the database please
$conn = new mysqli($servername, $dbusername, $password, $dbname);
// If unable to connect to the database display this error
if ($conn->connect_error) {
echo "Connection to wishlist failed";
die("Connection failed: " . $conn->connect_error);
}
echo "Once you have added creatures to your wishlist, click " .
"<strong><a href='http://eggcavity.com/edit-wishlist'>here</a></strong> to edit your wishlist.";
// Get current user's username
$current_user = wp_get_current_user();
$username = $current_user->user_login;
// Retrieve data from the database
$sql = "SELECT Name, Stage1 FROM Creatures";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// Display all of the data from the database
echo '<form method="POST">';
while($row = $result->fetch_assoc()) {
echo '<div style="display: inline-block; width: 30%;">' .
'<img src="' . $row["Stage1"] . '"><br>'.
$row["Name"] .
'<br><input type="checkbox" name="creautres[]" value="' .
$row["Name"] .
'"></div>';
}
echo '<br><br><input type="submit" value="Submit"></form>';
} else {
echo "Creatures not found";
}
if(isset($_POST['submit'])){
foreach($_POST['creatures'] as $selected){
$sql = "INSERT INTO " . $username .
" (Creature, Picture, Stage, Gender, Frozen, Notes) VALUES ('" .
$selected . "', 'http://static.eggcave.com/90x90/" . $selected .
"_1', 'Stage1', 'Unspecified', 'Unspecified', 'Unspecified', '')";
if ($conn->query($sql) === FALSE) {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
// Close the connection to the database
$conn->close();
It displays like I want it to:
But it doesn't update the database when I click the submit button.
I've tried echoing $stmt, it seemed to be written as it should be.
When I try echoing $selected, within the loop it doesn't seem to output anything.
Can you help me?
I have updated the code to use one database. Please help me. It still isn't adding.
You had a typo in your checkbox name. I re-did the submit line in the form and the isset() I believe.
The below includes activating error reporting, a try/catch, binding for safety against sql injection. The data saves. You will need to deal with what should be unique data getting saved more than once of course. For instance, a unique key on (Creature,Username). And I would re-think the columns for Id's, but this was your table design. Thanks for allowing us to show you a re-use of a table. Good luck.
schema (from you):
drop table if exists Wishlists;
CREATE TABLE `Wishlists` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Creature` varchar(100) DEFAULT NULL,
`Picture` varchar(200) DEFAULT NULL,
`Stage` varchar(100) DEFAULT NULL,
`Gender` varchar(100) DEFAULT NULL,
`Frozen` varchar(100) DEFAULT NULL,
`Notes` varchar(500) DEFAULT NULL,
`Username` varchar(100) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB; -- <------------------------ went with InnoDB
-- truncate table Wishlists; -- used during early testing
PHP (eggs01.php):
// Info to connect to the Wishlist database
$servername = "serve it up";
$dbusername = "dbu dbu dbu";
$password = "OpenSesame";
$dbname = "my db name";
try {
// To connect to the database please
$conn = new mysqli($servername, $dbusername, $password, $dbname);
if ($conn->connect_error) {
die('Connect Error (' . $conn->connect_errno . ') '
. $conn->connect_error);
}
echo "I am connected and feel happy.<br/>";
if(isset($_POST['submit'])){
// Postback - submit
// Get current user's username
//$current_user = wp_get_current_user(); // remmed out, I don't have your system
//$username = $current_user->user_login; // remmed out, I don't have your system
$theCount=0;
foreach($_POST['creatures'] as $selected){
$Creature=$selected;
$Picture="http://static.eggcave.com/90x90/" . $selected . "_1";
$Stage="Stage1";
$Gender="Unspecified";
$Frozen="Unspecified";
$Notes="Unspecified";
$Username="Stackoverflow123";
$sql = "INSERT Wishlists (Creature, Picture, Stage, Gender, Frozen, Notes, Username) " .
" VALUES (?,?,?,?,?,?,?)";
$stmt = $conn->prepare($sql); // SQL Injection - safe prepare / bind / execute
// 7 s's means 7 strings:
$stmt->bind_param('sssssss', $Creature, $Picture, $Stage, $Gender, $Frozen, $Notes, $Username);
$stmt->execute();
$theCount++;
}
echo "<br>Santa has been notified, count = ".$theCount."<br>";
}
else {
// Just display the form
// Retrieve data from the database
$result = $conn->query("SELECT Name, Stage1 FROM Creatures");
if ($result->num_rows > 0) {
// Display all of the data from the database
echo '<form method="POST">';
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
echo '<div style="display: inline-block; width: 30%;">' .
'<img src="' . $row["Stage1"] . '"><br>'.
$row["Name"] .
'<br><input type="checkbox" name="creatures[]" value="' .
$row["Name"] .
'"></div>';
}
echo '<br><br><button type="submit" name="submit">Submit</button></form>';
$result->close();
} else {
echo "Creatures not found";
}
}
} catch (mysqli_sql_exception $e) {
throw $e;
}
After the submit having selected 3 eggs:
Database Image:
First of all, look at code
$dbname1 = *****";
Here you are missing " :
So replace this with
$dbname1 = "*****";
and try again
First issue is you should never run a SQL statement in a Loop ALWAYS AVOID THIS - as it will put your server through a lot of strain.
And 2nd try this and tell me the out put
foreach($_POST['creatures'] as $selected){
$stmt = "INSERT INTO " . $username . " (Creature, Picture, Stage, Gender, Frozen, Notes) VALUES ('" . $selected . "', 'http://static.eggcave.com/90x90/" . $selected . "_1', 'Stage1', 'Unspecified', 'Unspecified', 'Unspecified', '')";
if ($conn->query($stmt) === TRUE) {
}
}
TO
foreach($_POST['creatures'] as $selected){
$stmt = "INSERT INTO " . $username . " (Creature, Picture, Stage, Gender, Frozen, Notes) VALUES ('" . $selected . "', 'http://static.eggcave.com/90x90/" . $selected . "_1', 'Stage1', 'Unspecified', 'Unspecified', 'Unspecified', '')";
$result = $conn->query($stmt) OR die(var_dump($conn));
var_dump($result->fetch_array(MYSQLI_ASSOC));
die;
}

Displaying ALL data from sql table in PHP?

When I print my code it only prints the question and description of id = 1 but not the rest of the table.
here is my code.
Please show me how to print my entire table which has like 20 questions or so...and also please show me how to make it so that the questions stay on the browser (even when I refresh the page) because currently the data does not stay on the browser when i refresh the page.
Thanks So Much!
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
} else {
echo "failed to fetch array";
}
}
?>
You need a for each loop:
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
} else {
echo "failed to fetch array";
}
}
?>
All I've done there is change:
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
to:
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
fetch_assoc() — Fetch a result row as an associative array
so it gets only 1 row you need to loop through the rest of the rows check the examples reference from php docs

Inserting a row into a table using PHP MYSQL

The following php code is meant to drop a table if it exists, create the table, use the table, and then insert a row into the table.
Everything works apart from the insert. I am new to PHP and MYSQL and I have tried many permutations of different types of quotes (singles, doubles, this one: `) but cannot get the data to be inserted into the table.
Can anybody shed some light on what is wrong with this?
$retval = mysqli_query($conn,'INSERT INTO `performance` (manager, program, programid, yearmonth, performance) VALUES ("manager1", "program1","programid1", "199901", "-3.4")');
The php script below gives the output:
Connected successfully
Table dropped successfully.
DB used successfully.
Table created successfully.
Could not insert data.
So everything worked apart from the insert.
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$retval = mysql_query('DROP TABLE IF EXISTS `managedfutures`.`performance`') or die(mysql_error());
if(! $retval )
{
die('Could not drop table ' . mysql_error());
}
echo "Table dropped successfully.";
echo "<br>";
$retval = mysql_query("USE managedfutures", $conn);
if(! $retval )
{
die('Could not use DB' . mysql_error());
}
echo "DB used successfully.";
echo "<br>";
$sql = "CREATE TABLE performance( ".
"performance_id INT NOT NULL AUTO_INCREMENT, ".
"manager VARCHAR(255) NOT NULL, ".
"program VARCHAR(255) NOT NULL, ".
"programid VARCHAR(255) NOT NULL, ".
"yearmonth VARCHAR(6) NOT NULL, ".
"performance FLOAT NOT NULL, ".
"PRIMARY KEY (performance_id )); ";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not create table: ' . mysql_error());
}
echo "Table created successfully.";
echo "<br>";
$retval = mysqli_query($conn,'INSERT INTO `performance` (manager, program, programid, yearmonth, performance) VALUES ("manager1", "program1","programid1", "199901", "-3.4")');
if(! $retval )
{
die('Could not insert data. ' . mysql_error());
}
echo "Data inserted successfully.";
echo "<br>";
return;
Thanks to Mike W for pointing out that I had mixed mysql and mysqli commands! I am new to php/mysql and did not realise that there was a difference between the two. There was another error also, I was inputting a number as a string in the insert statement. I.e. I wrote "-3.4" instead of just -3.4.
For completeness, here is the fixed version which works.
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_errno) {
die("Failed to connect to MySQL: " . $mysqli->connect_error);
}
echo 'Connected successfully<br />';
$retval = mysqli_query($mysqli,"DROP TABLE IF EXISTS `performance`");
if(! $retval )
{
die('Could not drop table ' . $mysqli->query_error);
}
echo "Table dropped successfully.";
echo "<br>";
$sql = "CREATE TABLE performance( ".
"performance_id INT NOT NULL AUTO_INCREMENT, ".
"manager VARCHAR(255) NOT NULL, ".
"program VARCHAR(255) NOT NULL, ".
"programid VARCHAR(255) NOT NULL, ".
"yearmonth VARCHAR(6) NOT NULL, ".
"performance FLOAT NOT NULL, ".
"PRIMARY KEY (performance_id )); ";
$retval = mysqli_query($mysqli, $sql);
if(! $retval )
{
die('Could not create table: ' . $mysqli->query_error);
}
echo "Table created successfully.";
echo "<br>";
$retval = mysqli_query($mysqli, "INSERT INTO `performance` (`manager`, `program`,`programid`, `yearmonth`, `performance`) VALUES ('manager1', 'program1','programid1', '199901', -3.4)");
if(! $retval )
{
die('Could not insert data. ' . $mysqli->query_error);
}
echo "Data inserted successfully.";
echo "<br>";
return;
You're mixing mysql_*() and mysqli_*() calls. The two are different and cannot be used together. mysql_*() is deprecated - use only mysqli_*().
You have used mysql_query throughout your code
$retval = mysql_query( $sql, $conn ); //**You have used mysql_query**
if(! $retval )
{
die('Could not create table: ' . mysql_error());
}
echo "Table created successfully.";
echo "<br>";
Suddenly a mysqli_query is seen (MAGIC !!!).
$retval = mysqli_query($conn,'INSERT INTO `performance` (manager, program, programid, yearmonth, performance) VALUES ("manager1", "program1","programid1", "199901", "-3.4")');
^^
// SUDDENLY you see mysqli_query

What value should I use? (Choose to display table data or not upon this variable)

form1.php
<?php
$connection = mysql_connect("localhost","root","")
or die ("Couldn't Connect To Server");
$query = "CREATE DATABASE IF NOT EXISTS db1";
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());
$db = mysql_select_db("db1", $connection)
or die ("Couldn't Select Database");
$query = "CREATE TABLE IF NOT EXISTS table1 (fname VARCHAR(20), lname VARCHAR(20), mail VARCHAR(20))";
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());
function insertvalues (){if ( isset ($_POST['fname']{0}, $_POST['lname']{0}, $_POST['mail']{0}) ){
$query = "INSERT INTO table1 (fname, lname, mail) VALUES ('".$_POST[fname]."', '".$_POST[lname]."', '".$_POST[mail]."')";
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());
}
else{
echo "No Values Entered. Please Press Back In Your Browser And Enter Some Values.";
}}
$value1 = "";
if isset($value1) {$query = "SELECT * FROM table1";
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());
echo "<TABLE BORDER = '1'>";
echo "<TR>";
echo "<TH>First Name</TH><TH>Last Name</TH><TH>Mail</TH>";
echo "</TR>";
while ($row = mysql_fetch_array($result))
{
echo "<TR>";
echo "<TD>", $row['fname'], "</TD><TD>",
$row['lname'], "</TD><TD>",
$row['mail'], "</TD>";
echo "</TR>";
}
echo "</TABLE>";}
else {
echo "<BR>No Table".
}
mysql_close($connection);
?>
I'm contemplating on what to put inside $value1. How do I check if"No Values Entered. Please Press Back In Your Browser And Enter Some Values." error was shown, and if it was, do not display the table?
is this what you asked for?
<?php
$connection = mysql_connect("localhost","root","")
or die ("Couldn't Connect To Server");
$query = "CREATE DATABASE IF NOT EXISTS db1";
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());
$db = mysql_select_db("db1", $connection)
or die ("Couldn't Select Database");
$query = "CREATE TABLE IF NOT EXISTS table1 (fname VARCHAR(20), lname VARCHAR(20), mail VARCHAR(20))";
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());
function insertvalues (){if ( isset ($_POST['fname']{0}, $_POST['lname']{0}, $_POST['mail']{0}) ){
$query = "INSERT INTO table1 (fname, lname, mail) VALUES ('".$_POST[fname]."', '".$_POST[lname]."', '".$_POST[mail]."')";
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());
return true;
}
else{
echo "No Values Entered. Please Press Back In Your Browser And Enter Some Values.";
return false;
}}
$value1 = insertvalues();
if isset($value1) {$query = "SELECT * FROM table1";
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());
echo "<TABLE BORDER = '1'>";
echo "<TR>";
echo "<TH>First Name</TH><TH>Last Name</TH><TH>Mail</TH>";
echo "</TR>";
while ($row = mysql_fetch_array($result))
{
echo "<TR>";
echo "<TD>", $row['fname'], "</TD><TD>",
$row['lname'], "</TD><TD>",
$row['mail'], "</TD>";
echo "</TR>";
}
echo "</TABLE>";}
else {
echo "<BR>No Table".
}
mysql_close($connection);
?>
the diffrence from your code is i added a return value of true if its successfully inserted and false if not. and gave that value into $value1.
And if i may .. this code have some serious performace and other problems starting with email often needs more than 20 charaters, and running a create db, create table queries on every run .. etc.

Categories