Insert into a db data coming from a loop (while) - php

hi have a code like this
for ($i=0; $i<=count($query)+1 ; $i++)
{
$sql ="SELECT * FROM $tabella[$i] WHERE id='1'";
$result=mysql_query($sql);
$numrows=mysql_num_rows($result);
while($row = mysql_fetch_array($result))
{
$name=$row['name'];
$surname=$row['surname'];
INSERT INTO student (name,surname) Values ($name,$surname)
}
}
It insert the data only from the first table he found so only one name and one surname and not all the $name and $surname with id=1
How can I resolve it

Here is the edit to your script and possible problems I fouund:
for ($i=0; $i<=count($query)+1 ; $i++) //Why is there a +1?
{
$sql ="SELECT * FROM $tabella[$i] WHERE id='1'"; //Your issue could be here, tabella[$1]
$result=mysql_query($sql); //may not be totally there
$numrows=mysql_num_rows($result); //Try to echo your SELECT $sql query
//to check
//Why do you have $numrows? I dont see
//that being used anywhere
while($row = mysql_fetch_array($result))
{
$name=$row['name'];
$surname=$row['surname'];
INSERT INTO student (name,surname) Values ($name,$surname) //Your INSERT statement
//looks ok
//Try to use single/or double
//quotes around the values
//I like having `name`,
//`surname` around fields
}
}
Check with comments. It's recommended you use Prepared/or PDO but in most cases
websites that use straight mysql functions are older or have already been coded so there
aren't any changes of being redone; its a lot of work. This makes sense when you're starting fresh. Hope it helps.

Related

How to check if the DB already have the data or insert new data

