String to Integer Returning 0 - php

I am converting , through type cast , through intval() and other procedures , but what is returned from $Id (string :eg "99973132") is always 0. I will be grateful if anyone can guide me.The value that I am converting from string to int is of length 99973132(all the values are close to this) . I have crossed checked . The value returned in $Id is 99973132 but conversion results in 0
<?php
require_once('../SchemaBuilder/Dbconfig.php');
require_once('../SchemaBuilder/NativeConfiguration.php');
$servername = MYSERVERNAME;
$username = MYUSERNAME;
$password = MYPW;
$dbname = MYDBNAME;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(!file_exists($_FILES['csvdata']['tmp_name']) || !is_uploaded_file($_FILES['csvdata']['tmp_name']))
{ echo "no file";
echo "<br> No file Selected press back to try again!!<br>";
}
else
{
$content= file_get_contents($_FILES["csvdata"]["tmp_name"]);
$content= file_get_contents($_FILES["csvdata"]["tmp_name"]);
$lines = explode("\n", $content);
$i = 0;//initialize
foreach($lines as $value)
{
if($i != 0)
{
$cols[$i] = explode("\t", $value);
if(isset($cols[$i][9]))
{ $id=$cols[$i][0] +0;
$query = "INSERT INTO csvdata(Id,UserName)
VALUES(".$i.", '".$cols[$i][9]. "')" ;
if ($conn->query($query) === TRUE)
{
echo "New record created successfully".'<br>';
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error.'<br>';
}
$x++;
}
}
$i++;
}
$conn->close();
}
?>
Edit : I am loading a .tsv file , after that parsing each line by skiping first line , then exploding by \t . fetching first attribute which is in $id and converting it to integer . but its not converted and gives 0

Related

I have a problem to insert into mysql all data from inputs and foreach loop ( only one data enters mysql)

