convert | separated values into new table using PHP - php

Edit: I forgot to add the explode part that I'm having the issues with. I need the query result exploded.
I have been messing with this for a while and have a workable procedure in mysql, however I want to accomplish this as part of a larger script. I have a table filled with IDs and several columns of data with "|" separated values. How can I use or edit the below PHP to query and insert normalized results into a new table?
If I run this with an actual string: "40|180|408|360|40|166|80|59"; It will insert values (not the ID, which I also need) but when I try to pass in query results, I get "Array to string conversion" errors. Any guidance would be appreciated.
$query = "Select id, imageSize from T1";
$result = mysqli_query($conn, $query);
$myArray = explode('|', $result);
foreach($myArray as $value) {
$sql = "INSERT INTO testExplode VALUES ($value)";
$result = mysqli_query($conn, $sql);
}

If you want to insert all of your results then:
$query = "Select id, imageSize from T1";
$myArray = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($myArray)) {
$sql = "INSERT INTO testExplode VALUES (" . mysqli_real_escape_string($conn, $row['imageSize']) . ")";
mysqli_query($conn, $sql);
}
//If just only one:
$query = "Select id, imageSize from T1";
$myArray = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($myArray);
$sql = "INSERT INTO testExplode VALUES (" . mysqli_real_escape_string($conn, $row['imageSize']) . ")";
mysqli_query($conn, $sql);
NOTE:
Avoid sql injecions by escaping your variables in your querys.
EDIT:
Based on the OP comment.
$query = "Select id, imageSize from T1";
$myArray = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($myArray)) {
$values = explode('|', $row['imageSize']);
foreach ($values as $value) {
$sql = "INSERT INTO testExplode VALUES (" . mysqli_real_escape_string($conn, $value) . ")";
mysqli_query($conn, $sql);
}
}

Related

How to get result from query and insert the results in other table?

I did query to the database where I need the results from it and then store it in a variable. Then I will pass the variable to the INSERT INTO statement but for some reason my code does not work. This is my code/
$query = "SELECT * from animals where old= 1 AND user_id=".$_SESSION['user_id'];
$result = mysqli_query(mysqli_connect("","","", ""), $query);
while ($row = mysqli_fetch_array($result))
{
$variable[] = $row['number'];
}
//now I will pass the $variable to the INSERT INTO statement
if(isset($_POST['submit_d']))
{
foreach($variable as $var)
{
$query="INSERT INTO selectedanimals(number) VALUES ({$var},2)";
mysqli_query($con, $query) or die (mysql_error());
}
?>
<script>
alert("Animal added.");
self.location="chooseAnimals.php";
</script>
<?php
}
?>
You can use INSERT INTO ... SELECT for this purpose in a single query:
INSERT INTO selectedanimals (number)
SELECT number
FROM animals
WHERE old = 1 AND user_id = some_id
PHP code:
$query = "INSERT INTO selectedanimals (number) ";
$query.= "SELECT number FROM animals WHERE old = 1 AND user_id = ".$_SESSION['user_id'];
mysqli_query($con, $query) or die (mysql_error());

Getting an array to string conversion error

