Field not being inserted into mysql database from php - php

I have a little problem where a field is not being inserted into my users table. I have two tables as follows:
users - id, gamerid, email, password, country, country_code
countries - country_id, country, country_code
Now i have a signup form that comprises of gamerid,email,password and a country select (pulls from the countries table using php)
My problem is that when i submit the form, i want to run a query to pull the country code from the table which matches what was selected by the user and insert these fields into the users table. All my data is inserting correctly except for the country_code.
Here is my code for the html select section:
<select name = "country_create" style = "height: 25px; width: 180px;">
<option value="0" selected="selected" class = "signup_form_country_select_class">Select your country</option>
<?php
include "config.php";
$connection = mysql_connect($host, $username, $password) or die(mysql_error());
mysql_select_db($dbname, $connection) or die(mysql_error());
$result = mysql_query('SELECT country FROM countries');
while($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['country'].'">'.$row['country'].'</option>';
}
?>
</select>
And here is the php from the register script:
$connection = mysql_connect($host, $username, $password) or die(mysql_error());
mysql_select_db($dbname, $connection) or die(mysql_error());
// INPUT CLEANING FUNCTION
function clean($str)
{
$cleaned = mysql_real_escape_string(strip_tags($str));
return $cleaned;
}
$gamerid = clean($_POST['gamerid_create']);
$email = clean($_POST['email_create']);
$password = clean($_POST['password_create']);
$country = ($_POST['country_create']);
$cc_qry = "SELECT country_code FROM countries WHERE country = '$country'";
$country_code = mysql_query($cc_qry);
$insert = "insert into users(gamerid,email,password,country,country_code) values('$gamerid','$email','$password','$country','$country_code')";
mysql_query($insert, $connection);
Thanks in advance guys!

First - use PDO or mysqli functions, but secondly - you must also fetch data from query result:
$res = mysql_query($cc_qry);
$res_cc = mysql_fetch_assoc($res);
$country_code = $res_cc['country_code'];

Related

Printing of data

I created 3 tables in my database "Colleges" in PhpMyAdmin. The names of the tables are "cool", "data" and "tab". The first table "cool" consists of the the names of the states of India. It has two columns : ID and Statename. From the data in this table, I created a drop down list in HTML form. Further the HTML form consists of the name, email id, contact and the address. The user has to fill in the details and select his/her state from the drop down list. Now, the user input consisting of name, email id, contact and the address goes into the second table "data" and the selected state from the drop down list goes into the 3rd table "tab", "tab" consists of 2 columns ID and stat where the state name gets stored here. I joined the above two tables "data" and "tab" using inner join of SQL. When I fetched the data in another web page, the name, email id, contact and address are getting printed but not the the statename. Instead of the state name, ID of the statename (as given in table cool) is getting printed.
I want state name to get printed.
Here is the drop down list created using the data from my database :
<td>State :</td>
<td>
<?php
$mysqli = new mysqli('localhost', 'root', '', 'colleges');
$resultset = $mysqli->query("SELECT ID, Statename from cool");
?>
<select name="state">
<?php
while($rows = $resultset->fetch_assoc())
{
$ID = $rows['ID'];
$Statename = $rows['Statename'];
echo "<option value='$ID'>$Statename</option>";
}
?>
</select>
</td>
</tr>
And what are the changes to be done here to insert the selected dropdown state name into the table in my database ?
<?php
$connection = mysqli_connect("localhost", "root", "", "colleges");
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$name = $_POST['name'];
$email = $_POST['email'];
$contact = $_POST['contact'];
$address = $_POST['address'];
$state = $_POST['state'];
if($name !=''||$email !=''){
//Insert Query of SQL
$insert = "INSERT Into data(student_name, student_email, student_contact, student_address) values ('$name', '$email', '$contact', '$address')";
$query = mysqli_query($connection, $insert);
$insert2 = "INSERT Into tab(stat) values ('$state')";
$query2 = mysqli_query($connection, $insert2);
echo "<br/><br/><span>Data has been inserted successfully</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank</p>";
}
}
mysqli_close($connection); // Closing Connection with Server
?>
3). The printing part:
<?php
$hostname = "localhost";
$dbname = "colleges";
$username = "root";
$password = "";
$conn = mysqli_connect("$hostname","$username","","$dbname");
if(mysqli_connect_errno())
{
echo "Failed to Connect MySQL (phpmyadmin) Database: ".mysqli_connect_error();
}
$query = ("select student_name, student_email, student_contact, student_address, stat from data t2 inner join tab t3 on t2.ID=t3.ID");
$result = mysqli_query($conn, $query);
echo "<center>";
echo "<h1>Student list</h1>";
echo "<hr/>";
echo"<table border = '1'>
<tr>
<th>Name</th>
<th>Email</th>
<th>Contact</th>
<th>Address</th>
<th>State</th>
</tr>";
while ($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>".$row['student_name']."</td>";
echo "<td>".$row['student_email']."</td>";
echo "<td>".$row['student_contact']."</td>";
echo "<td>".$row['student_address']."</td>";
echo "<td>".$row['stat']."</td>";
echo "</tr>";
}
echo "</table>";
echo "</center>";
mysqli_close($conn);
?>
echo "<option value='$ID'>$Statename</option>";
and
$state = $_POST['state'];
and
$insert2 = "INSERT Into tab(stat) values ('$state')";
You are actually not inserting the name of the state, but it's id, as the select return the selected option's value, not it's content. You can either change the first line to
echo "<option value='$Statename'>$Statename</option>";
which is a weird solution, or just use a join in your mysql query to get the statename
JOIN ON cool.ID = tab.stat
Extention:
When you use select, the innerHTML of option is displayed, but the value is sent in POST. So if you write
<select name="state">
<option value="1">name</option>
</select>
You will see name name, but the 1 will be sent.
On the next page, $State = $_POST['state']; will have $State the value of '1'. In the SQL you put this value to your stat field in your database, with a generated ID. It means, your ID won't hold any data, but the state field will!
So when printing on the third page, you have to join the list of states by it's ID with the stored stateid in the 'state' field. Then you will be able to print the statenames.
"SELECT * FROM t2 LEFT JOIN t3 ON t2.?? = t3.?? LEFT JOIN t1 ON t1.ID = t3.state"
Or something similar. Do you have a field you can use to join the t2 and t3 tables? It seems you are losing data when inserting to your database.