Just the last data enters mysql with this program :
<?php
$servername = "localhost";
$username = "bern...";
$password = "password";
$dbname = "base";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo $_POST["quantité"];
$a = $_POST["trekking"];
foreach ($a as $v) {
echo $v . "<br />\n";
$sql = "INSERT INTO Donnesmi (commentaire) VALUES ('$v')";
}
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Would you have a solution for this basic concern , thank you very much
the reason for your actual problem is
foreach ($a as $v) {
echo $v . "<br />\n";
$sql = "INSERT INTO Donnesmi (commentaire) VALUES ('$v')";
}
so you overwrite your $sql variable each time, and at the end of the loop you are left with the last value. but see the comments for the various issues/suggestions with this code
Edit: 5th Mar 2019
issue with your code was, since within for loop $sql always gets overwritten only the final $sql is executed.
As pointed out by #jameson2012, one optimum way to do this would be,
<?php
$servername = "localhost";
$username = "bern...";
$password = "password";
$dbname = "base";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo $_POST["quantité"];
$a = $_POST["trekking"];
$values = [];
foreach ($a as $v) {
echo $v . "<br />\n";
$values[] = "('$v')";
}
$sql = "INSERT INTO Donnesmi (commentaire) VALUES " . emplode(',', $values);
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
basically rather than running multiple insert statements, you build a one single statement and execute it.
========================================================================
Old Answer
You must execute SQL inside foreach. Refer below.
<?php
$servername = "localhost";
$username = "bern...";
$password = "password";
$dbname = "base";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo $_POST["quantité"];
$a = $_POST["trekking"];
foreach ($a as $v) {
echo $v . "<br />\n";
$sql = "INSERT INTO Donnesmi (commentaire) VALUES ('$v')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
mysqli_close($conn);
?>

Creating multiple SQL Data from For-loop

I am trying to add random x and y values to a MySQL database but strangely it only seems to ever add one value. I was looking at many of the other posts of similar issues on Stackoverflow and it just seemed they did not have query within the loop was the common issue. I do have the query in the loop and am unsure why it is still not working.
Please see my code below:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myTable";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
for ($i = 0; $i <= 100; $i++){
$x = rand(0,20);
$y = rand(0,200);
$sql = "INSERT INTO data (x, y)"
$sql .= "VALUES ($x, $y);";
//mysql_query($sql);
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
I edited your for loop to look something like this, and it worked perfectly fine for me.
for ($i = 0; $i <= 100; $i++){
$x = rand(0,20);
$y = rand(0,200);
$sql = "INSERT INTO data (x, y) VALUES ('$x', '$y')";
$result = mysqli_query($conn, $sql);
if($result)
{
echo "Successfully created record " . $i;
} else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
ob_start();
ob_flush();
flush();
usleep(001000);
ob_flush();
flush();
}
it Delay's the loop by just a little like a fifth of a second in total. The reason I have delayed the iteration is because your database might have a limit on how many queries can be sent within a time frame. It works for me let me know if it works for you.
Create the values array in the for loop, then use implode to build the query outside the loop.
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myTable";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_errno) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO data (x, y) VALUES ";
$values = [];
for ($i = 0; $i <= 100; $i++){
$x = rand(0,20);
$y = rand(0,200);
$values[] = "($x, $y)";
}
$query = $sql . implode(",", $values) . ";";
$r = $conn->query($query);
if ($r) {
echo "New records created successfully";
} else {
echo "Error: " . $query . "<br>" . $conn->connect_error;
}
$conn->close();
You are just running a single query for each loop. No need for multi query
for ($i = 0; $i <= 100; $i++){
$x = rand(0,20);
$y = rand(0,200);
$sql = "INSERT INTO data (x, y)"
$sql .= "VALUES ($x, $y);";
//mysql_query($sql);
if (mysqli_query($conn,$sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}

Undefined offset error on php when importing a CSV

I am trying to import a CSV file into my database and it is being successfully executed at the end. But, during the execution, I receive an "undefined offset" error message and when I checked the data imported, I see that there are some null records updated in the table. How can I avert importing these null cells into my database? I also would like not to see these error messages.
<?php
require_once("database.php");
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
/// Delete table contents
$dsql = "TRUNCATE TABLE User_Mirror_Tbl";
if ($conn->query($dsql) === TRUE) {
echo "Table content is truncated successfully". PHP_EOL;
} else {
echo "Error: " . $dsql . "<br>" . $conn->error;
}
//read file
$csvfile=file_get_contents("/samba/import/User_Update_Tbl.csv");
//counters:
$record_number=0;
$record_number_err=0;
$lines = explode(PHP_EOL, $csvfile);
$array = array();
foreach ($lines as $line) {
$field = str_getcsv($line);
if $field[0] != ''){
$field[1]= ( $field[1] == '' ? NULL : $field[1]);
$field[6]= ( $field[6] == '' ? NULL : $field[6]);
$field[7]= ( $field[7] == '' ? NULL : $field[7]);
$sql="INSERT INTO User_Mirror_Tbl (History_Record_ID, Employee_ID, Application_ID, User_Status, Record_Date, User_Name, User_Role, Last_Signon, UserKeyString)
VALUES
('$field[0]','$field[1]','$field[2]','$field[3]','$field[4]','$field[5]','$field[6]','$field[7]','$field[8]') ";
//insert record to database
if ($conn->query($sql) === TRUE) {
// echo "New record created successfully". PHP_EOL;
$record_number=$record_number+1;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
$record_number_err=$record_number_err+1;
}
}
}
echo $record_number.' Successful record and '.$record_number_err.' Unsuccessful record executed.';
$conn->close();
<?php
require_once("database.php");
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
/// Delete table contents
$dsql = "TRUNCATE TABLE User_Mirror_Tbl";
if ($conn->query($dsql) === TRUE) {
echo "Table content is truncated successfully". PHP_EOL;
} else {
echo "Error: " . $dsql . "<br>" . $conn->error;
}
//read file
$csvfile=file_get_contents("/samba/import/User_Update_Tbl.csv");
//counters:
$record_number=0;
$record_number_err=0;
$lines = explode(PHP_EOL, $csvfile);
$array = array();
foreach ($lines as $line) {
$field = str_getcsv($line);
if $field[0] != ''){
$field[1]= ( $field[1] == '' ? NULL : $field[1]);
$field[6]= ( $field[6] == '' ? NULL : $field[6]);
$field[7]= ( $field[7] == '' ? NULL : $field[7]);
$sql="INSERT INTO User_Mirror_Tbl (History_Record_ID, Employee_ID, Application_ID, User_Status, Record_Date, User_Name, User_Role, Last_Signon, UserKeyString)
VALUES
('$field[0]','$field[1]','$field[2]','$field[3]','$field[4]','$field[5]','$field[6]','$field[7]','$field[8]') ";
//insert record to database
if ($conn->query($sql) === TRUE) {
// echo "New record created successfully". PHP_EOL;
$record_number=$record_number+1;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
$record_number_err=$record_number_err+1;
}
}
}
echo $record_number.' Successful record and '.$record_number_err.' Unsuccessful record executed.';
$conn->close();
Sometimes you need to ignore the last line or lines of the csv. I set the number of ignore lines from the top as $start_offset and the number of lines to ignore from the bottom as $end_offset. Start with zero and increase until the offset error goes awayHere's how I do it:
$data = file_get_contents($filename);//load up csv
$data_array = explode("\n", $data);//break file into lines
$csv = array_map('str_getcsv', $data_array);//break up comma delimited
$csv_len = count($csv); //count of number of lines
$start_offset = 2;
$end_offset = 3;
for ($i=$start_offset; $i<$csv_len-$end_offset; $i++)
{
//access columns as $csv[$i][0], $csv[$i][1] etc
}

Retrieve data from a certain column and i can change the image whenever the data is different

Is it possible to retrieve data from a certain column and have a if else statement to it where i can change the image?
So basically i want to the pic to tally with the location that i retrieve with the database.
<?php
$servername = "......byethost5.com";
$username = "....";
$password = "...";
$dbname = "b...";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Location,DateTime FROM SensorDetails LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Last Seen Location: " . $row["Location"]."<br>";
$Help= $row["Location"];
if($Help=='Toilet')
{echo '<center><img src="Toilet.jpg"></center>';}
elseif($Help=='Kitchen')
{echo '<center><img src="Kitchen.jpg</center>';}
else {echo '<center><img src="BedRoom.jpg"></center>';}
}
} else {
echo "0 results";
}
$conn->close();
?>
Another solution is use the same name for 'Location' field and its current image.
<?php
$servername = "......byethost5.com";
$username = "....";
$password = "...";
$dbname = "b...";
//////////////////////////////////////////////////////
//Image folder
//put here the folder where you save images
$img_folder = './'; //current folder
/////////////////////////////////////////////////////
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Location,DateTime FROM SensorDetails LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$img_file = $img_folder . $row["Location"] . '.jpg';
//echo $img_file; //uncomment this if you wanna check img's path.
if( ! file_exists($img_file) ){//Check if the file exists
$img_file = '';
}
echo "Last Seen Location: " . $row["Location"]."<br>";
echo "<center><img src="$img_file"></center>";
}
}else {
echo "<p> 0 results </p>";
}
$conn->close();
?>
This solution is more appropriate if you're going to have more locations in the future. I supposed that you keep the images in the same folder as this script and all the images are in JPG format.
One solution is to store the Image URL (or last part) in the database as a separated column, and echo the image same you echo the field location.
Sure you can display different images for different locations .
I have considered your code and modified it a little bit .
if( $result->num_rows > 0 )
{
while( $row = $result->fetch_assoc( ) )
{
echo 'Last Seen Location: ' .$row[ 'Location' ] .'<br>';
$location = trim( $row[ 'Location' ] ); // trim to make sure no spaces on either side
switch( strtolower( $location ) )
{
case 'toilet' : $image = 'Toilet.jpg'; break;
case 'kitchen' : $image = 'Kitchen.jpg'; break;
case 'bedroom' : $image = 'BedRoom.jpg'; break;
default : $image = 'BedRoom.jpg'; // Change default image as needed
}
echo '<center><img src="' .$image .'"></center>';
}
}
else
{
echo "0 results";
}
Notes :
I have used switch instead of if .
I have used strtolower on $location before comparing .
I have renamed $Help to $location for readability .

