Good day,
I have a problem and i dont know how to do a Counting id number instead of random numbers, please help me. Thank you.
My codes working on random id, but i want it in Counting number ID. Thanks
<?php
$hostname_conn = "localhost";
$database_conn = "user_id";
$username_conn = "root";
$password_conn = "";
$conn = mysql_pconnect($hostname_conn, $username_conn, $password_conn) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_conn,$conn);
// run an endless loop
while(1) {
$randomNumber = mt_rand(10, 100);// generate unique random number
$query = "SELECT * FROM tblrand WHERE the_number='".mysql_real_escape_string ($randomNumber)."'"; // check if it exists in database
$res =mysql_query($query,$conn);
$rowCount = mysql_num_rows($res);
$id=$randomNumber;
// if not found in the db (it is unique), then insert the unique number into data_base and break out of the loop
if($rowCount < 1) {
$con = mysql_connect ("localhost","root");
mysql_select_db("user_id", $con);
$sql = "insert into tblrand(the_number) values('".$randomNumber."')";
mysql_query ($sql,$con);
mysql_close ($con);
break;
}
}
echo "IT-FORM" .$id;
?>
CASE 1: id generated by server-side
At server side, configure mysql database to generate sequential unique id. Add a field in your
table with auto-increment
https://dev.mysql.com/doc/refman/5.7/en/example-auto-increment.html as suggested by
#Londeren
Client side just manage insert query to save data in database (not ids, just data related to ids).
Generally this solution is preferable: even if you have many clients, the database will manage all
the query methodically and efficiently.
CASE 2: id generated by client-side (not preferable, use CASE 1 if possible. Included this in
the answer because your question started from here)
You get the last id from database, generate a new one (last id + 1), and insert new id in the
database.
Client side manage select id query, generate new id, and insert query. You take the
risk that other clients generate the same id simultaneously and insert it in the database.
Supposing at server-side is everything ok, code at client-side could be this:
<?php
$hostname_conn = "localhost";
$database_conn = "user_id";
$username_conn = "root";
$password_conn = "";
$conn = mysql_pconnect($hostname_conn, $username_conn, $password_conn) or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_conn,$conn);
// run an endless loop
$count=1;
while(1) {
$query = "SELECT * FROM tblrand WHERE the_number='".mysql_real_escape_string
($count)."'"; // check if it exists in database
$res =mysql_query($query,$conn);
$rowCount = mysql_num_rows($res);
// if not found in the db (it is unique), then insert the unique number into data_base and break
out of the loop
if($rowCount < 1) {
$con = mysql_connect ("localhost","root");
mysql_select_db("user_id", $con);
$sql = "insert into tblrand(the_number) values('".$count."')";
mysql_query ($sql,$con);
mysql_close ($con);
$count++;
break;
}
}
echo "IT-FORM" .$count;
?>
Related
I'm creating a signup form and am onto the confirmation email part. I want to find all values associated with one other value in a database.
Ex. I get the "key" that is in the URL, then want to find all the values associated with it. In my database there are 4 columns: STR (the key), USERNAME, PASSWORD, and EMAIL. If I get STR I want to get the username, password, and email that are in the same row as the key and then insert it into another table in the same database.
verify.php:
<?php
$username = $_GET['username'];
$password = $_GET['password'];
$email = $_GET['email'];
$servername = "localhost";
$user = 'usernamelol';
$pass = 'passwordlol';
$dbname = 'vibemcform';
$str = $_GET['str'];
$conn = new mysqli($servername, $user, $pass, $dbname);
/* The variable query gets the "key" from the dont database. I want to compare that value with the other values associated with it. Ex. the variables in the same row as the key. */
$query = mysqli_query($conn, "SELECT * FROM `dont` WHERE STR='".$key."'");
/* Below is my attempt. Feel free to change whatever you want. */
$sql = "SELECT USERNAME, PASSWORD, EMAIL FROM dont";
$result = $conn->query($sql);
if (!$query) {
die('Error: ' . mysqli_error($con));
}
if (mysqli_num_rows($query) > 0) {
if ($result -> num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$sqltwo = "INSERT INTO data (USERNAME, PASSWORD, EMAIL) VALUES ($row["USERNAME"], $row["PASSWORD"], $row["EMAIL"])";
}
}
}
echo 'Successfully verified your email!'; exit;
?>
Why not simpy use the insert ... select syntax?
insert into data(username, password, email)
select username, password, email from dont where str = :key
You can run this query right ahead, and then check how many rows were affected:
If no row was affected, then it means that the select did not bring a row back: so the :key was not found in the database
If a row was affected, then the key was found and the executed row was inserted
Note that you should use parametrized queries so your code is safe from SQL injection (and more efficient as well); recommended reading How can I prevent SQL injection in PHP??
Hey I have an online database which needs to be populated with sensor values periodically. There are 7 variables(columns) coupled with a timestamp column to make each row of the table. Problem is these variables are pushed a few at a time with the rest as 0. Now I'm coding an algo which will only insert a row if all values of latest row (by timestamp) are filled completely(not 0), else it will update the latest row.
Here's my PHP code for one of the insert php files which inserts 3 variables at a time - temp, pressure and altitude.
<?php
// Prepare variables for database connection
$dbusername = "uxpertla_terr"; // enter database username, I used "arduino" in step 2.2
$dbpassword = "abc123"; // enter database password, I used "arduinotest" in step 2.2
$server = "localhost";
// Connect to your database
$dbconnect = mysqli_connect($server, $dbusername, $dbpassword);
// Prepare the SQL statement
$sdl = "SELECT * FROM uxpertla_test_db.testt ORDER BY time DESC LIMIT 1";
$snd=mysqli_query($sdl);
$row = mysqli_fetch_array($snd,MYSQLI_ASSOC);
if($row)
{
if($row['Temperature']==0||$row['Pressure']==0||$row['Humidity']==0||$row['Light']==0)
{
$sql = "UPDATE uxpertla_test_db.testt
SET temp='".$_GET["value"]."',
pressure='".$_GET["value2"]."',
altitude='".$_GET["value3"]."'
WHERE time=".strtotime($row['time'])."";
}
else
$sql = "INSERT INTO uxpertla_test_db.testt
(temp,pressure,altitude) VALUES('".$_GET["value"]."', '".$_GET["value2"]."','".$_GET["value3"]."')";
}
else
$sql = "INSERT INTO uxpertla_test_db.testt
(temp,pressure,altitude) VALUES('".$_GET["value"]."', '".$_GET["value2"]."','".$_GET["value3"]."')";
// Execute SQL statement
mysqli_query($sql);
?>
Sorry if the code's not pretty, but I need help with the where clause of update query in the second if block..
Figured out the answer.. :p
<?php
// Prepare variables for database connection
$dbusername = "uxpertla_terr"; // enter database username, I used "arduino" in step 2.2
$dbpassword = "abc123"; // enter database password, I used "arduinotest" in step 2.2
$server = "localhost";
// Connect to your database
$dbconnect = mysqli_connect($server, $dbusername, $dbpassword);
$sdl = "SELECT * FROM uxpertla_test_db.testt ORDER BY time DESC LIMIT 1";
$snd=mysqli_query($dbconnect,$sdl);
$row = mysqli_fetch_array($snd,MYSQLI_ASSOC);
if($row['Temperature']==0||$row['Pressure']==0||$row['Humidity']==0||$row['Light']==0)
{
$sql = "UPDATE uxpertla_test_db.testt
SET temp='".$_GET["value"]."',
pressure='".$_GET["value2"]."',
altitude='".$_GET["value3"]."'
ORDER BY time DESC LIMIT 1";
}
else
$sql = "INSERT INTO uxpertla_test_db.testt
(temp,pressure,altitude) VALUES('".$_GET["value"]."', '".$_GET["value2"]."','".$_GET["value3"]."')";
// Execute SQL statement
mysqli_query($dbconnect,$sql);
?>
I am new in PHP .. I need help to make a PHP code to update data in MySQL if data exists and if don't already exists then insert data in MySQL.. I have made the PHP code to do this but it's inserting data when data already exists.. in MySQL.. Please help
$con = mysql_connect('localhost','root','root');
$db = mysql_select_db('gamingtracker',$con);
$query = "SELECT * FROM servers WHERE sgame='$game_insert'";
$result = mysql_query($query, $con);
While($row = mysql_fetch_array($result)) {
$id = #$row['id'];
$sname = #$row['sname'];
$sgame = #$row['sgame'];
$minplayers = #$row['minplayers'];
$maxplayers = #$row['maxplayers'];
$ip = #$row['ip'];
$port = #$row['port'];
$map = #$row['map'];
}
$sname1= html_entity_decode("{$server['s']['name']}");
if(#$sname=="{$server['s']['name']}"
AND #$sgame=="{$server['s']['game']}"
AND #$minplayers=="{$server['s']['players']}"
AND #$maxplayers=="{$server['s']['playersmax']}"
AND #$ip=="{$server['b']['ip']}"
AND #$port=="{$server['b']['c_port']}"
AND #$map=="{$server['s']['map']}" )
{
$query1 = "UPDATE servers
SET sname='$sname1', sgame='{$server['s']['game']}', minplayers='{$server['s']['players']}', maxplayers='{$server['s']['playersmax']}', ip='{$server['b']['ip']}', port='{$server['b']['port']}', map='{$server['s']['map']}'
WHERE ip='{$server['b']['ip']}', port='{$server['b']['port']}', sgame='{$server['s']['game']}'";
$result1 = mysql_query($query1, $con);
}
else {
$query1 = "INSERT INTO servers (id,sname,sgame,maxplayers,minplayers,ip,port,map) VALUES ('','$sname1','{$server['s']['game']}','{$server['s']['players']}','{$server['s']['playersmax']}','{$server['b']['ip']}','{$server['b']['c_port']}','{$server['s']['map']}')";
$result1 = mysql_query($query1, $con);
}
So you only want one entry per unique combination of ip, port, and sgame? The most straightforward way would be to let mysql handle this.
First, create a unique index on the table for those fields. Run the following in mysql:
CREATE UNIQUE INDEX ip_port_sgame ON servers (ip, port, sgame);
Then, instead of running an INSERT query, use REPLACE. So just change this one line in your php:
UPDATE servers
to
REPLACE INTO servers
So I am trying to download JSON into an iOS application and I don't really know a lot about PHP.
Currently I'm using a generic php scrip as a delegate that connects the the MySQL database and returns JSON results.
<?php
$host = "localhost"; //database host server
$db = "***"; //database name
$user = "root"; //database user
$pass = "root"; //password
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//Attempt to select the database
$dbconnect = mysql_select_db("***", $connection);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM table";
$resultset = mysql_query($query, $connection);
$records = array();
//Loop through all our records and add them to our array
while($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
The issue with this is that I don't want to encode the entire table in JSON I just want to return a few select data fields from the particular table so I don't download unnecessary data.
I know that you do this in the SELECT query but something is wrong with my syntax for this.
I had been trying with:
$query = "SELECT *[datafield],[otherdatafield],... FROM table";
but that doesnt seem to be working.
Also, In that table there are two separate data fields that are used to build a URL for an image, and Im not sure how to combine the two here so that they are returned in the JSON as one field.
For example: I Have a base string
"http://wwww.mysite.com/"
and i would like the add the two data Fields to that string so that when it returns the JSON objects they have those fields already concatenated so that the app can just use that URL:
"http://wwww.mysite.com/[data field1]/[datafield2]"
The query you should be trying looks like
$query = "SELECT col1,col2 FROM table";// no need of asterisk if you mention col names
Now if you need to combine two columns there itself in the query, try something like
$query = "SELECT CONCAT('mysite.com/',col1,'/',col2) FROM table";
"/" is the separator between two columns.
The query to fetch individual cols is
select col1,col2,col3 from table_name
No need to provide * like you did
$query = "SELECT *[datafield],[otherdatafield],... FROM table";
^........here * is causing the problem.
I have two identical tables in my database. I'm trying to ask the user the package number, then when the user clicks a button, it will copy the row matching the user input to another table.
My tables are:
awb - where the original data is.
temp - table to insert the data into.
Here's my code:
$dbhost = "localhost";
$dbuser = "root";
$dbname = "outbound";
mysql_connect($dbhost, $dbuser);
mysql_select_db($dbname) or die(mysql_error());
$packNO = $_GET['packNO'];
// Escape User Input to help prevent SQL Injection
$packNO = mysql_real_escape_string($packNO);
//build query
$query_add="INSERT INTO temp FROM awb WHERE packNO = '$packNO'";
#mysql_query($query_add);
$query = "SELECT * FROM temp";
$qry_result = mysql_query($query) or die(mysql_error());
The code that follows outputs the content of the temp table. But when I print it, I get nothing.
Why is the temp table empty when I print its values?
Try something like this
$query_add="INSERT INTO temp SELECT * FROM awb WHERE packNO = '$packNO'";
Documentation
Similar query, but not using *
$query_add="INSERT INTO temp (packNO, name)
SELECT packNO, name
FROM `awb`
WHERE `packNO` = '$packNO'";