How to insert IP address in table? - php

I'm coding an admin page where I keep track of users/visitors. I have some code so far, but I need to add ip addresses from the users/visitors to the table as well. This is my code, everything gets added to the database table except for ip address. The table is users4project and column is ip address with the int(10) UNSIGNED NOT NULL I created the table in phpmyadmin.
<?php
function visitor($record) {
// my database info
$db_host = "";
$db_username = "";
$db_password = "";
$db_name = "";
$db_table = "ipusers4project";
$counter_page = "access_page";
$counter_field = "access_counter";
$db = mysqli_connect ($db_host, $db_username, $db_password, $db_name)
or die("Host or database not accessible");
$sql_call = "INSERT INTO ".$db_table." (".$counter_page.",
".$counter_field.") VALUES ('".$record."', 1) ON DUPLICATE KEY UPDATE ".$counter_field." = ".$counter_field." + 1";
mysqli_query($db, $sql_call) or die("Error while entering");
$sql_call = "SELECT ".$counter_field. " FROM ".$db_table." WHERE ".$counter_page. " = '".$record. "'";
$sql_result = mysqli_query($db, $sql_call) or die("SQL request failed ");
$row = mysqli_fetch_assoc($sql_result);
$x = $row[$counter_field];
mysqli_close($db);
return $x;
}
?>
<?php
$ipadress = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO
ipusers4project
( ipadress )
VALUES
( '$ipadress')";
?>
EDIT: On index.php I have this code:
<?php
$page_name = "index.php";
?>
<title><?php echo $page_name; ?></title>
<?php
include "webcounter.php";
$access_number = visitor($page_name);
?>

Just add this as another column in the row that visitor() is adding.
<?php
function visitor($record) {
// my database info
$db_host = "";
$db_username = "";
$db_password = "";
$db_name = "";
$db_table = "ipusers4project";
$counter_page = "access_page";
$counter_field = "access_counter";
$ipadress = $_SERVER['REMOTE_ADDR'];
$db = mysqli_connect ($db_host, $db_username, $db_password, $db_name)
or die("Host or database not accessible");
$sql_call = "INSERT INTO ".$db_table." (".$counter_page.",
".$counter_field.", ipadress) VALUES ('".$record."', 1, '$ipadress') ON DUPLICATE KEY UPDATE ".$counter_field." = ".$counter_field." + 1, ipadress = VALUES(ipadress)";
mysqli_query($db, $sql_call) or die("Error while entering");
$sql_call = "SELECT ".$counter_field. " FROM ".$db_table." WHERE ".$counter_page. " = '".$record. "'";
$sql_result = mysqli_query($db, $sql_call) or die("SQL request failed ");
$row = mysqli_fetch_assoc($sql_result);
$x = $row[$counter_field];
mysqli_close($db);
return $x;
}
?>

Related

extracting info from database to html page error

