PHP - Insert SQL on while loop - php

I generated a random monster team from a table, and limited by 6. Now, I also want to insert the team into user_team which contains the fields
m1,m2,m3,m4,m5,m6
Those represent Monster 1 to Monster 6. Now when I try to insert the generated monsters into the team, only the last Monster seems to be inserting into it while I all of my monsters to be inserted.
http://prntscr.com/8zrj2
$sql = "SELECT * from monsterdata ORDER BY RAND() LIMIT 6";
$result = mysql_query($sql);
// this checks if you have a result
if ($result == null) echo "No result";
else {
while (($row = mysql_fetch_array($result)) != false) {
$row = mysql_fetch_array($result);
{
// html code here
}
}
the Insert statement is
$monster = $row['id'];
$sql = "INSERT into user_team(m1,m2,m3,m4,m5,m6) VALUES('$monster','$monster','$monster','$monster','$monster','$monster')";
$result = mysql_query($sql);
Just don't know where/how to place it so it inserts the right values into the right columns.

If it were me, I would push the ids into an array and then use that like so:
$monsterIds = array();
while(($row = mysql_fetch_array($result)) !== false) {
$monsterIds[] = $row['id'];
}
mysql_query("INSERT INTO user_team (m1, m2, m3, m4, m5, m6) VALUES ('{$monsterIds[0]}', '{$monsterIds[2]}', '{$monsterIds[3]}', '{$monsterIds[4]}', '{$monsterIds[5]}')") or die(mysql_error());
Also, don't forget to use the triple equals when comparing row results so that you don't get caught by a weird bug where things evaluate to false that aren't actually false (=== is the way to go with many functions which might return either an array, integer, or a boolean depending on the outcome).
The values will be placed in the columns in the order they are supplied.

Here is my example using PDO (php library):
$DBH = new PDO("mysql:host=$db_host;dbname=$db_name", $username, $password);
$webContractList=$DBH->query('SELECT id,nume,data FROM user2')->fetchAll();
$STH=$DBH->prepare("INSERT INTO user (id,nume,data) VALUES (:id ,:nume , :data)");
foreach ($webContractList as $item){
$STH->execute(array(':id'=>$item['id'],
':nume'=>$item['nume'],
':data'=>date('Y-m-d',strtotime($item['data']))));
}

Related

Problem with creating a function that checks for two variables and updates another variable

My variables in the mysql table are "usersEmail" "usersRefer and "usersPoint". I want to check the whole table if usersEmail = usersRefer on different rows then UPDATE the integer usersPoint on the row of both usersEmail and usersRefer. I want to check for one specific user, that is the value of the usersRefer checks the entire column of usersEmail to check if it matches.
Here's something that I tried out:
$sql = "SELECT * FROM walitlist";
if($result = $conn->query($sql)){
while ($row = $result->fetch_assoc()){
$pointSys = $row ["usersPoint"];
if ($row ["usersEmail"] = $row ["usersRefer"]){
$pointSys = "UPDATE waitlist SET usersPoint = usersPoint+100";
}
}
}
How can I make this work?

Returning a value 0 from a database row in PHP/MySQL after a query

I am trying to create a page where I can get the record values of a Database. My query is like this:
So I need to get the number of the values 1 on status (as count) from the tableexample if they exist and count them, if they do not exist, I need to get the value as 0 from it. To get the values I use this code and it works great, but I cannot seem to have the value return 0 on my PHP code if no results are found. I am a bit lost.
$user = $_SESSION["user"];
$systems = mysqli_connect("localhost", "root", "", "testdatabase");
$query = "SELECT SUM(count) AS value_sum FROM tableexample WHERE user = '$user' AND status = '1'";
$request = mysqli_query($systems, $query);
if (mysqli_num_rows($request) > 0) {
while ($row = mysqli_fetch_array($request)) {
echo '' . $row["value_sum"] . '';
}
} else {
echo '0';
}
So this code gets the values without any issue, but when I place "else" it should give me value 0 but does not give me anything.
Any idea on how I can solve this without changing my code so far as much?
Using PDO would it be something like this:
$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$pdo = new PDO($dsn, "username", "password", [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$stmt = $pdo->prepare('
SELECT SUM(count)
FROM `table_example`
WHERE `user` = :user
AND `status` = "1"'
);
$stmt->bindParam(':user', $_SESSION["user"], PDO::PARAM_STR);
$stmt->execute();
$sum = $stmt->fetchColumn();
echo $sum;
You don't need to write any loop or previous check in order to get the SUM value.
You are doing a SUM query which will always have a result row.
SELECT SUM(count) AS value_sum FROM tableexample WHERE user = '$user' AND status = '1'
You might want to check the SUM(count) = 0 where you can do it in your while loop
while ($row = mysqli_fetch_array($request)) {
if (!empty($row[0])) {
echo $row[0]; // sum not 0
} else {
echo '0';
}
}
Your are using mysqli_fetch_array which returns array with both numeric and associative indexes instead of just associative array. You should use mysqli_fetch_assoc or mysqli_fetch_array with 2nd parameter resulttype as mentioned in docs.
resulttype This optional parameter is a constant indicating what type of array should be produced from the current row data. The
possible values for this parameter are the constants MYSQLI_ASSOC,
MYSQLI_NUM, or MYSQLI_BOTH.
By using the MYSQLI_ASSOC constant this function will behave
identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave
identically to the mysqli_fetch_row() function. The final option
MYSQLI_BOTH will create a single array with the attributes of both.
https://www.php.net/manual/en/mysqli-result.fetch-array.php
https://www.php.net/manual/en/mysqli-result.fetch-assoc.php
As per OP's request.
Here is your code with some changes.
<?php
$user = $_SESSION["user"];
$systems = mysqli_connect("localhost", "root", "", "testdatabase");
$query = mysqli_real_escape_string($systems, "SELECT SUM(count) AS value_sum FROM tableexample WHERE user = '$user' AND status = '1'");
$request = mysqli_query($systems, $query) or die(mysqli_error($systems)); // Added die for dev env. You can choose how you want to deal with db query error.
if (mysqli_num_rows($request) > 0) {
// Just replaced mysqli_fetch_array with mysqli_fetch_assoc
while ($row = mysqli_fetch_assoc($request)) {
echo '' . $row["value_sum"] . '';
}
} else {
echo '0';
}
Also, as you are getting 0 it seems that your if (mysqli_num_rows($request) > 0) is not returning true. Might be due to some error in db query, you may want to check that again.
Edit 04-04-2020:
Updated info about indexes of returned array by mysqli_fetch_array.
Added mysqli_real_escape_string for $query.

Which is the Fastest method to check Rows existence while fetching?

From the following Queries, Which one is the most optimal and fastest to use?
[COUNT(id)]
$SQL = "SELECT name, COUNT(id) as Count FROM names WHERE name = :name";
$row = $stmt->fetch();
if ($data['count'] > 0) {
while ($row) {
$name = $row['name'];
}
} else {
return;
}
OR [rowCount()]
$SQL = "SELECT name FROM names WHERE name = :name";
if ($stmt->rowCount() > 0) {
while ($row = $stmt->fetch()) {
$name = $row['name'];
}
} else {
return;
}
OR [EXISTS]
$SQLEX = "SELECT EXISTS (SELECT name FROM names WHERE name = :name LIMIT 1)";
if ($stmt->fetchColumn == 1) {
$SQL = "SELECT name FROM names WHERE name = :name";
while (row = $stmt->fetch()){
$name = $row['name'];
}
} else {
return;
}
OR [RAW]
$SQL = "SELECT name FROM names WHERE name = :name";
$row = $stmt->fetch();
if ($row) {
while($row) {
$name = $row['name'];
}
} else {
return;
}
Also i wanted to know, Why does using $stmt->fetch() with $stmt->rowCount() allows me to fetch data, But using it with $stmt->fetchColumn doesn't?
First, if you have an index on names(name), then all should be quite comparable in speed.
Second, it is always worth trying such performance tests on your own system.
Third, if names are declared as unique (or primary key) in the names table, then all should be quite fast.
In general, though, the fastest way to determine if a row is available is:
SELECT EXISTS (SELECT name FROM names WHERE name = :name)
The LIMIT 1 in the subquery is unnecessary -- EXISTS stops at the first row (whether the database uses an index or a table scan).
In general, the first method using an aggregation is the worst solution. Without an index, it is going to result in a full table scan that reads the entire table. The second might or might not read the entire table, depending on whether the database starts returning matching rows as they are available. It also has the downside of returning more data.
Ok, it seems this question needs more than one answer...
f you need to check the existence only,
if there is an unique index for the field, all methods are equal, but some of them just make no sense.
if there is no unique index, then go for EXISTS
If you need to fetch the actual data and see if there was anything returned, then just select your data and fetch it:
if only one column from a single row is expected, then use fetchColumn()
if only one row is expected, then use fetch()
if multiple rows are expected, then use fetchAll()
and then use the resulting value to see whether your query returned any data.
So if you finally made your mind as to what you're asking about, here is the most optimal code for you:
$SQL = "SELECT name FROM names WHERE name = :name";
$data = $stmt->fetchAll(PDO::FETCH_COLUMN);
if (!$data) {
return;
}
foreach ($data as $name) ...
And there is nothing wrong with fetchColumn() other than your idea to use it.

Nest while statements while retaining values from parent PHP mysql

Update 2013/12/23
In other words, I have two tables within one database.
If a category exists in one table (e.g.: 43 in featured table) and also exists in another table (43 in category table) then match category ID relevant to the name and if true do something (e.g.: echo).
As far as I can tell nesting an if statement within an if statement that perform two separate MySQL queries doesn't allow me to keep the values of the parent if statement.
I need to somehow store the parent values from the MySQL value so they can be retrieved within the child if statement.
------------------------------
If the category ID in my category_description table exists in another table called sales_promotion then I want to execute another PHP statement.
After doing some research my code so far looks like this
$con = mysql_connect(DB_HOSTNAME,DB_USERNAME,DB_PASSWORD);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
foreach ($breadcrumbs as $breadcrumb) {
$db_selected = mysql_select_db(DB_USERNAME,$con);
$sql = "SELECT * FROM `sales_promotion` LIMIT 0, 30";
$result = mysql_query($sql,$con);
$sql_categories = "SELECT * FROM `category_description` LIMIT 0, 30";
$result_categories = mysql_query($sql_categories,$con);
$test = mysql_fetch_array($result);
while($row = mysql_fetch_array($result_categories))
{
if (strpos($row['name'],$breadcrumb['text']) !== false) {
echo('<p>Category '.$row['name'].' contains '.$row['category_id'].'</p>');
$category_id = $row['category_id'];
while($row = mysql_fetch_array($result))
{
if (strpos($row['options'],$row['category_id']) !== false) {
echo('<p>Category '.$row['name'].' contains '.$category_id.'</p>');
}
}
}
}
}
mysql_close($con);
Could someone please explain how I can achieve this?

Multiple SELECT Statements and INSERTS in 1 file

I'm working with a file and I'm attempting to do multiple select statements one after another and insert some values. So far the insert and the select I've got working together but when attempting to get the last SELECT to work I get no value. Checking the SQL query in workbench and everything works fine. Here's the code:
$id = "SELECT idaccount FROM `animator`.`account` WHERE email = '$Email'";
$result = mysqli_query($dbc, $id) or die("Error: ".mysqli_error($dbc));
while($row = mysqli_fetch_array($result))
{
echo $row[0];
$insert_into_user = "INSERT INTO `animator`.`user` (idaccount) VALUES ('$row[0]')";
}
$select_userid = "SELECT iduser FROM `animator`.`user` WHERE iduser = '$row[0]'";
$results = mysqli_query($dbc, $select_userid) or die("Error: ".mysqli_error($dbc));
while($rows = mysqli_fetch_array($results))
{
echo $rows[0];
}
I do not want to use $mysqli->multi_query because of previous problems I ran into. Any suggestions? And yes I know the naming conventions are close naming... They will be changed shortly.
Your code makes no sense. You repeatedly build/re-build the $insert_int-User query, and then NEVER actually execute the query. The $select_userid query will use only the LAST retrieved $row[0] value from the first query. Since that last "row" will be a boolean FALSE to signify that no more data is available $row[0] will actually be trying to de-reference that boolean FALSE as an array.
Since you're effectively only doing 2 select queries (or at least trying to), why not re-write as a single two-value joined query?
SELECT iduser, idaccount
FROM account
LEFT JOIN user ON user.iduser=account.idaccount
WHERE email='$Email';
I'm not sure what you're trying to do in your code exactly but that a look at this...
// create select statement to get all accounts where email=$Email from animator.account
$id_query = "SELECT idaccount FROM animator.account WHERE email = '$Email'";
echo $id_query."\n";
// run select statement for email=$mail
$select_results = mysqli_query($dbc, $id_query) or die("Error: ".mysqli_error($dbc));
// if we got some rows back from the database...
if ($select_results!==false)
{
$row_count = 0;
// loop through all results
while($row = mysqli_fetch_array($result))
{
$idaccount = $row[0];
echo "\n\n-- Row #$row_count --------------------------------------------\n";
echo $idaccount."\n";
// create insert statement for this idaccount
$insert_into_user = "INSERT INTO animator.user (idaccount) VALUES ('$idaccount')";
echo $insert_into_user."\n";
// run insert statement for this idaccount
$insert_results = mysqli_query($dbc, $insert_into_user) or die("Error: ".mysqli_error($dbc));
// if our insert statement worked...
if ($insert_results!==false)
{
// Returns the auto generated id used in the last query
$last_inisert_id = mysqli_insert_id($dbc);
echo $last_inisert_id."\n";
}
else
{
echo "insert statement did not work.\n";
}
$row_count++;
}
}
// we didn't get any rows back from the DB for email=$Email
else
{
echo "select query returned no results...? \n";
}

Categories