PHP Variable variables when saving to database - php

I have a save.php page that is being called using Ajax, it contains the following elements:
$q1 = $_POST["q1"];
$q2 = $_POST["q2"];
$q3 = $_POST["q3"];
$q4 = $_POST["q4"];
$q5 = $_POST["q5"];
$proc = mysqli_prepare($link, "INSERT INTO tresults
(respondent_id, ip, browser, company, q1, q2, q3, q4, q5)
VALUES (?, ?, ?, ?, ?, ?, ?, ?);");
mysqli_stmt_bind_param($proc, "issiiiii",
$respondent_id, $ip, $browser, $company,
$q1, $q2, $q3, $q4, $q5);
At the moment, the save.php page is manually coded but I am sure there must be a way of using variable variables to automate this page to a degree, especially when the number of fields exceeds 100 that I am saving to the database.
I am, however, having trouble getting my head around using variable variables and could use some guidance.
I am have, to no avail, tried the following:
for ($i = 1; $i <= 5; $i++) {
echo '$q.$i = $_POST["q".$i];';
}
and also
for ($i = 1; $i <= 5; $i++) {
$q.$i = $_POST["q".$i];
}
Any and all advice welcomed.
Thanks.

You can use:
${'q'.$i} = $_POST['q'.$i];
Also:
for ($i = 1; $i <= 5; $i++) {
echo '$q.$i = $_POST["q".$i];';
}
should be:
for ($i = 1; $i <= 5; $i++) {
echo "$q.$i = $_POST['q'.$i];";
// ^ ^
}
otherwise variables won't be interpolated within the string.

Wrap them in {} like
for ($i = 1; $i <= 5; $i++) {
${'q'.$i}=$_POST['q'.$i];
}
Please got through this once for reference http://www.php.net/manual/en/language.variables.variable.php

Related

From PHP to MySQL bind_param() bool error

I cannot fint the error nor could find ideas from the internet.
The database has key, userIP, and date.
the code segment is:
$last = $conn->query("SELECT LAST_INSERT_ID();");
if (strcmp($last, "<empty string>") == 0) {
$index = 0;
} else {
$index = $last + 1;
}
$stmt = $conn->prepare("INSERT INTO Users (key, userIP, date) VALUES (?, ?, ?)");
$stmt->bind_param("iss", $key, $ip, $date);
$key = $index;
$ip = $_SERVER['REMOTE_ADDR'];
$date = date('Y-m-d H:i:s');
The idea is that I save the last "key" and add 1 to it. Tho it doesn't seems to work if the db is empty. I was looking over it for hours so I have ran out on ideas.
You need to fetch the results of the query.
$result = $conn->query("SELECT LAST_INSERT_ID();");
$row = $result->fetch_row();
$last = $row[0];
if ($last == "") {
$index = 0;
} else {
$index = $last + 1;
}
But you don't need to perform a query for this, there's a built-in function for it:
$last = $conn->insert_id;
Another problem is that key is a reserved word, so you need to quote it with backticks.
$stmt = $conn->prepare("INSERT INTO Users (`key`, userIP, date) VALUES (?, ?, ?)");

How can I insert data into two or more tables at once in PHP and MySQL?

I am trying to instert data from an html form using php into mysql database. Only one table(customer table) is being inserted and not package table as well.Am asking for help on how I could insert into both tables at once. Here is the code...Please help
<?php
include "includes/connection.php";
//Customer Table
$firstName = $_POST['inputFirstName'];
$lastName = $_POST['inputLastName'];
$gender = $_POST['inputGender'];
$address = $_POST['inputAddress'];
$mobileNumber = $_POST['inputMobilePhone'];
$workAddress = $_POST['inputAddress'];
$age = $_POST['inputAge'];
//Package Information
$PackageName = $_POST['inputPackageName'];
$PackageWeight = $_POST['inputPackageWeight'];
$PackagePrice = $_POST['inputPackagePrice'];
$DepartureDestination = $_POST['inputDepartureDestination'];
$finalDestination = $_POST['inputFinalDestination'];
//$DeliveryOption = $_POST['inputDeliveryOption'];
//Receiver Information
$receiverFirstName = $_POST['inputReceiverFirstName'];
$receiverLastName = $_POST['inputReceiverLastName'];
$receiverAddress = $_POST['inputReceiverAddress'];
$receiverPhone = $_POST['inputReceiverPhone'];
if(!$_POST['submit']) {
echo "Please fill out the form";
header ('Location: user.php');
}
else {
$sql = "INSERT INTO cus_sender (SenderID,StaffID,SenderFirstName,SennderLastName,Address,Phone,SEX,Age,Time)
VALUES (NULL,NULL,:firstName,:lastName,:address,:mobileNumber,:gender,:age,'')";
$sql2= "INSERT INTO package(PID,SenderID,StaffID,PackageName,PackageWeight,Price,DepartureTown,DeliveryTown,DeliveryMethod)
VALUES (NULL,NULL,NULL,:PackageName,:PackageWeight,:PackagePrice,:DepartureDestination,:finalDestination)"; //Add delivery option
$q = $db->prepare($sql);
$q->execute(array(':firstName'=>$firstName,
':lastName'=>$lastName,
':address'=>$address,
':mobileNumber'=>$mobileNumber,
':gender'=>$gender,
':age'=>$age));
$q2 = $db->prepare($sql2);
$q2->execute(array(':PackagePrice'=>$PackageName,
':PackageWeight'=>$PackageWeight,
':PackagePrice'=>$PackagePrice,
':DepartureDestination'=>$DepartureDestination,
':finalDestination'=>$finalDestination));
//':DeliveryOption'=>$DeliveryOption)); To be added later
echo "<p>Customer has been added!</p>";
header ('Location: http://localhost/BNW/newCustomer.php');
}
?>
By this way you can insert values in more than one table with single query.
<?php
$db = new mysqli('localhost', 'user', 'pass', 'test');
$start = microtime(true);
$a = 'a';
$b = 'b';
$sql = $db->prepare('INSERT INTO multi (a,b) VALUES(?, ?)');
$sql->bind_param('ss', $a, $b);
for($i = 0; $i < 10000; $i++)
{
$a = chr($i % 1);
$b = chr($i % 2);
$sql->execute();
}
$sql->close();
echo microtime(true) - $start;
$db->close();
?>

Multiple MySQL rows with one form

I have a form that I would like to create up to 9 different MySQL rows with one process. The code I have as of right now doesn't throw any errors, but also does not insert any information into the database.
$id = '';
$rid = $_POST['rid'];
$desc = $_POST['desc'];
$ename = $_POST['ename'];
if ($stmt = $mysqli->prepare("INSERT INTO event(id, rid, desc, ename) VALUES (?, ?, ?, ?)")) {
$stmt->bind_param("isss", $id, $rid, $desc, $ename);
for ($i = 1; $i < 10; $i++) {
$rid = $_POST['rid' . $i];
$desc = $_POST['desc' . $i];
$ename = $_POST['ename' . $i];
$stmt->execute();
}
include ("./html/schedule2.htm");
} else {
printf("Errormessage: %s\n", $mysqli->error);
}
I have edited the code to follow the comment instructions but still get an error that is very vague. Not sure what is going on...
The comments have pointed out that you should prepare/execute this. This is what it should look like.
$id = '';
$rid = $_POST['rid1'];
$desc = $_POST['desc1'];
$ename = $_POST['ename1'];
$stmt = $mysqli->prepare("INSERT INTO `event`(`id`, `rid`, `desc`, `ename`) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $id, $rid, $desc, $ename);
$stmt->execute();
for ($i = 2; $i < 10; $i++) {
$rid = $_POST['rid' . $i];
$desc = $_POST['desc' . $i];
$ename = $_POST['ename' . $i];
$stmt->execute();
}
Also, I'd recommend using an array for your form elements. Like:
<input type="text" name="desc[]">

Inserting values of array into MYSQL

I have a text file, who's value i have put into arrays,
this is the php code:
<?php
$homepage = file_get_contents('hourlydump.txt');
$x = explode('|', $homepage);
$desc = array();
$cat = array();
$link = array();
$m = 1;
$n = 2;
$p = 3;
for ($i = 1; $i <= count($x) / 4; $i++) {
$m = $m + 4;
$desc[] = $x[$m];
$n = $n + 4;
$cat[] = $x[$n];
$p = $p + 4;
if ($x[$p])
$link[] = $x[$p];
}
echo "<pre>";
print_r($desc);
print_r($cat);
print_r($link);
?>
output is like:
Array
(
[0] => Kamal Heer - Facebook Official Video 720p Dual Audio [Hindi + Punjabi]76 mb by rANA.mkv
[1] => 50 HD Game Wallpapers Pack- 1
)
Array
(
[0] => Movies
[1] => Other
)
Array
(
[0] => http://kickass.to/kamal-heer-facebook-official-video-720p-dual-audio-hindi-punjabi-76-mb-by-rana-mkv-t7613070.html
[1] => http://kickass.to/50-hd-game-wallpapers-pack-1-t7613071.html
)
//
//
//
anyone please help me i dont know how to insert the values of these three arrays $desc, $cat and $link
into mysql table, columns named description, category, link
i know simple insert queries but dont how to deal with these arrays.
I will give you an example of how basic database connection is made and the insert is completed, this is for illustrative purpose only. You should reorganize this code inside a class so that every insert statement doesn't create a PDO object but re-use the object created before.
function insertItem($desc, $cat, $link) {
$dbh = new PDO("mysql:host=host;dbname=db", $user, $pass);
$sql = "INSERT INTO table (description, category, link) VALUES (:desc, :cat, :link)";
$sth = $dbh->prepare($sql);
$sth->bindValue(":desc", $desc);
$sth->bindValue(":cat", $cat);
$sth->bindValue(":link", $link);
$sth->execute();
}
You can use a for statement.
for($x =0, $num = count($desc); $x < $num; $x++){
// build you query
$sql = "INSERT into your_table (description, category, link) values ".
"(".$db->quote($desc[$x]).",".$db->quote($cat[$x]).",".
$db->quote($link[$x].")";
$db->query($sql);
}
Of course you will have to use the sanitation/quoting methods appropriate for your chosen database api.
Here is a simple sample to read your file as is from the website you retrieve it as well as inserting it to the database sanitizing the data:
<?php
// fill with your data
$db_host = 'localhost';
$db_user = '';
$db_pass = '';
$db_name = '';
$db_table = 'myTable';
$file = "hourlydump.txt.gz";
if($filehandle = gzopen($file, "r"))
{
$content = gzread($filehandle, filesize($file));
gzclose($file);
}
else
die('Could not read the file: ' . $file);
$con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
if($con->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
$sql = "INSERT INTO $db_table (description, category, link) VALUES (?, ?, ?)";
if (!$insert = $con->prepare($sql))
die('Query failed: (' . $con->errno . ') ' . $con->error);
foreach (explode("\n", $content) as $line)
{
list($md5hash,$desc,$cat,$link,$torrent) = explode("|", $line);
if (!$insert->bind_param('sss',$desc,$cat,$link))
echo 'Binding parameters failed: (', $insert->errno, ') ', $insert->error;
if (!$insert->execute())
echo 'Insert Error ', $insert->error;
}
$insert->close();
$con->close();
NOTE: you may want to check if the file was loaded with success, if the fields from the explode exist or not to prevent further problems but in general this should work just fine.
Also you may want to change the $sql to reflect your MySQL table aswell as the $db_table at the top.
UPDATE: to insert all values change this:
$sql = "INSERT INTO $db_table (description, category, link) VALUES (?, ?, ?)";
To:
$sql = "INSERT INTO $db_table (md5, description, category, link, torrent) VALUES (?, ?, ?, ? ,?)";
And this:
if (!$insert->bind_param('sss',$desc,$cat,$link))
To:
if (!$insert->bind_param('sssss',$md5hash,$desc,$cat,$link,$torrent))
Note above the s for each item you need a s you have 5 items so 5 s's the S means string, D double, I integer, B blob you can read more at about it here.
Also note the $sql for each item we will use on the bind_param we have a ?.
Try this. I am assuming that only these much of values are there for insertion
for($i = 0;$i<2;$++) {
mysqli_query("INSER INTO tablename values(description,category,link) VALUES('$desc[$i]'
,'$cat[$i]','$link[$i]')");
}
You can build your query while you're doing you calculations:
$query = "INSERT INTO `table` (`description`, `category`, `link`) VALUES ";
for ($i = 1; $i <= count($x) / 4; $i++) {
$m = $m + 4;
$query .= "('".$x[$m];
$n = $n + 4;
$query .= "','".$x[$n];
$p = $p + 4;
if ($x[$p]) $query .= "','".$x[$p]."'),";
else $query .= "',NULL),";
}
$query = substr($query, 0, -1);//get rid of last comma
mysqli_query($query);
You can also build the arrays along with the query if you need to:
$query = "INSERT INTO `table` (`description`, `category`, `link`) VALUES ";
for ($i = 1; $i <= count($x) / 4; $i++) {
$m = $m + 4;
$desc[] = $x[$m];
$query .= "('".$x[$m];
$n = $n + 4;
$cat[] = $x[$n];
$query .= "','".$x[$n];
$p = $p + 4;
if ($x[$p]){
$link[] = $x[$n];
$query .= "','".$x[$p]."'),";
} else {
$link[] = $x[$n];
else $query .= "',NULL),";
}
$query = substr($query, 0, -1);//get rid of last comma
mysqli_query($query);
make the array to a string
$description = json_encode($desc);
$category = json_encode($cat);
$link = json_encode($link);
then insert these values to database
At the time of fetching
Use json_decode to get the array again from the string

PDO bind loop index

I have some user uploaded images that can be sorted and need to save the image position. Was thinking that I could do this easy enough by just using the loop index while iterating through them. However using my $i variable to bind the 3rd param is being passed as a reference and I need the value. How do I get around this?
Here's the code:
$postId = $args['postId'];
$images = explode(",", $args['images']);
$sql = 'INSERT INTO post_image (name,postId,ordinal) VALUES ';
$part = array_fill(0, count($images), "(?, ?, ?)");
$sql .= implode(",", $part);
logit($sql);
try{
$db = DB::getInstance();
$stmt = $db->dbh->prepare($sql);
$count = count($images);
$n = 1;
for($i = 0; $i < $count; $i++){
$stmt->bindParam($n++, $images[$i]);
$stmt->bindParam($n++, $postId);
$stmt->bindParam($n++, $i);
}
$result = $stmt->execute();
if($result !== false) {
return true;
}else {
logit('Query Failed');
return false;
}
}catch(PDOException $e) {
logit($e->getMessage());
return false;
}
I fixed it by using bindValue for the third param.

Categories