goodness.. it's been a quite a headache for me.
I'm trying to get variable SQL1, SQL2 and SQL3 to update different mysql tables.. but how on earth will SQL2 and SQL3's "product_id" fields, correlate with SQL1?
See 'id' in the insert sections in SQL2 and SQL3.. i'm not sure how to replace and grab this generated data into this sections without making more ugly code.
Also, if any of you have any idea how to make this easier, please help a fellow out here.. this looks pretty dirty to me.. surely there are better ways :(
// DB Settings
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Load data from XML file
$xml = simplexml_load_file("Datafeed.xml");
// Capture XML Data
foreach($xml->children() as $product) {
// Change stock wording
$stock = $product->stock;
if ($stock == 'yes') {
$stock = 'on';
} else {
$stock = 'off'; }
// Convert XML data and insert into MYSQL
$sql = "INSERT INTO testshop_products (product_id, product_name, product_type, product_price, product_status) VALUES ("echo $product->code;", "echo $product->cat;", "echo $product->price;","echo $stock;")";
$sql2 = "INSERT INTO testshop_product_details (product_id, product_color, product_image, details_status) VALUES ('id', "Generating...", "echo $product->img;","echo $stock;")";
$sql3 = "INSERT INTO testshop_spesifications (product_id, specs_meta, specs_details, specs_slug, specs_status) VALUES ('id', General, "echo $product->img;", general, "echo $stock;")";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
if ($conn->query($sql2) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
if ($conn->query($sql3) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
write store procedure and inset all records and all table it will find.
store procedure like this
CREATE PROCEDURE `addJobApplicant`(IN XMLINPUT
text, OUT vresult VARCHAR(100))
BEGIN
DECLARE iCounter INT DEFAULT 1;
DECLARE maxCount INT;
SET vcompID=ExtractValue(XMLINPUT, '/ROOT/HEADER/COMPANYID[$iCounter]');
SET vjpID=ExtractValue(XMLINPUT, '/ROOT/HEADER/JOBID[$iCounter]');
insert command here
SET vresult = 'Successfully Inserted';
end
Related
I'm trying to build a database for a bookstore with 3 tables: Book, Volume and Publication. I'm using mysqli() and the code neither works nor echoes any errors.
<?php
//connect to db
$conn = new mysqli("localhost", "root", "", "ershadbookstore");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
#new recoed: if the new record is inserted into book successfully, another new record is inserted into volume table. the same goes for volume and phblication table. at the end the total number of this volumn is editted in the rows with the same isbn.
$sql = "INSERT INTO Book (name, vnum, writer, translator, publisher, genre, format)
VALUES ('test', 'test', 'test', 'test', 'test', 'test', 'test')";
if ($conn->query($sql) === TRUE) {
$last_bid = $conn->insert_id;
$sql = "INSERT INTO Volume (isbn, bid, vnum, note, image)
VALUES ('test', 'test', 'test', 'test', 'test')";
if ($conn->query($sql) === TRUE) {
$sql = "INSERT INTO Publication (isbn, pubnum, pyear, circulation, fpyear, pnum, price, num)
VALUES ('test', 'test', 'test', 'test', 'test', 'test', 'test', 'test')";
if ($conn->query($sql) === TRUE) {
$sql= "SELECT SUM(num) FROM Publication
WHERE (isbn='test')";
if ($conn->query($sql) === TRUE) {
$totalNum=$conn->query($sql);
$sql1= "UPDATE Volume
SET (tnum = test)
WHERE (isbn= test)";
if ($conn->query($sql1) === TRUE)
{
echo "true";
}
else
{
return "Error publication table: " . $sql1 . "<br>" . $conn->error;
}
}
}
else{
return "Error publication table: " . $sql . "<br>" . $conn->error;
}
}
else {
return "Error for volume table: " . $sql . "<br>" . $conn->error;
}
}
else {
return "Error for book table: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The problem is that you are checking with === TRUE.
As PHP Manual says:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
While your error checking would work for INSERT or UPDATE queries the SELECT query will not return true. In fact checking like this for boolean values is completely unnecessary.
Remove the check for === TRUE and your code should work fine.
$sql= "SELECT SUM(num) FROM Publication
WHERE isbn='test'";
if ($conn->query($sql)) { // removed === TRUE
$sql1= "UPDATE Volume
SET tnum = 'test'
WHERE isbn= 'test'";
if ($conn->query($sql1))
{
echo "true";
}
else
{
return "Error publication table: " . $sql1 . "<br>" . $conn->error;
}
}
If you enable mysqli error reporting, you don't need any if statements, which will make your code much simpler:
$sql = "SELECT SUM(num) FROM Publication
WHERE isbn='test'";
$conn->query($sql);
$sql1 = "UPDATE Volume
SET tnum = 'test'
WHERE isbn= 'test'";
$conn->query($sql1);
echo "true";
In addition, your values in the last update queries are missing quotes.
SET (tnum = 'test')
WHERE (isbn= 'test')";
Also there is no need to execute your SELECT query twice to get the values. You should refactor your code so that the second query ($totalNum=$conn->query($sql);) is not needed.
Also remove the triple equals === you are not comparing so you don not need a comparison operator so instead use !== FALSE
Example
if ($conn->query($sql) !== FALSE)
so this is saying if its not FALSE, than its TRUE so it will continue to run.
I have an array $alert_note. I iterate through a loop and fill it up with a few strings:
$n = 0;
$alert_note = array();
$results = array();
while($row = mysqli_fetch_assoc($query)){
//some code in here populates the $results[$n] array with results from $row
$thisnote = "<b>Location alert</b><br>
Alert ID: {$results[$n]['alert-id']}<br>
Start: {$results[$n]['start-formatted']}<br>
End: {$results[$n]['end-formatted']}<br>
Radius: {$results[$n]['radius-km']} km<br>
Distance: {$results[$n]['distance-km']} km<br>
<ul>\n";
//$results[$n]['data'] is a nested array, so iterate through it:
foreach($results[$n]['data'] as $name => $data){
$thisnote .= "<li>$name: $data</li>\n";
}
$thisnote .= "</ul>";
$alert_note[$n] = $thisnote;
$n++;
}
Then I call a foreach function:
foreach($alert_note as $alert_note_contents){
error_log("Note: $alert_note_contents");
mysqli_query($dblink, "INSERT INTO `incident_events` (`incident`, `data`, `time`, `operator`) VALUES ('$incident', '$alert_note_contents', '$now', '$operator')");
}
Each string in $alert_note shows up as expected in the PHP error log, but only the last one is inserted into the MySQL table. No PHP errors are being thrown. Any ideas why this may be?
plz before foreach($alert_note as $alert_note_contents){
do this so i can get the error
var_dump($alert_note );
and do this plz so i can see if there is any error ind db
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{ die("Connection failed: " . $conn->connect_error); }
$sql = "INSERT INTO incident_events (incident, data, time, operator) VALUES ('$incident', '$alert_note_contents', '$now', '$operator')";
if ($conn->query($sql) === TRUE)
{ echo "New record created successfully"; }
else { echo "Error: " . $sql . "<br>" . $conn->error; }
$conn->close();
This is the sample csv file I'm using:
Column1,Column2,Column3
data1,data2,data3
data1,data2,data3
data1,data2,data3
data1,data2,data3
The purpose of my program is to insert this table into a php file via command line and insert the data into an SQL database. I'm using this project as a way of learning how to use MySql.
A csv file is taken and the data is then converted into an array or arrays. A database is then created and the data is supposed to be inserted into the table.
Instead of my data being inserted, I get only one row with null values.
<?php
/**
* Created by PhpStorm.
* User:
* Date: 6/16/2017
* Time: 11:32 AM
*/
$servername = "localhost";
$username = "pop-user";
$password = "pop-pw";
$database = 'popdb';
parse_str(implode('&', array_slice($argv, 1)), $_GET);
$file = array_map('str_getcsv', file($argv[1]));
// connecting to MySQL
$link = mysqli_connect($servername,$username,$password);
// check if connection completed
if ($link->connect_error) {
die("Connection failed: ". $link->connect_error);
}
//creating database
printf("Creating database...\n");
$dbcheck = mysqli_select_db($link, $database);
// if database doesn't exist, then one will be created
if (!$dbcheck) {
$sql = 'CREATE DATABASE '. $database;
if (mysqli_query($link, $sql)) {
echo "Database ". $database ." created\n";
}
else {
echo "Failed to create database:\n";
echo $link->error."\n";
}
}
printf("Creating table...");
//creating table to hold information
$sql = 'USE '. $database. ';';
printf("\r\n");
mysqli_query($link,$sql);
$sql2 = "CREATE TABLE popCensus (";
foreach ($file[0] as $rows) {
if ($rows != end($file[0]))
$sql2 .= "{$rows} varchar(33), ";
else
$sql2 .= "{$rows} varchar(33)";
}
$sql2 .= ");";
echo $sql2;
printf("\r\n");
mysqli_query($link,$sql2);
printf("Inserting data into table...\n");
$cnt = 1;
$sql3 = "";
//Not inserting data
foreach ( $file as $file[$cnt]) {
$sql3 = "INSERT INTO popcensus VALUES ( ";
foreach ($file[$cnt] as $rows) {
if ($rows != end($file[$cnt]))
$sql3 .= "{$rows} , ";
else
$sql3 .= "{$rows});";
}
printf($sql3);
printf("\n");
mysqli_query($link, $sql3);
$cnt++;
printf("cnt: ". $cnt."\n");
$sql3 = "";
}
printf("\nDone\n");
mysqli_close($link);
?>
edit: I'm able to parse the information into an arrays of arrays. the problem I'm having is trying to insert them into a table afterwards.
you need to use prepared statement inside the loop
Try checking the query for an error result inside the foreach loop.
if (false === mysqli_query($link, $sql3)) {
throw new Exception(mysqli_error($link));
}
Beyond that, you should really be using a prepare statement.
I figured out how to run Arp-scan and show the results on the page. Now I need to insert the information into a Mysql DB. I know how to insert a single record, but I struggle with how to get many records into the db. Can't seem to wrap my head around it. Here's my code
<?php
$link = mysqli_connect("localhost", "user", "password", "mydb");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
error_reporting(E_ALL);
ini_set('display_errors', '1');
$output = shell_exec("sudo arp-scan --interface=eth0 --localnet --numeric -- quiet| grep -e 80:82:87");
foreach (explode("\n", $output) as $host)
{
list($ip, $mac) = array_pad(explode("\t", $host),2,null);
echo "$ip $mac<br>";
}
// attempt insert query execution
$sql = "INSERT INTO phones (ipadd, mac) VALUES ('$ip', '$mac')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
Any help is greatly appreciated
<?php
$values = array();
foreach (explode("\n", $output) as $host)
{
list($ip, $mac) = array_pad(explode("\t", $host),2,null);
$values[] = '("'.$ip.'", "'.$mac.'")';
}
// attempt insert query execution
$sql = "INSERT INTO phones (ipadd, mac) VALUES ".implode(',', $values);
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
It will create an array of strings in following format:
("IP", "MAC")
and connect them later using a comma
("IP", "MAC"),("IP2", "MAC2")
and add into the query
I have an address table and one of the fields is an image blob. When I update a record through $POST and include an image, everything works. However if no image is included in $POST, I want to reuse the image that is already stored in the record. This is were im having problems. when I run the code below it does not update the image file. here's my code.
function UpdateRecordfromPost()
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$FirstName = test_input($_POST['fname']);
$LastName = test_input($_POST['lname']);
$Address = test_input($_POST['address']);
$Town = test_input($_POST['town']);
$Postcode = test_input($_POST['pcode']);
$Phone = test_input($_POST['phone']);
$Email = test_input($_POST['email']);
$ID = ($_POST['idname']);
}
$mysqli = new mysqli( $GLOBALS['servername'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['dbname']);
if ($mysqli->connect_error)
{
die("Connection failed: " . $mysqli->connect_error);
}
$image = GetimagefromPost(); //this function returns a image and seems to work
if ($image == "")
{
$image = Saveimaqgefile($ID);
}
$query = "UPDATE addressbook SET firstname='$FirstName',lastname='$LastName',street='$Address',town='$Town',PostCode='$Postcode',phone='$Phone',email='$Email',Photo='$image' WHERE id='$ID'";
if ($result = $mysqli->query($query))
{
echo "Updated record successfully";
}
else
{
echo "Error: " . $query . "<br>" . $mysqli->error;
}
$mysqli->close();
}
function Saveimaqgefile($file_id) {
$mysqli = new mysqli( $GLOBALS['servername'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['dbname']);
if ($mysqli->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql= "SELECT * from ".$GLOBALS['dbname']. " WHERE id=".$file_id;
$result = $mysqli->query($sql);
if ($result->num_rows > 0)
{
$row=mysqli_fetch_array($result);
}
else { $row = "";}
$mysqli->close();
return base64_encode($row['Photo']);
}
This is my first question, sorry if i've done something wrong
You'd need conditional logic.
if (image was uploaded) {
mysqli_query('... update record with new image ...;);
} else {
mysqli_query('... update record WITHOUT image data ...');
}
For most other types of (small) data, you could do it in a single query, e.g.
UPDATE ... SET field=IF($newdata = '', field, $newdata)
but your image blob is likely to be HUGE, and you don't want to repeat it twice in the same query string.