multiple row saving to DB table - php

I have to save more than one row of data into database table.
I wrote this code for that. But when i run this code, two rows will be saved into two rows of db table, but every other row is same as the last row data.
i.e. that is the last row data is overwriting every other row data.
$values = array();
if (isset($_POST['sub_save'])) {
$row_count = $_POST['rowcount'];
while ($row_count > 0) {
for ($r = 1; $r <= 2; $r++) {
$val = $_POST['txt'.$row_count.$r];
$values[] = $val;
}
$row_count = $row_count - 1;
$sql = "insert into timesheet_entry (name, address) values ('$values[0]', '$values[1]')";
if (mysql_query($sql)) {
echo "inserted";
} else {
echo "fail";
}
}
}

You aren't resetting your values array inside the loop so values[0] and values[1] will always have the first to values.
if (isset($_POST['sub_save'])) {
$row_count = $_POST['rowcount'];
while ($row_count > 0) {
$values = array();
for ($r = 1; $r <= 2; $r++) {
$val = $_POST['txt'.$row_count.$r];
$values[] = $val;
}
$row_count = $row_count - 1;
$sql = "insert into timesheet_entry (name, address) values ('$values[0]', '$values[1]')";
if (mysql_query($sql)) {
echo "inserted";
} else {
echo "fail";
}
}
}
On a sidenote I would recommend looking into the PDO extension and parameterised queries as mysql_ is deprecated and the above code is vulnerable to SQL injection

You are mixing mysql and mysqli:
$conn = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db("dbname");
if (mysqli_query($sql)) {
echo "inserted";
} else {
echo "fail";
}

Related

Using multi_query doesn't give the desired output

I am trying to query two tables from a database, while using fetch_assoc() (instead of fetch_row()). The code is below and I am not getting any data from this query. I managed to query the first table, then added some code to query the second one and now I am not getting any output. Any help will be appreciated.
$mysqli = mysqli_connect($servername, $username, $password, "6dwxnmkq", 3314);
if(!$mysqli){
die('Connection failed!');
}
$sql = "SELECT IndexJedlo, Jedlo, Cena, Priloha FROM `jedalny_listok`";
$sql .= "SELECT index, polievka, cena FROM `polievky`";
$jedla = array(8);
$ceny = array(8);
$index = array(8);
$polievky = array(2);
$polievkyCeny = array(2);
$polievkyIndex = array(2);
$i = 0;
if ($mysqli->multi_query($sql)) {
do {
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_assoc()) {
if($i == 0){
array_push($jedla, $row['Jedlo']);
array_push($ceny, $row['Cena']);
array_push($index, $row['IndexJedlo']);
}else{
array_push($polievky, $row['polievka']);
array_push($polievkyCeny, $row['cena']);
array_push($polievkyIndex, $row['index']);
}
}
$result->free();
}
if ($mysqli->more_results()) {
$i = $i + 1;
}
} while ($mysqli->next_result());
}
$mysqli->close();

review system with function in variable

so basically I am trying to create a little thing where it outputs stars, based on the database saved rating integer. The problem is it does not seem to put the number I from the database, in the variable. Here is the code I used:
<?php
$productID = 100;
$con = mysqli_connect("localhost", "root", "", "example");
function connect()
{
$con = mysqli_connect("localhost", "root", "", "example");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
return $con;
}
}
function getStars($con)
{
$productID = 100;
$sql = "SELECT rating
FROM reviews
-- JOIN stockitemstockgroups USING (StockItemID)
-- JOIN stockgroups USING (StockGroupID)
WHERE reviewID = '5'
";
$result = $con->query($sql);
if ($con && ($result->num_rows > 0)) {
// output data of each row
while ($row = $result->fetch_assoc()) {
echo $row["rating"];
}
} else {
echo "error";
}
}
$value = getStars($con);
echo $value;
for ($x = 1; $x <= $value; $x++) {
echo '<div class="rating"><span>★</span></div>';
}
?>
I'm having trouble finding a duplicate, though I'm sure this is one. You aren't returning anything from your function, so $value doesn't have a value.
function getStars($con)
{
$productID = 100;
$sql = "SELECT rating FROM reviews WHERE reviewID = 5";
$result = $con->query($sql);
if ($result && ($result->num_rows > 0)) {
// output data of first row
$row = $result->fetch_assoc();
return $row["rating"];
} else {
return false;
}
}
As a general rule, never echo from a function. Also, no need for a loop over what will presumably be a single result.

Duplicate entries in SQL?