Display only data from table using keyword entered in search box in PHP

I am trying to filter out data from my table using a searchbox in HTML. My search box which should return value from SQL query.
But even if I search, the filtered table is not displayed.
I have checked the 'LIKE' query in phpMyAdmin with '%n' (which I meant an entry in my table ending with 'n' ) and it works, but since in mine I am searching for a specific text that is entered in the search box, I couldn't check for the query that I am using.
Would really appreciate any help and thanks in advance.
<?php
//error_reporting(E_ERROR | E_PARSE);
$db_host = 'localhost';
$db_user = 'zamil'; // Username
$db_pass = '1234'; // Password
$db_name = 'resi'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
else{
print("connected");
}
$output = '';
$query = '';
if (isset($_GET['search'])){
$searchq = $_GET['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query( $conn, "SELECT * FROM 'salesflow' WHERE 'Rep Name'
LIKE '%$searchq%'") or die("could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = 'There was no entries';
}else{
while ($row = mysqli_fetch_array($query)) {
$cname = $row['Source of Content'];
$rname = $row['Rep Name'];
$output .= '<div>'.cname.' '.rname.'</div>';
}
}
}
if ($query != 0) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
<form action="Sales1.php" method="post">
Search: <input type="text" name="search" />
<input type="submit" value="Search" /><br />
</form>
<?php print("$output"); ?>
</body>
</html>
Your SQL query is incorrect:
SELECT * FROM 'salesflow' WHERE 'Rep Name' LIKE '%$searchq%'
You put single quotes (') around the salesflow table name and Rep Name column name but you should use backticks (`) instead.
For more information see Using backticks around field names.
I think you have entered a wrong query syntax.
$query = mysqli_query( $conn, "SELECT * FROM 'salesflow' WHERE
'Rep Name' LIKE '%$searchq%'") or die("could not search!");
It should be written like this:
$query = mysqli_query( $conn, "SELECT * FROM 'salesflow' WHERE
'Rep Name' LIKE '%".$searchq."%'") or die("could not search!");
Always use ' for string in query.
Also, my additional recommendation is not to use SQL for searching in the table, instead, use DataTable based on AngularJS.

How to select one cell through the selected id. SQL

I have a database table in which there are 2 columns. The first is the ID, the second is the price. When the user selects a product on the site, a product card is opened (this will be id). At the bottom there is a calculator with prices where you need to load the price from the second column. Question: how to make a request for a specific ID(for loading price from second column). Here's the code that I could do.This code displays all IDs and prices, but need only when you select the product and only for it. Any help. Thank you
<?php
ini_set('display_errors','On');
error_reporting('E_ALL');//error's show
$host = 'localhost'; // host name
$database = 'test_sql'; // database name
$user = 'root'; // user name
$pswd = ''; // password
$dbh = mysql_connect($host, $user, $pswd) or die("Could not to connect MySQL.");//connect to mySQL
mysql_select_db($database) or die("Could not to connect database.");
$query = "SELECT * FROM `oc_product`";//load from product table
$res = mysql_query($query);
$row = mysql_fetch_array($res);//array call
while($row = mysql_fetch_array($res)){
echo "ID: ".$row['product_id']."<br>";//output for each ID
echo "Цена: ".$row['price']."<br>";//output for each price
}
?>
when you select a product pass that id to the function and update your query like :
$dbh = mysql_connect($host, $user, $pswd) or die("Could not to connect MySQL.");//connect to mySQL
mysql_select_db($database) or die("Could not to connect database.");
$query = "SELECT * FROM `oc_product` WHERE 'product_id' = <id that you passed>";//load from product table
$res = mysql_query($query);
$row = mysql_fetch_array($res);

Display amount of registered users in MySQL database using PHP

I want to display the current amount of users registered in my database (it's called dalton) / the users are stored in a table in that database called simpleauth_players. It stores their name, hash, registerdate, logindate, and lastip.
I want to somehow use a PHP code that (logs me into the database) and displays the current amount of names in the database. So I can display a message like "Hey, there is currently 1,894 registered players!" inside of my HTML/PHP page. I'm kinda a novice it would be awesome if somebody could share the code and instructions.
My code:
$connection = mysql_connect('host', 'username', 'password');
mysql_select_db('database');
$query = "SELECT * FROM simpleauth_players";
$result = mysql_query($query);
$registered = "SELECT COUNT(*) FROM dalton.tables WHERE simpleauth_players = 'name' and TABLE_TYPE='BASE TABLE';
echo "$registered";
mysql_close();
This is the code I used to display the amount of registered players (AKA rows) in the simpleauth_players table.
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("dalton", $link);
if ($_GET['task'] == 'total') {
$get_db = 'simpleauth_players';
$result = mysql_query("SELECT * FROM $get_db", $link);
echo '{"task":"total","amount":"';
echo mysql_num_rows($result);
echo '"}';
}
?>
select count(*) as total_player from simpleauth_players
OR
$sql = "select * from simpleauth_players";
$result = mysqli_query($con,$sql);
$count = mysqli_num_rows();
echo "Total ".$count." Players";
Try this one assumed that your column name is language
SELECT COUNT(*) FROM simpleauth_players WHERE language = "PHP"
or if you want to get count by each language type you can use this
SELECT COUNT(DISTINCT user_id) AS Count,language FROM simpleauth_players GROUP BY language
As per your original post/question Since you have not provided us with the MySQL API you're using to connect with, here's an mysqli_ version, using MySQL's aggregate COUNT() function, which will count the number of given rows in a table:
$connection = mysqli_connect('host', 'username', 'password', 'database');
$result = mysqli_query($connection, "SELECT COUNT(*) as count
FROM simpleauth_players"
);
while ($row = mysqli_fetch_array($result)) {
$var = $row['count'];
echo "There are currently " .$var. " users.";
}
Edit: if using mysql_
$connection = mysql_connect('host', 'username', 'password');
if (!$connection) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('database', $connection);
if (!$db_selected) {
die ('Can\'t use database : ' . mysql_error());
}
$result = mysql_query("SELECT COUNT(*) as count
FROM simpleauth_players", $connection);
while ($row = mysql_fetch_array($result)) {
$var = $row['count'];
echo "There are currently " .$var. " users.";
}

Data fetched from mysql is displayed 2 times

I am new to php. I want to fetch a particular data from mysql and display it in the label.I have tried a simple php coding.But it displays the fetched data two times(actually I have created 2 columns such as name and age in a table called test).Please help me.Here is the coding:
displayform.php
<body>
<form method="post" name="display" action="display.php" >
Enter the name you like to display the data from MySQL:<br>
<input type="text" name="name" />
<input type="submit" name="Submit" value="display" /> </form>
</body>
</html>
display.php
<?php
mysql_connect("localhost", "root", "") or die("Connection Failed");
mysql_select_db("acp")or die("Connection Failed");
$name = $_POST['name'];
$query = "select age from test where name = '$name'";
$result = mysql_query($query);
while ($line = mysql_fetch_array($result))
{
echo $line['age'];
echo "<br>\n";
}
?>
The datas in table is
name=janani
age=25
The output is displayed as
25
25
I am certain that you have two rows bearing the same name and/or age.
In order to show only one result, what you need to do is:
Use either DISTINCT with GROUP BY, or LIMIT 1.
I.e.:
$query = "select DISTINCT age from test where name = '$name' GROUP BY name";
or
$query = "select age from test where name = '$name' LIMIT 1";
Sidenote: I suggest you use mysqli with prepared statements though, since your code is open to SQL injection.
<?php
$DB_HOST = "xxx"; // Replace
$DB_NAME = "xxx"; // with
$DB_USER = "xxx"; // your
$DB_PASS = "xxx"; // credentials
$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
die('Connection failed [' . $conn->connect_error . ']');
}
if($statement=$conn->prepare("select age from test where name = ? LIMIT 1")){
// or this one
// if($statement=$conn->prepare("select distinct age from test where name = ? group by name")){
$name = "janani";
$statement-> bind_param("s", $name);
// Execute
$statement-> execute();
// Bind results
$statement-> bind_result($age);
// Fetch value
while ( $statement-> fetch() ) {
echo $age . "<br>";
}
// Close statement
$statement-> close();
}
// Close entire connection
$conn-> close();
$line = mysql_fetch_array($result) ; //remove while loop
echo $line['age'][0];
try this ans this is work for one data fetch from table .. And may possible your result show two time because $name match two times in table so it fetch two record
You are hard coding 'age' in the array reference so it will echo that element only. Loop over array by index and you will get the name also.

Categories