Can someone help me what's the problem with this code? Im trying to store the fetched data to an array and i want to based on the values of that array. Im getting an error of Array to string conversion. The datatype value of an array is string
Here's the code.
$sql3 ="SELECT DISTINCT subj_descr FROM subj_enrolled WHERE enroll_ref = '$ref'";
$results = mysqli_query($con, $sql3);
$data = array();
while($row = mysqli_fetch_array($results)){
$data[] = array($row['subj_descr']);
}
$sql ="SELECT * FROM notification WHERE subj_descr IN ({implode(',', $data})";
$result = mysqli_query($con, $sql);
$count = mysqli_num_rows($result);
Remove array inside your while loop:
$sql3 ="SELECT DISTINCT subj_descr FROM subj_enrolled WHERE enroll_ref = '$ref'";
$results = mysqli_query($con, $sql3);
$data = array();
while($row = mysqli_fetch_array($results)){
$data[] = $row['subj_descr'];
}
$sql ="SELECT * FROM notification WHERE subj_descr IN ({implode(',', $data})";
$result = mysqli_query($con, $sql);
$count = mysqli_num_rows($result);
create a new variable and implode in it.
Try this
$implodeAray = implode(",", $data);
$sql ="SELECT * FROM notification WHERE subj_descr IN ($implodeAray)";
You are creating a multidimensional array and so change this statement
$data[] = array($row['subj_descr']);
to
$data[] = $row['subj_descr'];
As SQL IN statement always used a single dimensional array so also make change in query where clause.
I have changed all, please try below code:
<?php
$sql3 ="SELECT DISTINCT subj_descr FROM subj_enrolled WHERE enroll_ref = '$ref'";
$results = mysqli_query($con, $sql3);
$data = array();
while($row = mysqli_fetch_array($results)){
$data[] = $row['subj_descr'];
}
$dataStr = implode(',', $data);
$sql ="SELECT * FROM notification WHERE subj_descr IN (".$dataStr.")";
$result = mysqli_query($con, $sql);
$count = mysqli_num_rows($result);
?>
You stored the element of your array inside another array while looping.
Do this:
$sql3 ='SELECT DISTINCT subj_descr
FROM subj_enrolled
WHERE enroll_ref = "$ref"';
$results = mysqli_query($con, $sql3);
$data = array();
while($row = mysqli_fetch_array($results)){
//Your error was here
//Each elements is escaped for security reasons
$data[] = mysqli_escape_string($con,$row['subj_descr']);
}
//This implodes and puts a single quote around each element
$dataIn= '\'' . implode( '\', \'', $data ) . '\'';
$sql ="SELECT * FROM notification
WHERE subj_descr IN ($dataIn)";
$result = mysqli_query($con, $sql);
$count = mysqli_num_rows($result);

query result array in loop for another query

I Queried Database Table 'users' for 'user_id'. and get an array of ids.
$sel = "SELECT user_id FROM users WHERE status='Approved'";
$result = #mysqli_query ($dbcon, $sel);
Then i inserted values into another table income for all those user ids.
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$ins = "INSERT INTO income (user_id, income_amount) VALUES ('$row', '100')";
$giv = #mysqli_query ($dbcon, $ins);
}
Notice: Array to string conversion in E:\xampp\htdocs\project\t.php on line 109
Can anyone help me resolve this issue.
$sel = "SELECT user_id FROM users WHERE status='Approved'";
$result = #mysqli_query ($dbcon, $sel);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$ins = "INSERT INTO income (user_id, income_amount) VALUES ('" . $row['user_id'] . "', '100')";
$giv = #mysqli_query ($dbcon, $ins);
}
First , Check if $results is in array ..you can put some error handling checked is_array($result).
If it is fine then pass it to mysqli_fetch_array().
Do't add suppress # error ,while developing.
i would like to suggest you a single query for that so after that you need not to use while loop to insert your data in income table:
Just try it :
INSERT INTO income (user_id,income_amount) SELECT user_id,'100' AS income_amount FROM users WHERE status = 'Approved';
You can use it like that way :
$sel = "INSERT INTO income (user_id,income_amount) SELECT user_id,'100' AS income_amount FROM users WHERE status = 'Approved'";
$result = #mysqli_query ($dbcon, $sel);

Sending information from a newly created record to a different MySQL table

