Inserting data two times in foreach loop with multiple arrays - php

I have a working code
<?php
$con = mysql_connect('localhost','test','test');
mysql_select_db('test',$con);
require_once("xml2json.php");
$testXmlFile = 'myxml.xml';
$xmlStringContents = file_get_contents($testXmlFile);
$jsonContents = "";
$jsonContents = xml2json::transformXmlStringToJson($xmlStringContents);
$obj =json_decode($jsonContents);
$rows = array();
foreach($obj->rss->channel->item as $item) {
$rows[] = "('".mysql_real_escape_string($item->title)."','".mysql_real_escape_string($item->description)."')";
}
$del_horoscope = "delete from jos_horoscope";
mysql_query($del_horoscope);
$query = "INSERT INTO `jos_horoscope` (`title`,`description`) VALUES ".implode(', ',$rows);
print_r ($query);
mysql_query($query);
// Do the query - do NOT show the output of mysql_error() in a production environment!
if (!mysql_query($query)) echo 'Oh no! Something went wrong with the query: '.mysql_error();
?>
But data is inserting twice with every run of this script. I am using delete statement to delete the data first before inserting new one.Can anyone please help me solve this twice problem. Here is teh screenshot of twice Data filled .http://i.imgur.com/7IM1mOE.png?1
NEW EDIT
Here is the INSERT QUERY echo http://pastebin.com/btZ7f85a
The data is not duplicate.
Thanks in advance

This is untested, but try something like this. I changed the delete to TRUNCATE which will drop all data in the table. I also changed the way the INSERTs work rather than 1 long ass insert I changed it to multiple inserts. There shouldn't be a huge performance hit. Give it a try, let me know.
<?php
$con = mysql_connect('localhost','test','test');
mysql_select_db('test',$con);
require_once("xml2json.php");
$testXmlFile = 'myxml.xml';
$xmlStringContents = file_get_contents($testXmlFile);
$jsonContents = xml2json::transformXmlStringToJson($xmlStringContents);
$obj =json_decode($jsonContents);
$rows = array();
foreach($obj->rss->channel->item as $item)
{
$rows[] = "('".mysql_real_escape_string($item->title)."','".mysql_real_escape_string($item->description)."')";
}
// Remove Data in Table.
$truncate = mysql_query("TRUNCATE TABLE jos_horoscope");
foreach($rows as $row)
{
$query = "INSERT INTO `jos_horoscope` (`title`,`description`) VALUES $row";
$result = mysql_query($query) or die(mysql_error());
}
?>

Related

Create PHP array out of table column

I am trying to create a loop that displays each row in a table. I think I need to make an array out of the PK, but I can't figure out how to do that. Here is my code so far:
$conn = dbConnect('read');
$getData = 'SELECT * FROM table';
$allData = $conn->query($getdata);
if (!$allData) {
$error = $conn->error;
} else {
$data = $allData->fetch_assoc();
$rowId = array($data['PK']);
} while ($rowId <= count($rowId)) {
// code to be run for each row
$rowId++;
}
EDIT: Sorry my question is confusing, I'm new to PHP.
Your question is a bit confusing but I think this is what you are trying to do:
$sql = 'SELECT * FROM table';
$query = $conn->query($sql);
while ($row = $query->fetch_assoc()) {
$data[$row['PK']] = $row;
}
That would iterate over each row, creating an array and using the row's value for column PK as an associative array key.
fetch_assoc() (I assume mysqli here now) doesn't fetch all data from a result, but one row after each other. So you don't need to make an array of $row['PK'], but need to loop over the results.
$conn = dbConnect('read');
$getData = 'SELECT * FROM `table`'; // you would need backticks here, if the table really is called "table" (what you shouldn't do...)
$result = $conn->query($getData); // it's not 'allData', it is a result_set. And be carefull about Case! $getData!=$getdata
if (!$result) {
$error = $conn->error;
} else {
$cnt=0;
while($row = $result->fetch_assoc()) {
// code to be run for each row
// you can display $row['PK'] now:
echo $row['PK'];
// or add that value to something else, whatever you need
$cnt = $cnt+$row['PK'];
// or to have a new array with the values of one table-column:
$columnRows[] = $row['PK'];
}
// now you can use the created array
foreach($columnRows as $PK) {
echo $PK;
}
}

Why does Mysql query only give me the last result of a query instead of all results?