Compare sql table with txt file line by line with table if variable dosent exsit insert it [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
<?php
function db_query()
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "single4thenight";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, alias, type, parent, ordering, published FROM iutca_jomcl_locations"; //selects locations from
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " alias" . $row["alias"]. " type: " . $row["type"]. " - parent: " . $row["parent"]. " ordering " . $row["ordering"]. "published " . $row["published"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();
}
function read_location()
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "single4thenight";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name FROM iutca_jomcl_locations"; //selects locations from
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
// echo "Location : " . $row["name"]."<br>";
$row_name = $row["name"];
echo $row_name.'<br />';
}
}
$file1 = "./location.txt";
$lines = file($file1);
foreach($lines as $line_num => $line)
{
echo $line;
}
}
My location.txt file contains this
Auburn
Birmingham
Dothan
Gadsden
Huntsville
Mobile
Montgomery
Muscle Shoals
Tuscaloosa
I would like to compare my sql database with txt file to make sure that i do not arealdy have variables inside. I do not want to put duplicates in side my sql i would like to know what is the easiest way to update my sql
You could use INSERT IGNORE INTO instead of just INSERT INTO and MySQL will then ignore duplicate entries. See the MySQL documentation for INSERT for more information. So, based on what I see in your question, your SQL would look something like:
INSERT IGNORE INTO iutca_jomcl_locations ('name') values (?)
Hope this helps! :)
First we read file content to the $content variable
$content = file('mytxt.txt')
As you posted, your file contains words separated with space (if not, skip this and make variable $words contain values you need) so we need to split content, to get each word as array item
$words = explode(" ", $content);
Finally, inserting value and checking if there is one like that existing in DB
foreach($words as $word)
{
$sql = "INSERT iutca_jomcl_locations (name)
SELECT $word
WHERE NOT EXISTS
( SELECT 1
FROM tblSoftwareTitles
WHERE name = $word
);"
$result = $conn->query($sql);
}
iutca_jomcl_locations - table name
name - column to insert (also checking for unique values using this column)
I used This Code and it Worked for me
foreach($lines as $line_num => $line)
{
$line = $line;
//echo $line;
$sql = "SELECT ordering, name FROM iutca_jomcl_locations WHERE name='$line'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
echo "Found Locations: " . $row["name"]." The ordering Number Is " . $row["ordering"]."<br>";
$ordering =$row["ordering"];
}
} else {
if($ordering >=0)
{
$count = $ordering;
//echo "0 results";
$lowerCase = strtolower($line);
$sql = "INSERT INTO iutca_jomcl_locations (name, alias , parent, published,ordering)
VALUES ('$line','$lowerCase','$parent','1','$count')";
$count = $count + 1;
if ($conn->query($sql) === TRUE) {
echo "New record created successfully <br />";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
}

Categories