I keep getting duplicate posts in the SQL DB.
This is the code I am using to create the table and insert data into the DB..
$query = "SELECT * FROM '.$cname.' WHERE name='$itemname' and price='$price'";
$result = mysqli_query($db, $query);
$count = mysqli_num_rows($result);
if($count == 0){
//insert doesn't exist, continue
//insert sizes
$list = "";
$number = count($sizes);
$num = 0;
if($usesize == 'yes'){
$num = 1;
if($number > 0){
for($i=0; $i<$number; $i++){
if(trim($_POST["size"][$i] != '')){
if(empty($list)){
$list = $_POST["size"][$i];
}else{
$list .= ",".$_POST["size"][$i];
}
}
}
echo $list;
}
$quantitylist = "";
$quantitynumber = count($quantity);
if($quantitynumber > 0){
for($a=0; $a<$quantitynumber; $a++){
if(trim($_POST["quantity"][$a] != '')){
if(empty($quantitylist)){
$quantitylist = $_POST["quantity"][$a];
}else{
$quantitylist .= ",".$_POST["quantity"][$a];
}
}
}
echo $quantitylist;
}
}else{
$num = 0;
}
$colorlist = "";
$colornumber = count($colors);
$cnum = 0;
if($usecolors == 'yes'){
$cnum = 1;
if($colornumber > 0){
for($i=0; $i<$colornumber; $i++){
if(trim($_POST["colors"][$i] != '')){
if(empty($colorlist)){
$colorlist = $_POST["colors"][$i];
}else{
$colorlist .= ":".$_POST["colors"][$i];
}
}
}
echo $colorlist;
}
}else{
$cnum = 0;
}
$query = "INSERT INTO ".$cname." (name, description, imgpath, price, sold, usesize, usecolors) VALUES ('$itemname', '$description', '$insertloc"."$name', '$price', '0', '$num', '$cnum')";
if(mysqli_query($db, $query)){
//inserted successfully
echo "Inserted successfully!";
}else{
$uploadOk = 0;
echo mysqli_error($db);
}
$conn = mysqli_connect('localhost', 'grampmkn_gramsandpops', 'Grams123', 'grampmkn_shop_quantity');
if($conn){
$query = "CREATE TABLE `".$itemname."` (
id int NOT NULL AUTO_INCREMENT,
size varchar(500),
color varchar(500),
quantity int(100),
PRIMARY KEY(id),
UNIQUE(size)
);";
$array = explode(',', $list);
if(mysqli_query($conn, $query)){
mysqli_select_db($conn, $name);
$array = explode(',', $list);
foreach($array as $value){
$arrays = explode(':', $colorlist);
foreach($arrays as $values){
$arrays1 = explode(',', $quantitylist);
foreach($arrays1 as $values1){
$query = "INSERT INTO `".$itemname."` (size, color, quantity) VALUES ('$value', '$values', '$values1')";
if(mysqli_query($conn, $query)){
echo "Successfully inserted data into grampmkn_shop_quantity!";
}else{
echo mysqli_error($conn);
}
}
}
}
}else{
echo "Could not create table";
}
}else{
echo "Could not connect to shop quantity database!";
echo mysqli_errno($conn);
}
}else{
//insert already exists
echo "Insert already exists!";
$uploadOk = 0;
}
Image from DB.
If I remove the nested loops, then how would I get all the data in the arrays to insert into the sql database.
I am only creating the table once, I am just inserting multiple times to get all the data into the db.
Any help is appreciated.

How do I display content with PDO based on num_rows?