getting values
session_start();
$text = $_SESSION['text']; (it's an array with multiple values)
making the array suitable for the query
$text = array_filter($text);
$text = implode("','", $text);
$text = "'".$text."'";
run query
$sql = "SELECT id_category FROM eiofm_category_lang WHERE name IN (".$text.")";
$query = mysql_query($sql);
get query result
while($result = mysql_fetch_array($query))
{
var_dump($result);
}
EDIT
I got it working with a foreach loop but still don't know why the while loop didn't work.
This worked for me
foreach($text as $values){
$query = mysql_query("SELECT id_category FROM eiofm_category_lang WHERE link_rewrite LIKE '$values'");
while ($row = mysql_fetch_assoc($query))
{
array_push($array, $row['id_category']);
}}
But still don't know why the while loop didn't work

How can I get this php to return the entire column of an sql db

I am trying to query a db for an entire column of data, but can't seem to get back more than the first row.
What I have so far is:
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_fetch_array($medicationItemObj, MYSQLI_NUM)){
echo count($row);
}
It's not my intention to just get the number of rows, I just have that there to see how many it was returning and it kept spitting out 1.
When I run the sql at cmd line I get back the full result. 6 items from 6 individual rows. Is mysqli_fetch_array() not designed to do this?
Well, I had a hard time understanding your question but i guess you are looking for this.
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_num_rows($medicationItemObj))
{
echo $row;
}
Or
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
$i = 0;
while ($row = mysqli_fetch_array($medicationItemObj))
{
$medicationItem[] = $row[0];
$i++;
}
echo "Number of Rows: " . $i;
If you just want the number of rows i would suggest using the first method.
http://php.net/manual/en/mysqli-result.num-rows.php
You can wrote your code like below
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
while ($row = mysqli_fetch_assoc($medicationItemObj))
{
echo $row['medication'];
}
I think this you want
You could give this a try:
$results = mysqli_fetch_all($medicationItemObj, MYSQLI_NUM);
First, I would use the object oriented version of this and always use prepared statements!
//prepare SELECT statement
$medicationItemSQL=$connection->prepare("SELECT medication FROM medication");
// execute statement
$medicationItemSQL->execute();
//bind results to a variable
$medicationItemSQL->bind_result($medication);
//fetch data
$medicationItemSQL->fetch();
//close statement
$medicationItemSQL->close();
You can use mysqli_fetch_assoc() as below.
while ($row = mysqli_fetch_assoc($medicationItemObj)) {
echo $row['medication'];
}

Setting PHP variables from Database Using MYSQL

Looking to select multiple values from the database and echo with PHP. (Newbie)
For instance:
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 4
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 5
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 6
How would I set the variables.. something along the lines of this using MYSQLi for multiple variables?
$sqlStremail = "SELECT subcheckr
FROM login
WHERE username = '$u'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$variable = $row["subcheckr"];
Truly appreciate any help.
Yes. Though if your query returns multiple rows, you'll need to use:
while ($row = mysqli_fetch_assoc($result))
{
//do something here
}
you need to make a loop for , foreach or a while loop
ex
while ($row = mysqli_fetch_assoc($result))
{
}
This should do it. First you need to connect, then you build your query. If query fails display an error so you know what went wrong. Then build your data array and use it.
$db = mysql_connect("localhost", "mysql_user", "mysql_password");
$sqlStremail = "SELECT `subcheckr`
FROM `login`
WHERE `username` = '".$u."'"; //needs to be concatenated
$result = mysql_query($sqlStremail, $db);
if(!$result) {
echo "query failed:". mysql_error();
exit;
}
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data = $row;
}
echo $data['sponsor'];
echo $data['contact'];
echo $data['script'];
//etc

Insert cloned elements in just one query

I make a cloned element from the original, also increase the name value like this:
Original
name="UM"
Cloned elements
name="UM1"
name="UM2"
name="UM3"
And I need to insert the data from that cloned elements, I thought make like this:
$UM1 = $_POST['UM1'];
$DS1 = $_POST['DS1'];
$Cant1 = $_POST['Cant1'];
$FU1 = $_POST['FU1'];
$query = 'INSERT INTO TABLE
VALUES (\''.$UM1.'\',\''.$DS1.'\',\''.$Cant1.'\',\''.$FU1.'\')';
mysql_query($query) or die(mysql_error());
With every element, but is so much code, exist any way to make this diferent, something like the css selectors select[id^="UM"]?
Many Thanks.
Fiddle
Solution:
$rows = array();
$i = 1;
while (isset($_POST["UM$i"])) {
$rows[] = array($_POST["UM$i"], $_POST["DS$i"], $_POST["Cant$i"], $_POST["FU$i"]);
$i++;
}
foreach ($rows as $row) {
$query = 'INSERT INTO papeleria (id, UM, DS, Cant, FU) VALUES ("","'.$row[0].'","'.$row[1].'","'.$row[2].'","'.$row[3].'")';
mysql_query($query) or die(mysql_error());
}
You can just use a for loop
$rows = array();
$i = 1;
while (isset($_POST["UM$i"])) {
$rows[] = array($_POST["UM$i"], $_POST["DS$i"], $_POST["Cant$1"], $_POST["FU$1"]);
$i++;
}
foreach ($rows as $row) {
$query = "insert into table values ('$row[0]', '$row[1]', '$row[2]', '$row[3]')";
mysql_query($query) or die(mysql_error());
}
No there is no such method but you dont need to escape the ' .
$query = "INSERT INTO TABLE VALUES ('$UM1','$DS1','$Cant1','$FU1')";
this should work perfectly

Categories