What I want is that php check if the client IP address is the same one which in the DB if it already exists, if not to insert new data.
well, it works if the client isn't already inserted in the database, but if he already exists php is skipping the update and trying to insert it again in the database............
I don't know whats wrong with it and couldn't figure out.
Here is my code:
<?php
$corruser = $_SESSION['user_name'];
$client_ip = $_SERVER['REMOTE_ADDR'];
require_once 'connections/dbc.php';
if (!$conn) {
echo "Error connecting the database";
exit();
} else{
$GUI = "SELECT * FROM `customers` WHERE user_name='$corruser'";
$GUI_response = mysqli_query($conn, $GUI);
if (!$row = mysqli_fetch_assoc($GUI_response)) {
echo "Error while query the database";
exit();
} else{
$customer_id = $row['customer_id'];
$check = "SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='$user_name' ";
$check_response = mysqli_query($conn,$check);
$check_result = mysqli_fetch_array($check_response, MYSQLI_NUM);
if ($check_result[0] > 1) {
$update_ip = "UPDATE `users-ipdb` SET `client_ip`='$client_ip' WHERE customer_id='$customer_id' AND user_name='$corruser' ";
$update_ip_result = mysqli_query($conn, $update_ip);
if (!$update_ip_result) {
echo "ERROR UPDATING DATA BASE";
exit();
}
} else{
$insert_new = "INSERT INTO `users-ipdb`(`customer_id`, `user_name`,`client_ip`) VALUES ('$customer_id','$corruser','$client_ip')";
$insert_new_result= mysqli_query($conn, $insert_new);
if (!$insert_new_result) {
echo "Error inserting new data in the database";
exit();
}
}
}
}
?>
I think you made an error with this code :
$check = "SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='$user_name' ";
$user_name variable doesn't exist, you should replace it with $corruser
That's why the code never goes into the UPDATE
First, make sure that your condition does work as expected. If customer_id is not a number the following line:
if ($check_result[0] > 1) {
can be possibly evaluated as if(0 > 1) let you read this:
Comparing String to Integer gives strange results.
The other comments mention "UPSERTS" which are explained here https://mariadb.com/kb/en/library/insert-on-duplicate-key-update/
The basic idea is that you can do
INSERT INTO `users-ipdb`(`customer_id`, `user_name`,`client_ip`)
VALUES ('$customer_id','$corruser','$client_ip')"
ON DUPLICATE KEY UPDATE client_ip='$client_ip';
and you get rid of the all the php logic. For this to work properly customer_id and user_name must be both part of the PRIMARY KEY.
If you need to query multiple tables, you can use joins - if you use ON DUPLICATE KEY UPDATE you don't need them, but still a good thing to know - https://mariadb.com/kb/en/library/join-syntax/
Last, but not least - it is a good habit to escape any value which may come from other sources. Maybe it is not your case, but some people tend to create usernames like Joe';DROP TABLE mysql.user;SELECT ' and it will destroy your database, because your query will become
SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='Joe';DROP TABLE mysql.user;SELECT ''
So be careful.

Fetch data and display it in a table in with codeigniter

Could anyone help me fetch data from a database and view it in a table? I am new to codeigniter framework.
here is a short Code for fetching Data from an SQL-Table
First you create a Connection:
// Create connection
$db = mysqli_connect($host,$username,$password,$database)
or die('Error connecting to MySQL server.');
The Values:
$host = your host-ip or URL or localhost
$username = Your Database Username
$password = your Database Password
$database = your database's Name
Then you need to request(query) something from a Table in that Database
For Example like this:
$sql = "SELECT * FROM $table ORDER BY id DESC";
$res = mysqli_query($db, $sql) or die("Fehler:$sql");
while($row = mysqli_fetch_assoc($res))
{
}
Now this Code will get all the Data out of a Table and orders it by the ID Descending.
In that code $table stands for your Table-Name and $db is your Database Name, as PHP7 needs it by every Query.
The Results eg. ALL Data in the Table, ordered by ID is now stored in the single Variable $res. If you want you can use code to check 'if ($res = true)' in order to make sure that you actually get a result from the query and catch an exception.
The 'Method mysqli_fetch_assoc()' will now give you all the Data nice and easy.
All you have to do is use this While Loop like this:
while($row = mysqli_fetch_assoc($res))
{
$username = $row['username'];
$date= $row['date'];
}
Meaning, that every While Cycle goes through one Row of results in the order you chose to query it at.
And $row acts as an Array where the Idice, ([] text in these brackets) corresponds to the given Clumn Name in your Table
Hope i could help you out :)
And please in the future state your question a little more clear and detailed and show that you have actually worked on your Problem before asking
Spytrycer
Edit
I overread the table part :)
In order to view it in a Table you should do something like this:
echo"<table border = '1'>";
echo"<tr>";
//Do <td> and </td> for as many Columns as you have and write them between the td's
echo"<td>";
echo"Column Name";
echo"</td>";
//Then comes the Data part
$sql = "SELECT * FROM $table ORDER BY id DESC";
$res = mysqli_query($db, $sql) or die("Fehler:$sql");
while($row = mysqli_fetch_assoc($res))
{
//open new Row
echo"<tr>";
//Do this td, data, /td loop for as many Columns you have in your
Database. For a Database with id, username and Password for example:
echo"<td>";
echo"$row['id']";
echo"</td>";
echo"<td>";
echo"$row['username']";
echo"</td>";
echo"<td>";
echo"$row['password']";
echo"</td>";
echo"</tr>";
//Close row
}

SQL SELECT * returns only one row

I'm designing a website and I wrote some webpage that display the list of users.
I used to do a
$query = SELECT * FROM `table_users` WHERE `id`='.$id.'
and then increment the ID with a "while" so I can grab all the users. But it's too slow now, and it glitches when there is a gap between IDs.
So I tried something like
$query = SELECT `name` FROM `tbl_user`ORDER BY `id`
and displaying the userlist with a
while ($i < sizeof(mysql_fetch_array(mysql_query($query)))){
<code to display an user>
$i++
}
But the mysql_fetch_array only returnes one user, the first one (the one with the littliest ID). I want it to return all users in an array. How do I do ?
Try This
$query = "SELECT `name` FROM `tbl_user` ORDER BY `id`";
$user_query = mysql_query($query);
$i=1;
while ($row = mysql_fetch_array($user_query)){
echo $i." : ".$row['name']."<br>";
$i++;
}
Try it like this:
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
//$row is the row which was just gathered
}
And please, use PDO or MySQLi instead of deprecated mysql.

