Multiple SELECT Statements and INSERTS in 1 file - php

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";
}

Related

How can I use mysqli to SELECT and both DELETE and RETURN a single row based on WHERE condition

How can I do a mysqli php query so a SELECT request both RETURNS the row AND DELETES the same row in the MySQL DB?
This php script works fine to query and return a single row based on max numerical zipcode (an example) but my modifications do not complete the delete row:
<?php
echo phpversion();
// Create connection
$con = mysqli_connect("localhost", "mysqluser", "mysqlpass", "mysqldb");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Select all from designated assigned bot
$sql = "SELECT * FROM mysqltable WHERE zipsize=( SELECT max(zipsize) FROM mysqltable ) LIMIT 1;";
// Confirm there are results
if ($result = mysqli_query($con, $sql)) {
// We have results, create an array to hold the results
// and an array to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each result
while ($row = $result->fetch_object()) {
// Add each result into the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
I tried adding this line in various places to delete the row to no success using Id, which is a unique code for every row in the table (also tried with $result and $resultArray instead of $row):
$delsql= mysqli_query($conn,"DELETE FROM mysqltable WHERE Id= $row['Id']");
If you want to select the data and then immediately delete that selected data then you need to run two separate queries. I don't really know why you have so much unnecessary code there, but I would do it this way:
<?php
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli("localhost", "mysqluser", "mysqlpass", "mysqldb");
$mysqli->set_charset('utf8mb4'); // always set the charset
// Select all from designated assigned bot
$sql = 'SELECT * FROM mysqltable WHERE zipsize=( SELECT max(zipsize) FROM mysqltable ) LIMIT 1';
$resultArray = $con->query($sql)->fetch_all(MYSQLI_ASSOC);
echo json_encode($resultArray);
// now delete
$sql = 'DELETE FROM mysqltable WHERE zipsize=( SELECT max(zipsize) FROM mysqltable ) LIMIT 1';
$resultArray = $con->query($sql);
If you don't need nested arrays and you only ever fetch a single row then you can replace fetch_all(MYSQLI_ASSOC) with fetch_assoc() instead.
Careful! These queries can have unexpected results due to the possibility of selecting a different row than the one you delete unless you specify ORDER BY.
If you have a primary/unique key in the table to uniquely identify the rows you are selecting/deleting then you can store the list of ids and then execute a WHERE IN() query.
For example:
// Select all from designated assigned bot
$sql = 'SELECT * FROM mysqltable WHERE zipsize=( SELECT max(zipsize) FROM mysqltable )';
$resultArray = $con->query($sql)->fetch_all(MYSQLI_ASSOC);
echo json_encode($resultArray);
// get all ids from our array
$ids = array_column($resultArray, 'Id');
// now delete
$sql = 'DELETE FROM mysqltable WHERE Id IN('.str_repeat('?,', count($ids) - 1) . '?)';
$stmt = $con->prepare($sql);
$stmt->bind_param(str_repeat('s', count($ids)), ...$ids);
$stmt->execute();

Remote MySQL : I Can Read Database Tables Names, But Can't Read The Rows

I just create a Remote MySQL access from my other database server (remote) and I can see tables in it :
// SHOW ALL TABLES NAME
$sql = "SHOW TABLES";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_row($result)) {
echo "Table: {$row[0]} <br>" ;
}
I can also see what columns name on each tables by using this :
// SHOW COLUMNS NAME OF A TABLE
$sql = 'DESCRIBE wp_ps_product_sku';
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_row($result)) {
echo "Column: {$row[0]} <br>" ;
}
but why I can't see any rows inside each table?
$sql = 'SELECT * wp_ps_product_sku';
$result = $conn->query($sql);
print_r($result);
it always gives me an empty result. for any tables. same result. it's always empty. what did I missed here? is it possible that server just give me an access to read the database structure only, but not the data?
thank you.
On your select statement, you are missing the 'from' clause.
select * from wp_ps_product_sku;

Error displaying rows from MySQL tables

I am trying to get rows from a table when a condition is satisfied (status = 'no transit') but nothing shows up even when rows are supposed to show up (count is 1 and more).
if($query['num'] == 0){
echo "<p>No shopping orders on transit</p>";
}else{
$sql = "SELECT *, FORMAT(total, 0) AS total, FORMAT(grand_total, 0) AS grand_total FROM shipping_details WHERE status = 'no transit' ORDER BY order_id DESC";
foreach ($db->query($sql) AS $query){
echo" Show some results ";
$select = "SELECT * FROM shipping_order WHERE order_id = :order_id";
foreach ($db->query($select, array('order_id' => $query['order_id'])) AS $items){
echo"
Some results
";
//Foreach ends
}
}
}
You don't show enough that we can tell which codebase you use to connect to your DB (MySQLi, mysql_, or PDO), so the code below may need some tweaking.
The problem is basically that you never retrieve your database results. Instead you try to loop through the query execution itself.
Change
$sql = "SELECT *...";
foreach ($db->query($sql) AS $query)...
To
$sql = "SELECT *...";
$result = $db->query($sql); //execute the query
if(!$result) die($db->error); //exit and show error if query failed
//now we can fetch the results one at a time and loop through them
//this line may need to be adjusted if you're not using MySQLi
while($row = $result->fetch_assoc())...
Within the while loop, $row will contain the values from the DB record. Use print_r($row) to learn its shape.
It is not working, because you forgot to use prepare and execute methods from pdoStatemnt class.
See below:
$stmt = $db->prepare("SELECT * FROM shipping_order WHERE order_id = :order_id");
$stmt->execute(array('order_id' => $query['order_id']));
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)){
echo"
Some results
";
//Foreach ends
}

PHP - Insert SQL on while loop

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']))));
}

No results showing for mysql select all

Hello guys i am trying to show all the users pokemon were the table belongsto = there username here is my code
i have a connect on top of this has well
// Get all the data from the "example" table
$result = "SELECT * FROM user_pokemon WHERE
belongsto='".$_SESSION['username']."'
AND (slot='0')'";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo $row['pokemon'];
echo $row['id'];
}
i have print red the username and there username is in the username session .
i think i mite be missing a ' or something i add or mysql at the end of the query but then the pages dies with no error
You are not running the query and have an error in it. And you're not escaping strings going into query.
A proper version of the code would be
// escape a string going to query.
$username = mysql_real_escape_string($_SESSION['username']);
// create a query
$sql = "SELECT * FROM user_pokemon WHERE belongsto='$username' AND slot=0";
// run a query and output possible error for debugging purposes.
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
// keep getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo $row['pokemon'];
echo $row['id'];
}
It appears to me that the final query would be:
SELECT * FROM user_pokemon WHERE belongsto='NAME' AND (slot='0')'
where NAME is the name you pass in. If that is the case, there is an extra single quote at the end. I presume you are getting a SQL error?

Categories