i'm very new to PHP so i apologize if this is a simple fix but i'm experiencing a weird issue. I've created a website that uses facebook authentication. once they login, their information gets stored in a database I've created. i then created some functions that display the users facebook image and name on the profile page of my website. problem is sometimes it shows, and other times i receive this error. "notice: undefined index: fbid in /PATH/ on line 132". Here is the code.
<div id="userInfo" class="userInfo">
<h1> <?php
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName = "facebooklogin";
$conn = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT first_name, last_name, picture FROM users WHERE
oauth_uid = '".$_SESSION['fbid']."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo " ". $row["first_name"]." ". $row["last_name"]."";
}
} else {
echo "0 results";
}
$conn->close();
?></h1>
userData.php
<?php
session_start();
include 'dbConfig.php';
$userData = json_decode($_POST['userData']);
if(!empty($userData)){
$oauth_provider = $_POST['oauth_provider'];
$_SESSION['fbid'] = $userData->id;
var_dump($_SESSION);
$prevQuery = "SELECT * FROM users WHERE oauth_provider =
'".$oauth_provider."' AND oauth_uid = '".$userData->id."'";
$prevResult = $db->query($prevQuery);
if($prevResult->num_rows > 0){
$query = "UPDATE users SET first_name = '".$userData-
>first_name."', last_name = '".$userData->last_name."', email =
'".$userData->email."', gender = '".$userData->gender."', locale =
'".$userData->locale."', picture = '".$userData->picture->data->url."',
link = '".$userData->link."', modified = '".date("Y-m-d H:i:s")."'
WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid =
'".$userData->id."'";
$update = $db->query($query);
}else{
$query = "INSERT INTO users SET oauth_provider =
'".$oauth_provider."', oauth_uid = '".$userData->id."', first_name =
'".$userData->first_name."', last_name = '".$userData->last_name."',
email = '".$userData->email."', gender = '".$userData->gender."',
locale = '".$userData->locale."', picture = '".$userData->picture-
>data->url."', link = '".$userData->link."', created = '".date("Y-m-d
H:i:s")."', modified = '".date("Y-m-d H:i:s")."'";
$insert = $db->query($query);
}
}
?>
It seems that you don't have the variable set when you use it in the query.
Check it before the query, like:
if (isset($_SESSION['fbid'])) {
$sql = "SELECT first_name, last_name, picture FROM users WHERE
oauth_uid = '".$_SESSION['fbid']."'";
$result = $conn->query($sql); } else {
// not logged in
}
To check the values of $_SESSION, just do a var_dump($_SESSION) and you can see what is set.

How to put the output query from mySQL to php int variable

I want to do a query to get the last id (int) in a table to create a new row with that last id + 1 but actually this just put all rows with the same id
my code:
<?php
$servername = "localhost";
$user = "root";
$pass = "dbpass";
$dbname = "site";
$mail = $_POST['mail'];
$password = $_POST['password'];
// Create connection
$conn = mysqli_connect($servername, $user, $pass, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sqlID = "SELECT MAX(id) FROM `login`;";
if ($result = mysqli_query($conn, $sqlID)) {
$id = mysqli_fetch_row($result);
}
settype($id, "int");
$id = $id + 1;
$sql = "INSERT INTO login (`id`,`mail`,`password`)
VALUES ('".$id."','".$mail."','".$password."');";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
mysqli_fetch_row returns always an array, also if there is only 1 element. So the MAX(id) in in $row[0].
Fixing this, you also don't need to use settype.
If your id is autoincrement, change this:
$sql = "INSERT INTO login (`id`,`mail`,`password`)
VALUES ('".$id."','".$mail."','".$password."');";
to:
$sql = "INSERT INTO login (`mail`,`password`)
VALUES ('".$mail."','".$password."');";
Then get rid of all code from $sqlID to $id + 1; (for tidyness)

Trying to get property of non-object: Using SELECT

I got little problem with my code... because I try to SELECT sth from database and then INSERT some value to another table, but in normal code from w3school
and I got error
Tryingo to get property of non-object
Here is my code:
<?php
session_start();
function connectionDB(){
$host = "localhost";
$username = "root";
$password = "";
$db_name = "project";
$conn = new mysqli($host, $username, $password, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
function getID(){
$id = $_GET['id'];
return $id;
}
$login =$_SESSION['login'];
$conn =connectionDB();
$idCar = getID();
echo $idCar;
$sqluser = "SELECT ID_USER FROM login_table WHERE LOGIN = $login";
if($result->num_rows > 0)
$result = $conn->query($sqluser);
{
while($row = $result->fetch_assoc())
{
$sql = "INSERT INTO cart (id_user) VALUES ('".$row['ID_USER']."')";
}
}else echo"error";
?>
THIS IS THE CODE OF SIDE WITH PRODUCT
Please see change near your IF loop
$sqluser = "SELECT ID_USER FROM login_table WHERE LOGIN = $login";
$result = $conn->query($sqluser); //check result first
if($result->num_rows > 0) //get number of rows
{
while($row = $result->fetch_assoc())
{
$sql = "INSERT INTO cart (id_user) VALUES ('".$row['ID_USER']."')";
}
}else echo"error";

check if a value exists in my database table

I want to check if a URL exists in my MySQL database table for example if Url=exist, message=url already exist
<?php
if(isset($_POST['Submit'])){
$dbhost = 'localhost';
$dbuser = '####';
$dbpass = '#######';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$Title = $_POST['Title'];
$Url = $_POST['Url'];
$email_data = $_POST['email_data'];
$type_data = $_POST['type_data'];
$sql = "INSERT INTO table ". "(Title,Url,email_data,type_data)"."VALUES('$Title','$Url','$email_data','$type_data')";
mysql_select_db('dbname');
$retval = mysql_query( $sql, $conn );
if(! $retval ){
die('Could not enter data: ' . mysql_error());
}
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
mysql_close($conn);
} else {
?>
You can do like this
$sql = "SELECT Url FROM 'your_table_name' WHERE Url = $_POST['Url']";
Run this sql and if it is return true you can say its exist.
$query = mysql_query('select url from table-name where url=$_post['url']');
if(mysql_fetch_rows($query) != 0){
echo "URL allready Exists";
}else{
Insert Query
}
Hi, Try this code.
Its a bit hard know what you are doing by just looking at the code but if you wondering how to check if something is in the database you could do like this:
PHP:
$sql = mysql_query("SELECT * FROM dbname WHERE Url='$Url'");
if(mysql_num_rows($sql) > 0){
echo "alreday exist";
}

PHP error: Query was empty

here is the code that gives me this error. I have searched around, found related questions, but I couldn't apply the implementation. Here is something wrong and it's beyond my understanding..
function add_user_to_db()
{
$dbhost = "111.111.111.111";
$dbuser = "Bob";
$dbpass = "password";
$connection = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$connection){die('Could not connect: '.mysql_error());}
echo 'Connected to Vikings Game DB!';
mysql_select_db('vgDB');
$tb_result = mysql_query("SHOW TABLES LIKE 'Players'");
$table_exists = mysql_num_rows($tb_result) > 0;
if($table_exists)
{
if( isset($_POST["ID"]) && isset($_POST["NAME"]) && isset($_POST["COMMENT"]) )
{
$id = $_POST['ID'];
$name = $_POST["NAME"];
$comment = $_POST["COMMENT"];
//Check if a row exists
$row_result = mysql_query("SELECT `".$id."` FROM Players");
if($row_result == FALSE)
{
$add_user_query = mysql_query( "INSERT INTO Players( ID , NAME , COMMENT )VALUES('123','Bob','Bob's comment')" );
$retval = mysql_query($add_user_query, $connection);
if(!$retval) die("Could not insert data: ".mysql_error());
echo "User '".$id."' was added successfully!";
}
else
{
$name_read = mysql_query("SELECT NAME FROM Players WHERE ID = `".$id."`");
$comment_read = mysql_query("SELECT COMMENT FROM Players WHERE ID = `".$id."`");
echo "Reading data of user (`".$id."`): Name = `".$name_read."`; Comment: `".$comment_read."`";
}
}
}
mysql_close($connection);
}
I think your problem is in the following line:
$add_user_query = mysql_query( "INSERT INTO Players( ID , NAME , COMMENT )VALUES('123','Bob','Bob's comment')" );
Try modifing (just for testing purposes) as follows:
$add_user_query = mysql_query( "INSERT INTO Players( ID , NAME , COMMENT )VALUES('123','Bob','Bob comment')" );
If you get it working with this, means that 'Bob's comment' was the problem, the quote after the Bob was causing it.

Categories