I need to update the initial values of a mysql column, a tokens column, at the beginning, those values are all null, then, they need to be updated, with a tokens generating function, how am doing it, it just doesn´t updates any values, see:
$query = "SELECT `id` FROM `acuses_recibo` WHERE `id_envio`=101 AND `token` IS NULL";
$result = mysqli_query($conn, $query);
here I select the id´s of those null tokens for an specific id_envio, then
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){//as long as there are token null values
foreach($row as $id=>$row['id']){
$indice = $row['id'];
$v=getToken(32);
echo $v.PHP_EOL;
echo "id es: ".$row['id'].PHP_EOL;
$queryDos = "UPDATE `acuses_recibo` SET `token`={$v} WHERE `id`={$indice} ";
mysqli_query($conn, $queryDos);
}
where getToken(32) calculates a token of length 32, this way no token is updated, the only way they get updated is if I set tokenin $queryDos to a fixed value, how could I remedy this in such a way that every token value gets updated? thanx i.a.
This is how I solved it, I separated the problem in two parts, the first just selects all the id´s for a specific id_envio as follows
$query = "SELECT `id` FROM `acuses_recibo` WHERE `id_envio`=101 AND `token` IS NULL";
$result = mysqli_query($conn, $query);
// an arrays is created and used to store the id´s selected
$members = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$members[] = array('id'=> $row['id']);
}
// the connection is then closed, something I found on mysql not being explicitly multiconnection
mysqli_close($conn);
// then a new connection is setup
$connDos = mysqli_connect($servername, $username, $password, $database);
Now, the token values are updated as follows, please note that $indice has to be cast to int type because the array fetched returns strings
foreach($members as $m){
$indice = $m["id"];
$indice = intval($indice);
$voken=getToken(32);
$queryDos = " UPDATE `acuses_recibo` SET `token`='{$voken}' WHERE `id`='{$indice}' ";
if (mysqli_query($connDos, $queryDos)) {
echo "Record updated successfully".PHP_EOL;
} else {
echo "Error updating record: " . mysqli_error($connDos).PHP_EOL;
}
}
then, the second connection is closed
mysqli_close($connDos);
and this is how I could update the token values to their calculated values. I hope it helps somebody.
Related
I am taking a users input and storing it in a database, however I want to be able to update the records if a user adds more information. So I want to search the database find the server with the same name and update the the last downtime and the number of downtimes.
$connect = mysqli_connect("localhost", "Username", "Password","Test_downtime");
if (!$connect)
{
die("Connection failed: " . mysqli_connect_error());
}else
{
echo "Connected successfully\n";
}
$servername = $_GET["server_name"];
$downtime = $_GET["downtime"];
$time_now = time();
$result = mysqli_query($connect, "SELECT COUNT(*) FROM `Test_downtime`.`Downtime` WHERE `Server_Name` = '$servername'");
$row = mysqli_fetch_array($result);
// If no downtime have been reported before
if ($row[0] == 0){
$sql = mysqli_query($connect, "INSERT INTO `Test_downtime`.`Downtime` (ID, Server_name, First_downtime, Last_downtime, Num_of_downtime,Total_downtime) VALUES (NULL, '$servername', '$time_now','$time_now',1,'$downtime'); ");
if ($sql==true) {
echo $servername . " has has its first downtime recorded\n";
}
}
//If users is already in the database
else{
$numdowntime = ($row["Num_of_downtime"] + 1);
$id = ($row["ID"]);
$sqlupdate = "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'";
if ($sqlupdate == TRUE) {
echo "Oh No! " . $servername . " has had ". $numdowntime ." of downtimes" ;
}
}
?>
The program works fine if the server is not already in the database, the problems arise if the server is already in the database. I get the message saying it has been updated yet nothing happens to the database. How do i make it so it search and updates the records for the searched item.
So nothing append since you do not execute the sql statement ^^
Take a look here :
$sqlupdate = "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'";
You need to use :
$sql = mysqli_query($connect, $sqlupdate);
Just after it in order to execute it.
Or at least change it to
$sqlupdate = mysqli_query($connect, "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'" );
Btw there is other problem but here is the main one [check out the other answer in order to found another one ]
you are fetching the result as indexed array
mysqli_fetch_array($result);
and here you are accessing results as associative array
$numdowntime = ($row["Num_of_downtime"] + 1);
change your query to
mysqli_fetch_assoc($result);
use
mysqli_num_rows($result);
to checking if you have any data
change
if ($row[0] == 0){}
to
if(mysqli_num_rows($result) ==0){}
A good approach for increasing a count in a column is using SQL to increase that.
$sqlupdate = mysqli_query($connect, "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = (`Num_of_downtime` + 1), `Last_downtime` = now() WHERE `Server_Name` = '$servername'" );
This way you can skip your $numdowntime calculation, and the result is more accurate.
In your current setup, two users may fire the event at the same time, they both retrieve the same number from the database (ie. 9), both increasing it with one (ie. 10), and writing the same number in the database.
Making your count one short of the actual count.
SQL takes care of this for you by locking rows, and you are left with a more accurate result using less logic :)
You miss the mysqli_query() function, which actually queries the database.
$sqlupdate = mysqli_query("
UPDATE `Test_downtime`.`Downtime`
SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now()
WHERE `Server_Name` = '$servername'"
);
I'm taking data from mysql database table. The table have ID and "POST" columns. I've ordered posts by id's from bottom so i always have the newest post on the first place. But when i want to echo specific post (eg. with id 5) i can't echo it with $col = mysqli_fetch_array($result); echo $col;. I've tried with foreach loop but it echo's all posts. So I thought if i could put them into array with foreach loop it would do the job.
$sql = "SELECT * FROM `post` ORDER BY `id` DESC";
$result = mysqli_query($con, $sql);
$col = mysqli_fetch_array($result);
foreach($col as $cols) {
}
I've tried a lot of things and spent a lot of time on research but still don't have idea how to do it.
Thanks for your ideas and help.
$sql = "SELECT * FROM `post` ORDER BY `id` DESC";
$result = mysqli_query($con, $sql);
$col = mysqli_fetch_array($result);
foreach($col as $cols) {
if($col['id'] == 5) {
print_r($col);
}
}
mysqli_fetch_array fetchs a result row as an associative, a numeric array, or both.
You need to specify the name of the column you want to print out.
Because you may have more than one row in your result set, you should use a loop (while) like so:
while ($row = mysqli_fetch_array($result)) {
echo $row['POST']; // 'POST' here is the name of the column you want to print out
}
Hope this helps!
UPDATED:
If you want to get a specific post, you have to change your SQL to something like this:
$sql = "SELECT * FROM `post` WHERE `id` = $wanted_post_id";
I'm new to both PHP & mySQL, but I suspect some apostrophe related bug here (maybe).
For some reason the first query always seems to return null because the
echo "result: $result\n";
never prints any data. At the first call that is expected, but at the second call the player has been added to the db. My database works in the sense that I can see that rows with correct ids are added to the database (via phpMyAdmin).
Can you help me spot the error?
<?php
require_once('Db.php');
$db = new Db();
// Quote and escape form submitted values
$id = $db->quote($_POST['id']);
$score = $db->quote($_POST['score']);
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = `$id`");
echo "result: $result\n"; // Never prints any data
if($result->num_rows == 0) {
// Row not found. Create it!
$result = $db->query("INSERT INTO `xxxxxx`.`Player` (`id`,`score`) VALUES (" . $id . "," . 0 . ")");
}
?>
First, drop those backticks from id in WHERE clause, otherwise it will take the field name from id column instead of 'id'.
Then you need to fetch data from $result:
$result = $db->query("SELECT id FROM `xxxxxx`.`Player` WHERE id = '$id'");
$row = $result->fetch_array();
echo $row['id'];
Or if there are more rows than one:
while($row = $result->fetch_array())
{
echo $row['id'];
}
You are using backticks in your query for $id. Remove them and try again.
Your query should be
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = $id");
OR
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = ".$id."");
Basically, I have been having some trouble with sending a request to a MySQL server and receiving the data back and checking if a user is an Admin or just a User.
Admin = 1
User = 0
<?php
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`";
$checkAdmin = $checkAdminQuery
mysqli_query = $checkAdmin;
if ($checkAdmin == 1) {
echo '<h1>Working!</h1>';
}else {
echo '<h1>Not working!</h1>';
}
?>
Sorry that this may not be as much info needed, I am currently new to Stack Overflow.
Firstly, your SQL query is wrong
SELECT * FROM `users` WHERE `admin`
It's missing the rest of the WHERE clause
SELECT * FROM `users` WHERE `admin` = 1
Then you're going to need fetch the result from the query results. You're not even running the query
$resultSet = mysqli_query($checkAdminQuery)
Then from there, you'll want to extract the value.
while($row = mysqli_fetch_assoc($resultSet))
{
//do stuff
}
These are the initial problems I see, I'll continue to analyze and find more if needed.
See the documentation here
http://php.net/manual/en/book.mysqli.php
You need to have something like user id if you want to check someone in database. For example if you have user id stored in session
<?php
// 1. start session
session_start();
// 2. connect to db
$link = mysqli_connect('host', 'user', 'pass', 'database');
// 3. get user
$checkAdminQuery = mysqli_query($link, "SELECT * FROM `users` WHERE `id_user` = " . $_SESSION['id_user'] );
// 4. fetch from result
$result = mysqli_fetch_assoc($checkAdminQuery);
// 5. if column in database is called admin test it like this
if ($result['admin'] == 1) {
echo '<h1>Is admin!</h1>';
}else {
echo '<h1>Not working!</h1>';
}
?>
// get all admin users (assumes database already connected)
$rtn = array();
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`=1";
$result = mysqli_query($dbcon,$checkAdminQuery) or die(mysqli_error($dbconn));
while($row = mysqli_fetch_array($result)){
$rtn[] = $row;
}
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`"; !!!!
where what ? you need to specify where job = 'admin' or where name ='admin'
you need to specify the column name where you are adding the admin string
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";
}