Problems with foreach

I have a form that posts data for 2 fields related to specific rows. The form can vary in number of rows for updating dependent on who is using it. However it is not updating any part of the table. If I take the while loop out it will only update the last row. Any suggestions on how to fix it?
foreach($_POST as $k=>$p){ ${$k}=$p; }
if (isset($_POST['Update'])) {
$result = mysql_query("SELECT id, rank FROM accounts WHERE tag='$tag'");
while ($row = mysql_fetch_assoc($result)) {
//Set Variables
$query = "UPDATE accounts SET rank=$rank WHERE id=$m_id";
mysql_query($query);
}
}
you can simply do this:
if (isset($_POST['Update'])) {
$result = mysql_query("UPDATE accounts SET rank=".$_POST['rank']." WHERE tag='".$_POST['tag']."'");
mysql_query($query);
}
better read mysql and php properly.

Multiple SELECT Statements and INSERTS in 1 file

I'm working with a file and I'm attempting to do multiple select statements one after another and insert some values. So far the insert and the select I've got working together but when attempting to get the last SELECT to work I get no value. Checking the SQL query in workbench and everything works fine. Here's the code:
$id = "SELECT idaccount FROM `animator`.`account` WHERE email = '$Email'";
$result = mysqli_query($dbc, $id) or die("Error: ".mysqli_error($dbc));
while($row = mysqli_fetch_array($result))
{
echo $row[0];
$insert_into_user = "INSERT INTO `animator`.`user` (idaccount) VALUES ('$row[0]')";
}
$select_userid = "SELECT iduser FROM `animator`.`user` WHERE iduser = '$row[0]'";
$results = mysqli_query($dbc, $select_userid) or die("Error: ".mysqli_error($dbc));
while($rows = mysqli_fetch_array($results))
{
echo $rows[0];
}
I do not want to use $mysqli->multi_query because of previous problems I ran into. Any suggestions? And yes I know the naming conventions are close naming... They will be changed shortly.
Your code makes no sense. You repeatedly build/re-build the $insert_int-User query, and then NEVER actually execute the query. The $select_userid query will use only the LAST retrieved $row[0] value from the first query. Since that last "row" will be a boolean FALSE to signify that no more data is available $row[0] will actually be trying to de-reference that boolean FALSE as an array.
Since you're effectively only doing 2 select queries (or at least trying to), why not re-write as a single two-value joined query?
SELECT iduser, idaccount
FROM account
LEFT JOIN user ON user.iduser=account.idaccount
WHERE email='$Email';
I'm not sure what you're trying to do in your code exactly but that a look at this...
// create select statement to get all accounts where email=$Email from animator.account
$id_query = "SELECT idaccount FROM animator.account WHERE email = '$Email'";
echo $id_query."\n";
// run select statement for email=$mail
$select_results = mysqli_query($dbc, $id_query) or die("Error: ".mysqli_error($dbc));
// if we got some rows back from the database...
if ($select_results!==false)
{
$row_count = 0;
// loop through all results
while($row = mysqli_fetch_array($result))
{
$idaccount = $row[0];
echo "\n\n-- Row #$row_count --------------------------------------------\n";
echo $idaccount."\n";
// create insert statement for this idaccount
$insert_into_user = "INSERT INTO animator.user (idaccount) VALUES ('$idaccount')";
echo $insert_into_user."\n";
// run insert statement for this idaccount
$insert_results = mysqli_query($dbc, $insert_into_user) or die("Error: ".mysqli_error($dbc));
// if our insert statement worked...
if ($insert_results!==false)
{
// Returns the auto generated id used in the last query
$last_inisert_id = mysqli_insert_id($dbc);
echo $last_inisert_id."\n";
}
else
{
echo "insert statement did not work.\n";
}
$row_count++;
}
}
// we didn't get any rows back from the DB for email=$Email
else
{
echo "select query returned no results...? \n";
}

Categories