I'm making a form that submits a story into a MySQL table called 'work'. I want to later take the id of the newly created record and put the information into a different table.
But when I submit the story, it says:
$workid is undefined.
I can't see the problem though because I believe I've defined it?
<?php
if (!empty($_POST) && !empty($_POST['title']) && !empty($_POST['story']) && !empty($_POST['genre']) && !empty($_POST['rating'])) {
$title = strip_tags($_POST['title']);
$story = strip_tags($_POST['story']);
$title = mysqli_real_escape_string($db, $title);
$story = mysqli_real_escape_string($db, $story);
$genre = $_POST['genre'];
$rating = $_POST['rating'];
$query = "SELECT COUNT(*) AS count FROM works WHERE Title = '".$title."'";
$result = $db->query($query);
$data = $result->fetch_assoc();
if ($data['count'] > 0) {
echo "<p>Story already exists!</p>";
} else {
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$query = "SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row = $result->fetch_assoc())
$workid = $row["id"]; //workid is written here but still considered undefined
}
$query = "INSERT INTO `author_work` (`author_id`) VALUES ('".$authorid."')";
$result = $db->query($query);
$query = "INSERT INTO `author_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`login_id`) VALUES ('".$userid."')";
$result = $db->query($query);
if ($result) {
echo "<p>Story submitted!</p>";
} else {
echo "SQL Error: " . $db->error;
}
}
}
?>
You never did a $db->query() on your INSERT INTO... query string, so it was never inserted, and was overwritten by your SELECT id ... query.
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$db->query($query); // Missing this $db->query()
$query="SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row= $result->fetch_assoc())
$workid = $row["id"];}
Your $workid might not be initialized, depending on your condition and the result of your SQL query: so try to avoid next operations that will causes warnings/errors by using continue or else

PHP stops at, and shows, a single line of code

Recently I copied a PHP script to use it for another database. After I correctly edited all the words and links, I got an weird error.
SELECT naam, aantal, prijs
FROM boeken, bestelling
WHERE boeken.Boekcode = bestelling.Boekcode
AND bestelling.Boekcode IN ('101','102')
AND bestelnummer = 3;
It's not a regular error that say something like
Error on line 42
Basically what the code does, is that when you order books and filled in a form (Name, last name, email etc) it puts that in a database. And afterwards puts it in a "thankyou.html" page.
Here's part of the code that causes this
mysqli_query($con, $query) or die($query . "<br>");
$bestelnummer = MYSQLI_INSERT_ID($con);
$object = array_filter($object);
$objectnaam = join("','",array_keys($object));
$object = http_build_query($object);
$object = str_replace('=', ',', $object);
$object = str_replace('&', "),($bestelnummer,", $object);
$query = "INSERT INTO bestelling (bestelnummer, Boekcode, aantal) VALUES ($bestelnummer,$object)";
$result = mysqli_query($con, $query) or die($query."<br>");
$aantal = "SELECT naam, aantal, prijs FROM boeken, bestelling WHERE boeken.Boekcode = bestelling.Boekcode AND bestelling.Boekcode IN ('".$objectnaam."') AND bestelnummer = $bestelnummer";
$result = mysqli_query($con, $aantal) or die($aantal . "<br>");
$res = mysqli_fetch_all($result);
$prijs = 0;
The $object is an array of the books you choose.
I've Google'd for this problem, and yes, I have Apache and everything enabled.
Sorry if I'm unclear, it's been a while, I can answer any questions you might have.
Well you echo out the query if it fails.
$aantal = "SELECT naam, aantal, prijs FROM boeken, bestelling WHERE boeken.Boekcode = bestelling.Boekcode AND bestelling.Boekcode IN ('".$objectnaam."') AND bestelnummer = $bestelnummer";
$result = mysqli_query($con, $aantal) or die($aantal . "<br>");
You might want to check the error message that is returned from the database using mysqli_error().
$result = mysqli_query($con, $aantal) or die(mysqli_error() . "<br>");
first need to refine
$query = "INSERT INTO bestelling (bestelnummer, Boekcode, aantal) VALUES ($bestelnummer,$object)";
you are selecting values insertion for 3 columns and passing only two values
For second query try to use backticks for tablename and column

Categories