Apparently, the num_rows property does not work in PDO as it would with mysqli.
Normally, with mysqli, my code would look like this:
<?php
$conn = new mysqli('127.0.0.1','root','mypassword','mydbname');
if($conn->connect_errno){
die("Sorry, could not connect.");
}
$id = 1;
$qry = "SELECT * FROM customers WHERE id = ?";
$getCustomers = $conn->prepare($qry);
$getCustomers->bind_param("i",$id);
$getCustomers->execute();
$result = $getCustomers->get_result();
$count = $result->num_rows;
if($count == 0){
echo "Sorry, there are no results";
}else{
while($row = $result->fetch_object()){
echo $row->id;
echo $row->fname;
echo $row->lname;
echo $row->entry_date;
}
}
?>
How do I create the equivalent with PDO? Here is what I have tried so far:
<?php
try{
$conn = new PDO('mysql:host=127.0.0.1;dbname=mydbname','root','mypassword');
}catch(PDOException $e){
echo $e;
}
$id = 1;
$qry = $conn->prepare("SELECT * FROM customers WHERE id = :id");
$qry->execute([':id'=>$id]);
$rows = $qry->fetchAll(PDO::FETCH_OBJ);
$count = count($rows);
if($count == 0){
echo "Sorry, there are no results for your criteria";
}else{
for($i = 0; $i < $count; $i++){
echo $rows->fname;
}
}
?>
Yeah isn't PDO great ;p no need to count rows when you have already got them.
To loop over your result as you have an array.
Change:
for ($i = 0; $i < $count; $i++){
echo $rows->fname;
}
To:
for ($i = 0; $i < $count; $i++){
echo $rows[$i]->fname;
}
Or better just use a foreach.
foreach ($rows as $row) {
echo $row->fname;
}
The statement
fetchAll(PDO::FETCH_OBJ) returns an array containing all of the result set rows as described here. To get the size of the array use sizeof($count). That should give you the size of the array.
To answer your question specifically. You can use rowCount() to retrieve the number of rows in a result:
$qry = $conn->prepare("SELECT * FROM customers WHERE id = :id");
$qry->execute([':id'=>$id]);
$count = $qry->rowCount();
$rows = $qry->fetchAll(PDO::FETCH_ASSOC); //my personal preference
for($i=0; $i < $count; $i++) {
echo $rows[$i]['fname'];
}
To more closely replicate your mysqli code:
while($row = $qry->fetch(PDO::FETCH_OBJ) {
echo $row->fname;
}
Of course, you should always check $conn->errorCode() after each database execution to ensure something go sideways on you.
UPDATE:
As Lawrence points out, rowCount() does not work with MS SQL Server. An alternative in that case is to use fetchAll() and count().

Store query results in a different table in PHP/MySql

I'm using PHP/MySql and I'm trying to team users into pairs based on a skill that they have. I have an existing table for users, and an existing table for the teams.
For example, I executed a query which returned 6 members which needs to be paired up into a team.
SELECT * FROM users WHERE skill = 'Office'
users
id/name/skill
1/Bob/Office
2/Ted/Office
3/Tim/Office
4/Bill/Office
5/Shawn/Office
6/Gab/Office
These results must be then paired up, and the expected output should be:
teams
name/member
Office1/Bob
Office1/Ted
Office2/Tim
Office2/Bill
Office3/Shawn
Office3/Gab
Once 2 members are placed in a team, the team name should increment by one.
Any help will be greatly appreciated Thanks.
Edit: I tried this:
$results = mysql_query("SELECT * FROM users WHERE skill = 'Office'");
$numrows = mysql_num_rows($results); $name ="";
if($numrows!=0) {
while($row = mysql_fetch_assoc($results)) {
$name = $row['userName'];
}
}
//For incrementing the team name
$namectr=0;
for($ctr=0;$ctr<$results_num;$ctr++) {
if($ctr%2==0) {
$query = mysql_query("INSERT INTO teams VALUES ('Office$namectr','$name')");
$ctr++; if($ctr%2==1) {
$query = mysql_query("INSERT INTO teams VALUES (Office$namectr','$name')");
$namectr++;
}
}
}
why not try:
$result = mysql_query("SELECT * FROM users WHERE users.skill = 'office'");
$count = 0;
$sqlcount = 0;
$offcount = 1;
while ($source = mysql_fetch_array($result)) {
if ($count < 1) {
$office = $source['skill'] . $offcount;
$name = $source['name'];
$result[$sqlcount] = mysql_query("INSERT INTO teams ('name', 'member') VALUES ('$office', '$name')");
$sqlcount++;
} else if ($count >= 1) {
$offcount++;
$count = 0;
$office = $source['skill'] . $offcount;
$name = $source['name'];
$result[$sqlcount] = mysql_query("INSERT INTO teams ('name', 'member') VALUES ('$office', '$name')");
$sqlcount++;
} else {
echo "ERROR" . mysql_error();
}
}//end while
$sqlcount = 0;
while ($result[$sqlcount] != "") {
if ($source = $result) {
} else {
echo "ERROR! " . mysql_error();
}
}//end while
Couldn't you do your database query, then do something like the below:
$count=0;
$team=1;
$teams = array();
foreach($result as $output){
if($count % 2 == 0){
// if even number, reset count and increment position
$count=0;
$team++;
}
$teams[] = $output['skill']." ".$team." - ".$output['member'];
$count++;
}
Something like the above, but it is untested, but should work in theory.

Categories